babylon.max.js 3.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348
  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 serialize(sourceName) {
  4681. return generateSerializableMember(0, sourceName); // value member
  4682. }
  4683. BABYLON.serialize = serialize;
  4684. function serializeAsTexture(sourceName) {
  4685. return generateSerializableMember(1, sourceName); // texture member
  4686. }
  4687. BABYLON.serializeAsTexture = serializeAsTexture;
  4688. function serializeAsColor3(sourceName) {
  4689. return generateSerializableMember(2, sourceName); // color3 member
  4690. }
  4691. BABYLON.serializeAsColor3 = serializeAsColor3;
  4692. function serializeAsFresnelParameters(sourceName) {
  4693. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4694. }
  4695. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4696. function serializeAsVector2(sourceName) {
  4697. return generateSerializableMember(4, sourceName); // vector2 member
  4698. }
  4699. BABYLON.serializeAsVector2 = serializeAsVector2;
  4700. function serializeAsVector3(sourceName) {
  4701. return generateSerializableMember(5, sourceName); // vector3 member
  4702. }
  4703. BABYLON.serializeAsVector3 = serializeAsVector3;
  4704. function serializeAsMeshReference(sourceName) {
  4705. return generateSerializableMember(6, sourceName); // mesh reference member
  4706. }
  4707. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4708. function serializeAsColorCurves(sourceName) {
  4709. return generateSerializableMember(7, sourceName); // color curves
  4710. }
  4711. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4712. var SerializationHelper = (function () {
  4713. function SerializationHelper() {
  4714. }
  4715. SerializationHelper.Serialize = function (entity, serializationObject) {
  4716. if (!serializationObject) {
  4717. serializationObject = {};
  4718. }
  4719. // Tags
  4720. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4721. // Properties
  4722. for (var property in entity.__serializableMembers) {
  4723. var propertyDescriptor = entity.__serializableMembers[property];
  4724. var targetPropertyName = propertyDescriptor.sourceName || property;
  4725. var propertyType = propertyDescriptor.type;
  4726. var sourceProperty = entity[property];
  4727. if (sourceProperty !== undefined && sourceProperty !== null) {
  4728. switch (propertyType) {
  4729. case 0:
  4730. serializationObject[targetPropertyName] = sourceProperty;
  4731. break;
  4732. case 1:
  4733. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4734. break;
  4735. case 2:
  4736. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4737. break;
  4738. case 3:
  4739. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4740. break;
  4741. case 4:
  4742. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4743. break;
  4744. case 5:
  4745. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4746. break;
  4747. case 6:
  4748. serializationObject[targetPropertyName] = sourceProperty.id;
  4749. break;
  4750. case 7:
  4751. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4752. break;
  4753. }
  4754. }
  4755. }
  4756. return serializationObject;
  4757. };
  4758. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4759. var destination = creationFunction();
  4760. // Tags
  4761. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4762. // Properties
  4763. for (var property in destination.__serializableMembers) {
  4764. var propertyDescriptor = destination.__serializableMembers[property];
  4765. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4766. var propertyType = propertyDescriptor.type;
  4767. if (sourceProperty !== undefined && sourceProperty !== null) {
  4768. switch (propertyType) {
  4769. case 0:
  4770. destination[property] = sourceProperty;
  4771. break;
  4772. case 1:
  4773. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4774. break;
  4775. case 2:
  4776. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4777. break;
  4778. case 3:
  4779. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4780. break;
  4781. case 4:
  4782. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4783. break;
  4784. case 5:
  4785. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4786. break;
  4787. case 6:
  4788. destination[property] = scene.getLastMeshByID(sourceProperty);
  4789. break;
  4790. case 7:
  4791. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4792. break;
  4793. }
  4794. }
  4795. }
  4796. return destination;
  4797. };
  4798. SerializationHelper.Clone = function (creationFunction, source) {
  4799. var destination = creationFunction();
  4800. // Tags
  4801. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4802. // Properties
  4803. for (var property in destination.__serializableMembers) {
  4804. var propertyDescriptor = destination.__serializableMembers[property];
  4805. var sourceProperty = source[property];
  4806. var propertyType = propertyDescriptor.type;
  4807. if (sourceProperty !== undefined && sourceProperty !== null) {
  4808. switch (propertyType) {
  4809. case 0: // Value
  4810. case 6:
  4811. destination[property] = sourceProperty;
  4812. break;
  4813. case 1: // Texture
  4814. case 2: // Color3
  4815. case 3: // FresnelParameters
  4816. case 4: // Vector2
  4817. case 5: // Vector3
  4818. case 7:
  4819. destination[property] = sourceProperty.clone();
  4820. break;
  4821. }
  4822. }
  4823. }
  4824. return destination;
  4825. };
  4826. return SerializationHelper;
  4827. }());
  4828. BABYLON.SerializationHelper = SerializationHelper;
  4829. })(BABYLON || (BABYLON = {}));
  4830. //# sourceMappingURL=babylon.decorators.js.map
  4831. var BABYLON;
  4832. (function (BABYLON) {
  4833. /**
  4834. * A class serves as a medium between the observable and its observers
  4835. */
  4836. var EventState = (function () {
  4837. /**
  4838. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4839. */
  4840. function EventState(mask, skipNextObservers) {
  4841. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4842. this.initalize(mask, skipNextObservers);
  4843. }
  4844. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4845. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4846. this.mask = mask;
  4847. this.skipNextObservers = skipNextObservers;
  4848. return this;
  4849. };
  4850. return EventState;
  4851. }());
  4852. BABYLON.EventState = EventState;
  4853. /**
  4854. * Represent an Observer registered to a given Observable object.
  4855. */
  4856. var Observer = (function () {
  4857. function Observer(callback, mask) {
  4858. this.callback = callback;
  4859. this.mask = mask;
  4860. }
  4861. return Observer;
  4862. }());
  4863. BABYLON.Observer = Observer;
  4864. /**
  4865. * The Observable class is a simple implementation of the Observable pattern.
  4866. * 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.
  4867. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4868. * 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).
  4869. * 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.
  4870. */
  4871. var Observable = (function () {
  4872. function Observable() {
  4873. this._observers = new Array();
  4874. this._eventState = new EventState(0);
  4875. }
  4876. /**
  4877. * Create a new Observer with the specified callback
  4878. * @param callback the callback that will be executed for that Observer
  4879. * @param mask the mask used to filter observers
  4880. * @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.
  4881. */
  4882. Observable.prototype.add = function (callback, mask, insertFirst) {
  4883. if (mask === void 0) { mask = -1; }
  4884. if (insertFirst === void 0) { insertFirst = false; }
  4885. if (!callback) {
  4886. return null;
  4887. }
  4888. var observer = new Observer(callback, mask);
  4889. if (insertFirst) {
  4890. this._observers.unshift(observer);
  4891. }
  4892. else {
  4893. this._observers.push(observer);
  4894. }
  4895. return observer;
  4896. };
  4897. /**
  4898. * Remove an Observer from the Observable object
  4899. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4900. */
  4901. Observable.prototype.remove = function (observer) {
  4902. var index = this._observers.indexOf(observer);
  4903. if (index !== -1) {
  4904. this._observers.splice(index, 1);
  4905. return true;
  4906. }
  4907. return false;
  4908. };
  4909. /**
  4910. * Remove a callback from the Observable object
  4911. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4912. */
  4913. Observable.prototype.removeCallback = function (callback) {
  4914. for (var index = 0; index < this._observers.length; index++) {
  4915. if (this._observers[index].callback === callback) {
  4916. this._observers.splice(index, 1);
  4917. return true;
  4918. }
  4919. }
  4920. return false;
  4921. };
  4922. /**
  4923. * Notify all Observers by calling their respective callback with the given data
  4924. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4925. * @param eventData
  4926. * @param mask
  4927. */
  4928. Observable.prototype.notifyObservers = function (eventData, mask) {
  4929. if (mask === void 0) { mask = -1; }
  4930. var state = this._eventState;
  4931. state.mask = mask;
  4932. state.skipNextObservers = false;
  4933. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4934. var obs = _a[_i];
  4935. if (obs.mask & mask) {
  4936. obs.callback(eventData, state);
  4937. }
  4938. if (state.skipNextObservers) {
  4939. return false;
  4940. }
  4941. }
  4942. return true;
  4943. };
  4944. /**
  4945. * return true is the Observable has at least one Observer registered
  4946. */
  4947. Observable.prototype.hasObservers = function () {
  4948. return this._observers.length > 0;
  4949. };
  4950. /**
  4951. * Clear the list of observers
  4952. */
  4953. Observable.prototype.clear = function () {
  4954. this._observers = new Array();
  4955. };
  4956. /**
  4957. * Clone the current observable
  4958. */
  4959. Observable.prototype.clone = function () {
  4960. var result = new Observable();
  4961. result._observers = this._observers.slice(0);
  4962. return result;
  4963. };
  4964. /**
  4965. * Does this observable handles observer registered with a given mask
  4966. * @param {number} trigger - the mask to be tested
  4967. * @return {boolean} whether or not one observer registered with the given mask is handeled
  4968. **/
  4969. Observable.prototype.hasSpecificMask = function (mask) {
  4970. if (mask === void 0) { mask = -1; }
  4971. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4972. var obs = _a[_i];
  4973. if (obs.mask & mask && obs.mask === mask) {
  4974. return true;
  4975. }
  4976. }
  4977. return false;
  4978. };
  4979. return Observable;
  4980. }());
  4981. BABYLON.Observable = Observable;
  4982. })(BABYLON || (BABYLON = {}));
  4983. //# sourceMappingURL=babylon.observable.js.map
  4984. var BABYLON;
  4985. (function (BABYLON) {
  4986. var Database = (function () {
  4987. function Database(urlToScene, callbackManifestChecked) {
  4988. // Handling various flavors of prefixed version of IndexedDB
  4989. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  4990. this.callbackManifestChecked = callbackManifestChecked;
  4991. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  4992. this.db = null;
  4993. this.enableSceneOffline = false;
  4994. this.enableTexturesOffline = false;
  4995. this.manifestVersionFound = 0;
  4996. this.mustUpdateRessources = false;
  4997. this.hasReachedQuota = false;
  4998. if (!Database.IDBStorageEnabled) {
  4999. this.callbackManifestChecked(true);
  5000. }
  5001. else {
  5002. this.checkManifestFile();
  5003. }
  5004. }
  5005. Database.prototype.checkManifestFile = function () {
  5006. var _this = this;
  5007. function noManifestFile() {
  5008. that.enableSceneOffline = false;
  5009. that.enableTexturesOffline = false;
  5010. that.callbackManifestChecked(false);
  5011. }
  5012. var that = this;
  5013. var timeStampUsed = false;
  5014. var manifestURL = this.currentSceneUrl + ".manifest";
  5015. var xhr = new XMLHttpRequest();
  5016. if (navigator.onLine) {
  5017. // Adding a timestamp to by-pass browsers' cache
  5018. timeStampUsed = true;
  5019. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  5020. }
  5021. xhr.open("GET", manifestURL, true);
  5022. xhr.addEventListener("load", function () {
  5023. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  5024. try {
  5025. var manifestFile = JSON.parse(xhr.response);
  5026. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  5027. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  5028. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  5029. _this.manifestVersionFound = manifestFile.version;
  5030. }
  5031. if (_this.callbackManifestChecked) {
  5032. _this.callbackManifestChecked(true);
  5033. }
  5034. }
  5035. catch (ex) {
  5036. noManifestFile();
  5037. }
  5038. }
  5039. else {
  5040. noManifestFile();
  5041. }
  5042. }, false);
  5043. xhr.addEventListener("error", function (event) {
  5044. if (timeStampUsed) {
  5045. timeStampUsed = false;
  5046. // Let's retry without the timeStamp
  5047. // It could fail when coupled with HTML5 Offline API
  5048. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  5049. xhr.open("GET", retryManifestURL, true);
  5050. xhr.send();
  5051. }
  5052. else {
  5053. noManifestFile();
  5054. }
  5055. }, false);
  5056. try {
  5057. xhr.send();
  5058. }
  5059. catch (ex) {
  5060. BABYLON.Tools.Error("Error on XHR send request.");
  5061. that.callbackManifestChecked(false);
  5062. }
  5063. };
  5064. Database.prototype.openAsync = function (successCallback, errorCallback) {
  5065. var _this = this;
  5066. function handleError() {
  5067. that.isSupported = false;
  5068. if (errorCallback)
  5069. errorCallback();
  5070. }
  5071. var that = this;
  5072. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  5073. // Your browser doesn't support IndexedDB
  5074. this.isSupported = false;
  5075. if (errorCallback)
  5076. errorCallback();
  5077. }
  5078. else {
  5079. // If the DB hasn't been opened or created yet
  5080. if (!this.db) {
  5081. this.hasReachedQuota = false;
  5082. this.isSupported = true;
  5083. var request = this.idbFactory.open("babylonjs", 1);
  5084. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  5085. request.onerror = function (event) {
  5086. handleError();
  5087. };
  5088. // executes when a version change transaction cannot complete due to other active transactions
  5089. request.onblocked = function (event) {
  5090. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  5091. handleError();
  5092. };
  5093. // DB has been opened successfully
  5094. request.onsuccess = function (event) {
  5095. _this.db = request.result;
  5096. successCallback();
  5097. };
  5098. // Initialization of the DB. Creating Scenes & Textures stores
  5099. request.onupgradeneeded = function (event) {
  5100. _this.db = (event.target).result;
  5101. try {
  5102. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  5103. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  5104. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  5105. }
  5106. catch (ex) {
  5107. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  5108. handleError();
  5109. }
  5110. };
  5111. }
  5112. else {
  5113. if (successCallback)
  5114. successCallback();
  5115. }
  5116. }
  5117. };
  5118. Database.prototype.loadImageFromDB = function (url, image) {
  5119. var _this = this;
  5120. var completeURL = Database.ReturnFullUrlLocation(url);
  5121. var saveAndLoadImage = function () {
  5122. if (!_this.hasReachedQuota && _this.db !== null) {
  5123. // the texture is not yet in the DB, let's try to save it
  5124. _this._saveImageIntoDBAsync(completeURL, image);
  5125. }
  5126. else {
  5127. image.src = url;
  5128. }
  5129. };
  5130. if (!this.mustUpdateRessources) {
  5131. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  5132. }
  5133. else {
  5134. saveAndLoadImage();
  5135. }
  5136. };
  5137. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  5138. if (this.isSupported && this.db !== null) {
  5139. var texture;
  5140. var transaction = this.db.transaction(["textures"]);
  5141. transaction.onabort = function (event) {
  5142. image.src = url;
  5143. };
  5144. transaction.oncomplete = function (event) {
  5145. var blobTextureURL;
  5146. if (texture) {
  5147. var URL = window.URL || window.webkitURL;
  5148. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  5149. image.onerror = function () {
  5150. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  5151. image.src = url;
  5152. };
  5153. image.src = blobTextureURL;
  5154. }
  5155. else {
  5156. notInDBCallback();
  5157. }
  5158. };
  5159. var getRequest = transaction.objectStore("textures").get(url);
  5160. getRequest.onsuccess = function (event) {
  5161. texture = (event.target).result;
  5162. };
  5163. getRequest.onerror = function (event) {
  5164. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  5165. image.src = url;
  5166. };
  5167. }
  5168. else {
  5169. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5170. image.src = url;
  5171. }
  5172. };
  5173. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  5174. var _this = this;
  5175. if (this.isSupported) {
  5176. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  5177. var generateBlobUrl = function () {
  5178. var blobTextureURL;
  5179. if (blob) {
  5180. var URL = window.URL || window.webkitURL;
  5181. try {
  5182. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  5183. }
  5184. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  5185. catch (ex) {
  5186. blobTextureURL = URL.createObjectURL(blob);
  5187. }
  5188. }
  5189. image.src = blobTextureURL;
  5190. };
  5191. if (Database.IsUASupportingBlobStorage) {
  5192. var xhr = new XMLHttpRequest(), blob;
  5193. xhr.open("GET", url, true);
  5194. xhr.responseType = "blob";
  5195. xhr.addEventListener("load", function () {
  5196. if (xhr.status === 200) {
  5197. // Blob as response (XHR2)
  5198. blob = xhr.response;
  5199. var transaction = _this.db.transaction(["textures"], "readwrite");
  5200. // the transaction could abort because of a QuotaExceededError error
  5201. transaction.onabort = function (event) {
  5202. try {
  5203. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5204. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5205. _this.hasReachedQuota = true;
  5206. }
  5207. }
  5208. catch (ex) { }
  5209. generateBlobUrl();
  5210. };
  5211. transaction.oncomplete = function (event) {
  5212. generateBlobUrl();
  5213. };
  5214. var newTexture = { textureUrl: url, data: blob };
  5215. try {
  5216. // Put the blob into the dabase
  5217. var addRequest = transaction.objectStore("textures").put(newTexture);
  5218. addRequest.onsuccess = function (event) {
  5219. };
  5220. addRequest.onerror = function (event) {
  5221. generateBlobUrl();
  5222. };
  5223. }
  5224. catch (ex) {
  5225. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  5226. if (ex.code === 25) {
  5227. Database.IsUASupportingBlobStorage = false;
  5228. }
  5229. image.src = url;
  5230. }
  5231. }
  5232. else {
  5233. image.src = url;
  5234. }
  5235. }, false);
  5236. xhr.addEventListener("error", function (event) {
  5237. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  5238. image.src = url;
  5239. }, false);
  5240. xhr.send();
  5241. }
  5242. else {
  5243. image.src = url;
  5244. }
  5245. }
  5246. else {
  5247. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5248. image.src = url;
  5249. }
  5250. };
  5251. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  5252. var _this = this;
  5253. var updateVersion = function (event) {
  5254. // the version is not yet in the DB or we need to update it
  5255. _this._saveVersionIntoDBAsync(url, versionLoaded);
  5256. };
  5257. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  5258. };
  5259. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  5260. var _this = this;
  5261. if (this.isSupported) {
  5262. var version;
  5263. try {
  5264. var transaction = this.db.transaction(["versions"]);
  5265. transaction.oncomplete = function (event) {
  5266. if (version) {
  5267. // If the version in the JSON file is > than the version in DB
  5268. if (_this.manifestVersionFound > version.data) {
  5269. _this.mustUpdateRessources = true;
  5270. updateInDBCallback();
  5271. }
  5272. else {
  5273. callback(version.data);
  5274. }
  5275. }
  5276. else {
  5277. _this.mustUpdateRessources = true;
  5278. updateInDBCallback();
  5279. }
  5280. };
  5281. transaction.onabort = function (event) {
  5282. callback(-1);
  5283. };
  5284. var getRequest = transaction.objectStore("versions").get(url);
  5285. getRequest.onsuccess = function (event) {
  5286. version = (event.target).result;
  5287. };
  5288. getRequest.onerror = function (event) {
  5289. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  5290. callback(-1);
  5291. };
  5292. }
  5293. catch (ex) {
  5294. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  5295. callback(-1);
  5296. }
  5297. }
  5298. else {
  5299. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5300. callback(-1);
  5301. }
  5302. };
  5303. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  5304. var _this = this;
  5305. if (this.isSupported && !this.hasReachedQuota) {
  5306. try {
  5307. // Open a transaction to the database
  5308. var transaction = this.db.transaction(["versions"], "readwrite");
  5309. // the transaction could abort because of a QuotaExceededError error
  5310. transaction.onabort = function (event) {
  5311. try {
  5312. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5313. _this.hasReachedQuota = true;
  5314. }
  5315. }
  5316. catch (ex) { }
  5317. callback(-1);
  5318. };
  5319. transaction.oncomplete = function (event) {
  5320. callback(_this.manifestVersionFound);
  5321. };
  5322. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  5323. // Put the scene into the database
  5324. var addRequest = transaction.objectStore("versions").put(newVersion);
  5325. addRequest.onsuccess = function (event) {
  5326. };
  5327. addRequest.onerror = function (event) {
  5328. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  5329. };
  5330. }
  5331. catch (ex) {
  5332. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  5333. callback(-1);
  5334. }
  5335. }
  5336. else {
  5337. callback(-1);
  5338. }
  5339. };
  5340. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  5341. var _this = this;
  5342. var completeUrl = Database.ReturnFullUrlLocation(url);
  5343. var saveAndLoadFile = function (event) {
  5344. // the scene is not yet in the DB, let's try to save it
  5345. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  5346. };
  5347. this._checkVersionFromDB(completeUrl, function (version) {
  5348. if (version !== -1) {
  5349. if (!_this.mustUpdateRessources) {
  5350. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  5351. }
  5352. else {
  5353. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  5354. }
  5355. }
  5356. else {
  5357. errorCallback();
  5358. }
  5359. });
  5360. };
  5361. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  5362. if (this.isSupported) {
  5363. var targetStore;
  5364. if (url.indexOf(".babylon") !== -1) {
  5365. targetStore = "scenes";
  5366. }
  5367. else {
  5368. targetStore = "textures";
  5369. }
  5370. var file;
  5371. var transaction = this.db.transaction([targetStore]);
  5372. transaction.oncomplete = function (event) {
  5373. if (file) {
  5374. callback(file.data);
  5375. }
  5376. else {
  5377. notInDBCallback();
  5378. }
  5379. };
  5380. transaction.onabort = function (event) {
  5381. notInDBCallback();
  5382. };
  5383. var getRequest = transaction.objectStore(targetStore).get(url);
  5384. getRequest.onsuccess = function (event) {
  5385. file = (event.target).result;
  5386. };
  5387. getRequest.onerror = function (event) {
  5388. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  5389. notInDBCallback();
  5390. };
  5391. }
  5392. else {
  5393. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5394. callback();
  5395. }
  5396. };
  5397. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  5398. var _this = this;
  5399. if (this.isSupported) {
  5400. var targetStore;
  5401. if (url.indexOf(".babylon") !== -1) {
  5402. targetStore = "scenes";
  5403. }
  5404. else {
  5405. targetStore = "textures";
  5406. }
  5407. // Create XHR
  5408. var xhr = new XMLHttpRequest(), fileData;
  5409. xhr.open("GET", url, true);
  5410. if (useArrayBuffer) {
  5411. xhr.responseType = "arraybuffer";
  5412. }
  5413. xhr.onprogress = progressCallback;
  5414. xhr.addEventListener("load", function () {
  5415. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  5416. // Blob as response (XHR2)
  5417. //fileData = xhr.responseText;
  5418. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  5419. if (!_this.hasReachedQuota) {
  5420. // Open a transaction to the database
  5421. var transaction = _this.db.transaction([targetStore], "readwrite");
  5422. // the transaction could abort because of a QuotaExceededError error
  5423. transaction.onabort = function (event) {
  5424. try {
  5425. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  5426. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  5427. _this.hasReachedQuota = true;
  5428. }
  5429. }
  5430. catch (ex) { }
  5431. callback(fileData);
  5432. };
  5433. transaction.oncomplete = function (event) {
  5434. callback(fileData);
  5435. };
  5436. var newFile;
  5437. if (targetStore === "scenes") {
  5438. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  5439. }
  5440. else {
  5441. newFile = { textureUrl: url, data: fileData };
  5442. }
  5443. try {
  5444. // Put the scene into the database
  5445. var addRequest = transaction.objectStore(targetStore).put(newFile);
  5446. addRequest.onsuccess = function (event) {
  5447. };
  5448. addRequest.onerror = function (event) {
  5449. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  5450. };
  5451. }
  5452. catch (ex) {
  5453. callback(fileData);
  5454. }
  5455. }
  5456. else {
  5457. callback(fileData);
  5458. }
  5459. }
  5460. else {
  5461. callback();
  5462. }
  5463. }, false);
  5464. xhr.addEventListener("error", function (event) {
  5465. BABYLON.Tools.Error("error on XHR request.");
  5466. callback();
  5467. }, false);
  5468. xhr.send();
  5469. }
  5470. else {
  5471. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  5472. callback();
  5473. }
  5474. };
  5475. return Database;
  5476. }());
  5477. Database.IsUASupportingBlobStorage = true;
  5478. Database.IDBStorageEnabled = true;
  5479. Database.parseURL = function (url) {
  5480. var a = document.createElement('a');
  5481. a.href = url;
  5482. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  5483. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  5484. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  5485. return absLocation;
  5486. };
  5487. Database.ReturnFullUrlLocation = function (url) {
  5488. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  5489. return (Database.parseURL(window.location.href) + url);
  5490. }
  5491. else {
  5492. return url;
  5493. }
  5494. };
  5495. BABYLON.Database = Database;
  5496. })(BABYLON || (BABYLON = {}));
  5497. //# sourceMappingURL=babylon.database.js.map
  5498. var BABYLON;
  5499. (function (BABYLON) {
  5500. var Internals;
  5501. (function (Internals) {
  5502. /*
  5503. * Based on jsTGALoader - Javascript loader for TGA file
  5504. * By Vincent Thibault
  5505. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  5506. */
  5507. var TGATools = (function () {
  5508. function TGATools() {
  5509. }
  5510. TGATools.GetTGAHeader = function (data) {
  5511. var offset = 0;
  5512. var header = {
  5513. id_length: data[offset++],
  5514. colormap_type: data[offset++],
  5515. image_type: data[offset++],
  5516. colormap_index: data[offset++] | data[offset++] << 8,
  5517. colormap_length: data[offset++] | data[offset++] << 8,
  5518. colormap_size: data[offset++],
  5519. origin: [
  5520. data[offset++] | data[offset++] << 8,
  5521. data[offset++] | data[offset++] << 8
  5522. ],
  5523. width: data[offset++] | data[offset++] << 8,
  5524. height: data[offset++] | data[offset++] << 8,
  5525. pixel_size: data[offset++],
  5526. flags: data[offset++]
  5527. };
  5528. return header;
  5529. };
  5530. TGATools.UploadContent = function (gl, data) {
  5531. // Not enough data to contain header ?
  5532. if (data.length < 19) {
  5533. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  5534. return;
  5535. }
  5536. // Read Header
  5537. var offset = 18;
  5538. var header = TGATools.GetTGAHeader(data);
  5539. // Assume it's a valid Targa file.
  5540. if (header.id_length + offset > data.length) {
  5541. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  5542. return;
  5543. }
  5544. // Skip not needed data
  5545. offset += header.id_length;
  5546. var use_rle = false;
  5547. var use_pal = false;
  5548. var use_rgb = false;
  5549. var use_grey = false;
  5550. // Get some informations.
  5551. switch (header.image_type) {
  5552. case TGATools._TYPE_RLE_INDEXED:
  5553. use_rle = true;
  5554. case TGATools._TYPE_INDEXED:
  5555. use_pal = true;
  5556. break;
  5557. case TGATools._TYPE_RLE_RGB:
  5558. use_rle = true;
  5559. case TGATools._TYPE_RGB:
  5560. use_rgb = true;
  5561. break;
  5562. case TGATools._TYPE_RLE_GREY:
  5563. use_rle = true;
  5564. case TGATools._TYPE_GREY:
  5565. use_grey = true;
  5566. break;
  5567. }
  5568. var pixel_data;
  5569. var numAlphaBits = header.flags & 0xf;
  5570. var pixel_size = header.pixel_size >> 3;
  5571. var pixel_total = header.width * header.height * pixel_size;
  5572. // Read palettes
  5573. var palettes;
  5574. if (use_pal) {
  5575. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  5576. }
  5577. // Read LRE
  5578. if (use_rle) {
  5579. pixel_data = new Uint8Array(pixel_total);
  5580. var c, count, i;
  5581. var localOffset = 0;
  5582. var pixels = new Uint8Array(pixel_size);
  5583. while (offset < pixel_total && localOffset < pixel_total) {
  5584. c = data[offset++];
  5585. count = (c & 0x7f) + 1;
  5586. // RLE pixels
  5587. if (c & 0x80) {
  5588. // Bind pixel tmp array
  5589. for (i = 0; i < pixel_size; ++i) {
  5590. pixels[i] = data[offset++];
  5591. }
  5592. // Copy pixel array
  5593. for (i = 0; i < count; ++i) {
  5594. pixel_data.set(pixels, localOffset + i * pixel_size);
  5595. }
  5596. localOffset += pixel_size * count;
  5597. }
  5598. else {
  5599. count *= pixel_size;
  5600. for (i = 0; i < count; ++i) {
  5601. pixel_data[localOffset + i] = data[offset++];
  5602. }
  5603. localOffset += count;
  5604. }
  5605. }
  5606. }
  5607. else {
  5608. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  5609. }
  5610. // Load to texture
  5611. var x_start, y_start, x_step, y_step, y_end, x_end;
  5612. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  5613. default:
  5614. case TGATools._ORIGIN_UL:
  5615. x_start = 0;
  5616. x_step = 1;
  5617. x_end = header.width;
  5618. y_start = 0;
  5619. y_step = 1;
  5620. y_end = header.height;
  5621. break;
  5622. case TGATools._ORIGIN_BL:
  5623. x_start = 0;
  5624. x_step = 1;
  5625. x_end = header.width;
  5626. y_start = header.height - 1;
  5627. y_step = -1;
  5628. y_end = -1;
  5629. break;
  5630. case TGATools._ORIGIN_UR:
  5631. x_start = header.width - 1;
  5632. x_step = -1;
  5633. x_end = -1;
  5634. y_start = 0;
  5635. y_step = 1;
  5636. y_end = header.height;
  5637. break;
  5638. case TGATools._ORIGIN_BR:
  5639. x_start = header.width - 1;
  5640. x_step = -1;
  5641. x_end = -1;
  5642. y_start = header.height - 1;
  5643. y_step = -1;
  5644. y_end = -1;
  5645. break;
  5646. }
  5647. // Load the specify method
  5648. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  5649. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  5650. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  5651. };
  5652. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5653. var image = pixel_data, colormap = palettes;
  5654. var width = header.width, height = header.height;
  5655. var color, i = 0, x, y;
  5656. var imageData = new Uint8Array(width * height * 4);
  5657. for (y = y_start; y !== y_end; y += y_step) {
  5658. for (x = x_start; x !== x_end; x += x_step, i++) {
  5659. color = image[i];
  5660. imageData[(x + width * y) * 4 + 3] = 255;
  5661. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  5662. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  5663. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  5664. }
  5665. }
  5666. return imageData;
  5667. };
  5668. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5669. var image = pixel_data;
  5670. var width = header.width, height = header.height;
  5671. var color, i = 0, x, y;
  5672. var imageData = new Uint8Array(width * height * 4);
  5673. for (y = y_start; y !== y_end; y += y_step) {
  5674. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5675. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  5676. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  5677. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  5678. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  5679. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  5680. }
  5681. }
  5682. return imageData;
  5683. };
  5684. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5685. var image = pixel_data;
  5686. var width = header.width, height = header.height;
  5687. var i = 0, x, y;
  5688. var imageData = new Uint8Array(width * height * 4);
  5689. for (y = y_start; y !== y_end; y += y_step) {
  5690. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  5691. imageData[(x + width * y) * 4 + 3] = 255;
  5692. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5693. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5694. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5695. }
  5696. }
  5697. return imageData;
  5698. };
  5699. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5700. var image = pixel_data;
  5701. var width = header.width, height = header.height;
  5702. var i = 0, x, y;
  5703. var imageData = new Uint8Array(width * height * 4);
  5704. for (y = y_start; y !== y_end; y += y_step) {
  5705. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  5706. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5707. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  5708. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  5709. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  5710. }
  5711. }
  5712. return imageData;
  5713. };
  5714. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5715. var image = pixel_data;
  5716. var width = header.width, height = header.height;
  5717. var color, i = 0, x, y;
  5718. var imageData = new Uint8Array(width * height * 4);
  5719. for (y = y_start; y !== y_end; y += y_step) {
  5720. for (x = x_start; x !== x_end; x += x_step, i++) {
  5721. color = image[i];
  5722. imageData[(x + width * y) * 4 + 0] = color;
  5723. imageData[(x + width * y) * 4 + 1] = color;
  5724. imageData[(x + width * y) * 4 + 2] = color;
  5725. imageData[(x + width * y) * 4 + 3] = 255;
  5726. }
  5727. }
  5728. return imageData;
  5729. };
  5730. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  5731. var image = pixel_data;
  5732. var width = header.width, height = header.height;
  5733. var i = 0, x, y;
  5734. var imageData = new Uint8Array(width * height * 4);
  5735. for (y = y_start; y !== y_end; y += y_step) {
  5736. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  5737. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  5738. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  5739. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  5740. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  5741. }
  5742. }
  5743. return imageData;
  5744. };
  5745. return TGATools;
  5746. }());
  5747. TGATools._TYPE_NO_DATA = 0;
  5748. TGATools._TYPE_INDEXED = 1;
  5749. TGATools._TYPE_RGB = 2;
  5750. TGATools._TYPE_GREY = 3;
  5751. TGATools._TYPE_RLE_INDEXED = 9;
  5752. TGATools._TYPE_RLE_RGB = 10;
  5753. TGATools._TYPE_RLE_GREY = 11;
  5754. TGATools._ORIGIN_MASK = 0x30;
  5755. TGATools._ORIGIN_SHIFT = 0x04;
  5756. TGATools._ORIGIN_BL = 0x00;
  5757. TGATools._ORIGIN_BR = 0x01;
  5758. TGATools._ORIGIN_UL = 0x02;
  5759. TGATools._ORIGIN_UR = 0x03;
  5760. Internals.TGATools = TGATools;
  5761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5762. })(BABYLON || (BABYLON = {}));
  5763. //# sourceMappingURL=babylon.tools.tga.js.map
  5764. var BABYLON;
  5765. (function (BABYLON) {
  5766. var SmartArray = (function () {
  5767. function SmartArray(capacity) {
  5768. this.length = 0;
  5769. this._duplicateId = 0;
  5770. this.data = new Array(capacity);
  5771. this._id = SmartArray._GlobalId++;
  5772. }
  5773. SmartArray.prototype.push = function (value) {
  5774. this.data[this.length++] = value;
  5775. if (this.length > this.data.length) {
  5776. this.data.length *= 2;
  5777. }
  5778. if (!value.__smartArrayFlags) {
  5779. value.__smartArrayFlags = {};
  5780. }
  5781. value.__smartArrayFlags[this._id] = this._duplicateId;
  5782. };
  5783. SmartArray.prototype.forEach = function (func) {
  5784. for (var index = 0; index < this.length; index++) {
  5785. func(this.data[index]);
  5786. }
  5787. };
  5788. SmartArray.prototype.pushNoDuplicate = function (value) {
  5789. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5790. return false;
  5791. }
  5792. this.push(value);
  5793. return true;
  5794. };
  5795. SmartArray.prototype.sort = function (compareFn) {
  5796. this.data.sort(compareFn);
  5797. };
  5798. SmartArray.prototype.reset = function () {
  5799. this.length = 0;
  5800. this._duplicateId++;
  5801. };
  5802. SmartArray.prototype.dispose = function () {
  5803. this.reset();
  5804. this.data.length = 0;
  5805. };
  5806. SmartArray.prototype.concat = function (array) {
  5807. if (array.length === 0) {
  5808. return;
  5809. }
  5810. if (this.length + array.length > this.data.length) {
  5811. this.data.length = (this.length + array.length) * 2;
  5812. }
  5813. for (var index = 0; index < array.length; index++) {
  5814. this.data[this.length++] = (array.data || array)[index];
  5815. }
  5816. };
  5817. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5818. if (array.length === 0) {
  5819. return;
  5820. }
  5821. if (this.length + array.length > this.data.length) {
  5822. this.data.length = (this.length + array.length) * 2;
  5823. }
  5824. for (var index = 0; index < array.length; index++) {
  5825. var item = (array.data || array)[index];
  5826. this.pushNoDuplicate(item);
  5827. }
  5828. };
  5829. SmartArray.prototype.indexOf = function (value) {
  5830. var position = this.data.indexOf(value);
  5831. if (position >= this.length) {
  5832. return -1;
  5833. }
  5834. return position;
  5835. };
  5836. return SmartArray;
  5837. }());
  5838. // Statics
  5839. SmartArray._GlobalId = 0;
  5840. BABYLON.SmartArray = SmartArray;
  5841. })(BABYLON || (BABYLON = {}));
  5842. //# sourceMappingURL=babylon.smartArray.js.map
  5843. var BABYLON;
  5844. (function (BABYLON) {
  5845. /**
  5846. * This class implement a typical dictionary using a string as key and the generic type T as value.
  5847. * The underlying implementation relies on an associative array to ensure the best performances.
  5848. * The value can be anything including 'null' but except 'undefined'
  5849. */
  5850. var StringDictionary = (function () {
  5851. function StringDictionary() {
  5852. this._count = 0;
  5853. this._data = {};
  5854. }
  5855. /**
  5856. * This will clear this dictionary and copy the content from the 'source' one.
  5857. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  5858. * @param source the dictionary to take the content from and copy to this dictionary
  5859. */
  5860. StringDictionary.prototype.copyFrom = function (source) {
  5861. var _this = this;
  5862. this.clear();
  5863. source.forEach(function (t, v) { return _this.add(t, v); });
  5864. };
  5865. /**
  5866. * Get a value based from its key
  5867. * @param key the given key to get the matching value from
  5868. * @return the value if found, otherwise undefined is returned
  5869. */
  5870. StringDictionary.prototype.get = function (key) {
  5871. var val = this._data[key];
  5872. if (val !== undefined) {
  5873. return val;
  5874. }
  5875. return undefined;
  5876. };
  5877. /**
  5878. * Get a value from its key or add it if it doesn't exist.
  5879. * This method will ensure you that a given key/data will be present in the dictionary.
  5880. * @param key the given key to get the matching value from
  5881. * @param factory the factory that will create the value if the key is not present in the dictionary.
  5882. * The factory will only be invoked if there's no data for the given key.
  5883. * @return the value corresponding to the key.
  5884. */
  5885. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  5886. var val = this.get(key);
  5887. if (val !== undefined) {
  5888. return val;
  5889. }
  5890. val = factory(key);
  5891. if (val) {
  5892. this.add(key, val);
  5893. }
  5894. return val;
  5895. };
  5896. /**
  5897. * Get a value from its key if present in the dictionary otherwise add it
  5898. * @param key the key to get the value from
  5899. * @param val if there's no such key/value pair in the dictionary add it with this value
  5900. * @return the value corresponding to the key
  5901. */
  5902. StringDictionary.prototype.getOrAdd = function (key, val) {
  5903. var curVal = this.get(key);
  5904. if (curVal !== undefined) {
  5905. return curVal;
  5906. }
  5907. this.add(key, val);
  5908. return val;
  5909. };
  5910. /**
  5911. * Check if there's a given key in the dictionary
  5912. * @param key the key to check for
  5913. * @return true if the key is present, false otherwise
  5914. */
  5915. StringDictionary.prototype.contains = function (key) {
  5916. return this._data[key] !== undefined;
  5917. };
  5918. /**
  5919. * Add a new key and its corresponding value
  5920. * @param key the key to add
  5921. * @param value the value corresponding to the key
  5922. * @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
  5923. */
  5924. StringDictionary.prototype.add = function (key, value) {
  5925. if (this._data[key] !== undefined) {
  5926. return false;
  5927. }
  5928. this._data[key] = value;
  5929. ++this._count;
  5930. return true;
  5931. };
  5932. StringDictionary.prototype.set = function (key, value) {
  5933. if (this._data[key] === undefined) {
  5934. return false;
  5935. }
  5936. this._data[key] = value;
  5937. return true;
  5938. };
  5939. /**
  5940. * Get the element of the given key and remove it from the dictionary
  5941. * @param key
  5942. */
  5943. StringDictionary.prototype.getAndRemove = function (key) {
  5944. var val = this.get(key);
  5945. if (val !== undefined) {
  5946. delete this._data[key];
  5947. --this._count;
  5948. return val;
  5949. }
  5950. return null;
  5951. };
  5952. /**
  5953. * Remove a key/value from the dictionary.
  5954. * @param key the key to remove
  5955. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  5956. */
  5957. StringDictionary.prototype.remove = function (key) {
  5958. if (this.contains(key)) {
  5959. delete this._data[key];
  5960. --this._count;
  5961. return true;
  5962. }
  5963. return false;
  5964. };
  5965. /**
  5966. * Clear the whole content of the dictionary
  5967. */
  5968. StringDictionary.prototype.clear = function () {
  5969. this._data = {};
  5970. this._count = 0;
  5971. };
  5972. Object.defineProperty(StringDictionary.prototype, "count", {
  5973. get: function () {
  5974. return this._count;
  5975. },
  5976. enumerable: true,
  5977. configurable: true
  5978. });
  5979. /**
  5980. * Execute a callback on each key/val of the dictionary.
  5981. * Note that you can remove any element in this dictionary in the callback implementation
  5982. * @param callback the callback to execute on a given key/value pair
  5983. */
  5984. StringDictionary.prototype.forEach = function (callback) {
  5985. for (var cur in this._data) {
  5986. var val = this._data[cur];
  5987. callback(cur, val);
  5988. }
  5989. };
  5990. /**
  5991. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  5992. * If the callback returns null or undefined the method will iterate to the next key/value pair
  5993. * Note that you can remove any element in this dictionary in the callback implementation
  5994. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  5995. */
  5996. StringDictionary.prototype.first = function (callback) {
  5997. for (var cur in this._data) {
  5998. var val = this._data[cur];
  5999. var res = callback(cur, val);
  6000. if (res) {
  6001. return res;
  6002. }
  6003. }
  6004. return null;
  6005. };
  6006. return StringDictionary;
  6007. }());
  6008. BABYLON.StringDictionary = StringDictionary;
  6009. })(BABYLON || (BABYLON = {}));
  6010. //# sourceMappingURL=babylon.stringDictionary.js.map
  6011. var BABYLON;
  6012. (function (BABYLON) {
  6013. // Screenshots
  6014. var screenshotCanvas;
  6015. var cloneValue = function (source, destinationObject) {
  6016. if (!source)
  6017. return null;
  6018. if (source instanceof BABYLON.Mesh) {
  6019. return null;
  6020. }
  6021. if (source instanceof BABYLON.SubMesh) {
  6022. return source.clone(destinationObject);
  6023. }
  6024. else if (source.clone) {
  6025. return source.clone();
  6026. }
  6027. return null;
  6028. };
  6029. var Tools = (function () {
  6030. function Tools() {
  6031. }
  6032. ;
  6033. Tools.Instantiate = function (className) {
  6034. var arr = className.split(".");
  6035. var fn = (window || this);
  6036. for (var i = 0, len = arr.length; i < len; i++) {
  6037. fn = fn[arr[i]];
  6038. }
  6039. if (typeof fn !== "function") {
  6040. return null;
  6041. }
  6042. return fn;
  6043. };
  6044. Tools.SetImmediate = function (action) {
  6045. if (window.setImmediate) {
  6046. window.setImmediate(action);
  6047. }
  6048. else {
  6049. setTimeout(action, 1);
  6050. }
  6051. };
  6052. Tools.IsExponentOfTwo = function (value) {
  6053. var count = 1;
  6054. do {
  6055. count *= 2;
  6056. } while (count < value);
  6057. return count === value;
  6058. };
  6059. Tools.GetExponentOfTwo = function (value, max) {
  6060. var count = 1;
  6061. do {
  6062. count *= 2;
  6063. } while (count < value);
  6064. if (count > max)
  6065. count = max;
  6066. return count;
  6067. };
  6068. Tools.GetFilename = function (path) {
  6069. var index = path.lastIndexOf("/");
  6070. if (index < 0)
  6071. return path;
  6072. return path.substring(index + 1);
  6073. };
  6074. Tools.GetDOMTextContent = function (element) {
  6075. var result = "";
  6076. var child = element.firstChild;
  6077. while (child) {
  6078. if (child.nodeType === 3) {
  6079. result += child.textContent;
  6080. }
  6081. child = child.nextSibling;
  6082. }
  6083. return result;
  6084. };
  6085. Tools.ToDegrees = function (angle) {
  6086. return angle * 180 / Math.PI;
  6087. };
  6088. Tools.ToRadians = function (angle) {
  6089. return angle * Math.PI / 180;
  6090. };
  6091. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6092. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6093. var output = "";
  6094. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6095. var i = 0;
  6096. var bytes = new Uint8Array(buffer);
  6097. while (i < bytes.length) {
  6098. chr1 = bytes[i++];
  6099. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6100. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6101. enc1 = chr1 >> 2;
  6102. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6103. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6104. enc4 = chr3 & 63;
  6105. if (isNaN(chr2)) {
  6106. enc3 = enc4 = 64;
  6107. }
  6108. else if (isNaN(chr3)) {
  6109. enc4 = 64;
  6110. }
  6111. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6112. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6113. }
  6114. return "data:image/png;base64," + output;
  6115. };
  6116. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6117. if (bias === void 0) { bias = null; }
  6118. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6119. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6120. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6121. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6122. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6123. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6124. }
  6125. if (bias) {
  6126. minimum.x -= minimum.x * bias.x + bias.y;
  6127. minimum.y -= minimum.y * bias.x + bias.y;
  6128. minimum.z -= minimum.z * bias.x + bias.y;
  6129. maximum.x += maximum.x * bias.x + bias.y;
  6130. maximum.y += maximum.y * bias.x + bias.y;
  6131. maximum.z += maximum.z * bias.x + bias.y;
  6132. }
  6133. return {
  6134. minimum: minimum,
  6135. maximum: maximum
  6136. };
  6137. };
  6138. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6139. if (bias === void 0) { bias = null; }
  6140. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6141. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6142. if (!stride) {
  6143. stride = 3;
  6144. }
  6145. for (var index = start; index < start + count; index++) {
  6146. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6147. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6148. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6149. }
  6150. if (bias) {
  6151. minimum.x -= minimum.x * bias.x + bias.y;
  6152. minimum.y -= minimum.y * bias.x + bias.y;
  6153. minimum.z -= minimum.z * bias.x + bias.y;
  6154. maximum.x += maximum.x * bias.x + bias.y;
  6155. maximum.y += maximum.y * bias.x + bias.y;
  6156. maximum.z += maximum.z * bias.x + bias.y;
  6157. }
  6158. return {
  6159. minimum: minimum,
  6160. maximum: maximum
  6161. };
  6162. };
  6163. Tools.Vector2ArrayFeeder = function (array) {
  6164. return function (index) {
  6165. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6166. var length = isFloatArray ? array.length / 2 : array.length;
  6167. if (index >= length) {
  6168. return null;
  6169. }
  6170. if (isFloatArray) {
  6171. var fa = array;
  6172. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6173. }
  6174. var a = array;
  6175. return a[index];
  6176. };
  6177. };
  6178. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6179. if (bias === void 0) { bias = null; }
  6180. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6181. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6182. var i = 0;
  6183. var cur = feeder(i++);
  6184. while (cur) {
  6185. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6186. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6187. cur = feeder(i++);
  6188. }
  6189. if (bias) {
  6190. minimum.x -= minimum.x * bias.x + bias.y;
  6191. minimum.y -= minimum.y * bias.x + bias.y;
  6192. maximum.x += maximum.x * bias.x + bias.y;
  6193. maximum.y += maximum.y * bias.x + bias.y;
  6194. }
  6195. return {
  6196. minimum: minimum,
  6197. maximum: maximum
  6198. };
  6199. };
  6200. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6201. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6202. return undefined;
  6203. return Array.isArray(obj) ? obj : [obj];
  6204. };
  6205. // Misc.
  6206. Tools.GetPointerPrefix = function () {
  6207. var eventPrefix = "pointer";
  6208. // Check if pointer events are supported
  6209. if (!window.PointerEvent && !navigator.pointerEnabled) {
  6210. eventPrefix = "mouse";
  6211. }
  6212. return eventPrefix;
  6213. };
  6214. /**
  6215. * @param func - the function to be called
  6216. * @param requester - the object that will request the next frame. Falls back to window.
  6217. */
  6218. Tools.QueueNewFrame = function (func, requester) {
  6219. if (requester === void 0) { requester = window; }
  6220. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  6221. /*if(requester.isPresenting) {
  6222. return;
  6223. } else*/ if (requester.requestAnimationFrame)
  6224. requester.requestAnimationFrame(func);
  6225. else if (requester.msRequestAnimationFrame)
  6226. requester.msRequestAnimationFrame(func);
  6227. else if (requester.webkitRequestAnimationFrame)
  6228. requester.webkitRequestAnimationFrame(func);
  6229. else if (requester.mozRequestAnimationFrame)
  6230. requester.mozRequestAnimationFrame(func);
  6231. else if (requester.oRequestAnimationFrame)
  6232. requester.oRequestAnimationFrame(func);
  6233. else {
  6234. window.setTimeout(func, 16);
  6235. }
  6236. };
  6237. Tools.RequestFullscreen = function (element) {
  6238. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6239. if (!requestFunction)
  6240. return;
  6241. requestFunction.call(element);
  6242. };
  6243. Tools.ExitFullscreen = function () {
  6244. if (document.exitFullscreen) {
  6245. document.exitFullscreen();
  6246. }
  6247. else if (document.mozCancelFullScreen) {
  6248. document.mozCancelFullScreen();
  6249. }
  6250. else if (document.webkitCancelFullScreen) {
  6251. document.webkitCancelFullScreen();
  6252. }
  6253. else if (document.msCancelFullScreen) {
  6254. document.msCancelFullScreen();
  6255. }
  6256. };
  6257. Tools.SetCorsBehavior = function (url, img) {
  6258. if (Tools.CorsBehavior) {
  6259. switch (typeof (Tools.CorsBehavior)) {
  6260. case "function":
  6261. var result = Tools.CorsBehavior(url);
  6262. if (result) {
  6263. img.crossOrigin = result;
  6264. }
  6265. break;
  6266. case "string":
  6267. default:
  6268. img.crossOrigin = Tools.CorsBehavior;
  6269. break;
  6270. }
  6271. }
  6272. };
  6273. // External files
  6274. Tools.CleanUrl = function (url) {
  6275. url = url.replace(/#/mg, "%23");
  6276. return url;
  6277. };
  6278. Tools.LoadImage = function (url, onload, onerror, database) {
  6279. if (url instanceof ArrayBuffer) {
  6280. url = Tools.EncodeArrayBufferTobase64(url);
  6281. }
  6282. url = Tools.CleanUrl(url);
  6283. var img = new Image();
  6284. if (url.substr(0, 5) !== "data:") {
  6285. Tools.SetCorsBehavior(url, img);
  6286. }
  6287. img.onload = function () {
  6288. onload(img);
  6289. };
  6290. img.onerror = function (err) {
  6291. Tools.Error("Error while trying to load image: " + url);
  6292. if (Tools.UseFallbackTexture) {
  6293. img.src = Tools.fallbackTexture;
  6294. onload(img);
  6295. }
  6296. else {
  6297. onerror();
  6298. }
  6299. };
  6300. var noIndexedDB = function () {
  6301. img.src = url;
  6302. };
  6303. var loadFromIndexedDB = function () {
  6304. database.loadImageFromDB(url, img);
  6305. };
  6306. //ANY database to do!
  6307. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6308. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6309. }
  6310. else {
  6311. if (url.indexOf("file:") === -1) {
  6312. noIndexedDB();
  6313. }
  6314. else {
  6315. var textureName = url.substring(5).toLowerCase();
  6316. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  6317. try {
  6318. var blobURL;
  6319. try {
  6320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  6321. }
  6322. catch (ex) {
  6323. // Chrome doesn't support oneTimeOnly parameter
  6324. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  6325. }
  6326. img.src = blobURL;
  6327. }
  6328. catch (e) {
  6329. img.src = null;
  6330. }
  6331. }
  6332. else {
  6333. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6334. img.src = Tools.fallbackTexture;
  6335. }
  6336. }
  6337. }
  6338. return img;
  6339. };
  6340. //ANY
  6341. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6342. url = Tools.CleanUrl(url);
  6343. var noIndexedDB = function () {
  6344. var request = new XMLHttpRequest();
  6345. var loadUrl = Tools.BaseUrl + url;
  6346. request.open('GET', loadUrl, true);
  6347. if (useArrayBuffer) {
  6348. request.responseType = "arraybuffer";
  6349. }
  6350. request.onprogress = progressCallBack;
  6351. request.onreadystatechange = function () {
  6352. if (request.readyState === 4) {
  6353. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6354. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  6355. callback(!useArrayBuffer ? request.responseText : request.response);
  6356. }
  6357. else {
  6358. if (onError) {
  6359. onError();
  6360. }
  6361. else {
  6362. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  6363. }
  6364. }
  6365. }
  6366. };
  6367. request.send(null);
  6368. };
  6369. var loadFromIndexedDB = function () {
  6370. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6371. };
  6372. if (url.indexOf("file:") !== -1) {
  6373. var fileName = url.substring(5).toLowerCase();
  6374. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6375. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6376. }
  6377. else {
  6378. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  6379. }
  6380. }
  6381. else {
  6382. // Caching all files
  6383. if (database && database.enableSceneOffline) {
  6384. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6385. }
  6386. else {
  6387. noIndexedDB();
  6388. }
  6389. }
  6390. };
  6391. /**
  6392. * Load a script (identified by an url). When the url returns, the
  6393. * content of this file is added into a new script element, attached to the DOM (body element)
  6394. */
  6395. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6396. var head = document.getElementsByTagName('head')[0];
  6397. var script = document.createElement('script');
  6398. script.type = 'text/javascript';
  6399. script.src = scriptUrl;
  6400. var self = this;
  6401. script.onload = function () {
  6402. if (onSuccess) {
  6403. onSuccess();
  6404. }
  6405. };
  6406. script.onerror = function () {
  6407. if (onError) {
  6408. onError();
  6409. }
  6410. };
  6411. head.appendChild(script);
  6412. };
  6413. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6414. var reader = new FileReader();
  6415. reader.onload = function (e) {
  6416. //target doesn't have result from ts 1.3
  6417. callback(e.target['result']);
  6418. };
  6419. reader.onprogress = progressCallback;
  6420. reader.readAsDataURL(fileToLoad);
  6421. };
  6422. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6423. var reader = new FileReader();
  6424. reader.onerror = function (e) {
  6425. Tools.Log("Error while reading file: " + fileToLoad.name);
  6426. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6427. };
  6428. reader.onload = function (e) {
  6429. //target doesn't have result from ts 1.3
  6430. callback(e.target['result']);
  6431. };
  6432. reader.onprogress = progressCallBack;
  6433. if (!useArrayBuffer) {
  6434. // Asynchronous read
  6435. reader.readAsText(fileToLoad);
  6436. }
  6437. else {
  6438. reader.readAsArrayBuffer(fileToLoad);
  6439. }
  6440. };
  6441. //returns a downloadable url to a file content.
  6442. Tools.FileAsURL = function (content) {
  6443. var fileBlob = new Blob([content]);
  6444. var url = window.URL || window.webkitURL;
  6445. var link = url.createObjectURL(fileBlob);
  6446. return link;
  6447. };
  6448. // Misc.
  6449. Tools.Format = function (value, decimals) {
  6450. if (decimals === void 0) { decimals = 2; }
  6451. return value.toFixed(decimals);
  6452. };
  6453. Tools.CheckExtends = function (v, min, max) {
  6454. if (v.x < min.x)
  6455. min.x = v.x;
  6456. if (v.y < min.y)
  6457. min.y = v.y;
  6458. if (v.z < min.z)
  6459. min.z = v.z;
  6460. if (v.x > max.x)
  6461. max.x = v.x;
  6462. if (v.y > max.y)
  6463. max.y = v.y;
  6464. if (v.z > max.z)
  6465. max.z = v.z;
  6466. };
  6467. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6468. for (var prop in source) {
  6469. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6470. continue;
  6471. }
  6472. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6473. continue;
  6474. }
  6475. var sourceValue = source[prop];
  6476. var typeOfSourceValue = typeof sourceValue;
  6477. if (typeOfSourceValue === "function") {
  6478. continue;
  6479. }
  6480. if (typeOfSourceValue === "object") {
  6481. if (sourceValue instanceof Array) {
  6482. destination[prop] = [];
  6483. if (sourceValue.length > 0) {
  6484. if (typeof sourceValue[0] == "object") {
  6485. for (var index = 0; index < sourceValue.length; index++) {
  6486. var clonedValue = cloneValue(sourceValue[index], destination);
  6487. if (destination[prop].indexOf(clonedValue) === -1) {
  6488. destination[prop].push(clonedValue);
  6489. }
  6490. }
  6491. }
  6492. else {
  6493. destination[prop] = sourceValue.slice(0);
  6494. }
  6495. }
  6496. }
  6497. else {
  6498. destination[prop] = cloneValue(sourceValue, destination);
  6499. }
  6500. }
  6501. else {
  6502. destination[prop] = sourceValue;
  6503. }
  6504. }
  6505. };
  6506. Tools.IsEmpty = function (obj) {
  6507. for (var i in obj) {
  6508. return false;
  6509. }
  6510. return true;
  6511. };
  6512. Tools.RegisterTopRootEvents = function (events) {
  6513. for (var index = 0; index < events.length; index++) {
  6514. var event = events[index];
  6515. window.addEventListener(event.name, event.handler, false);
  6516. try {
  6517. if (window.parent) {
  6518. window.parent.addEventListener(event.name, event.handler, false);
  6519. }
  6520. }
  6521. catch (e) {
  6522. // Silently fails...
  6523. }
  6524. }
  6525. };
  6526. Tools.UnregisterTopRootEvents = function (events) {
  6527. for (var index = 0; index < events.length; index++) {
  6528. var event = events[index];
  6529. window.removeEventListener(event.name, event.handler);
  6530. try {
  6531. if (window.parent) {
  6532. window.parent.removeEventListener(event.name, event.handler);
  6533. }
  6534. }
  6535. catch (e) {
  6536. // Silently fails...
  6537. }
  6538. }
  6539. };
  6540. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6541. if (mimeType === void 0) { mimeType = "image/png"; }
  6542. // Read the contents of the framebuffer
  6543. var numberOfChannelsByLine = width * 4;
  6544. var halfHeight = height / 2;
  6545. //Reading datas from WebGL
  6546. var data = engine.readPixels(0, 0, width, height);
  6547. //To flip image on Y axis.
  6548. for (var i = 0; i < halfHeight; i++) {
  6549. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6550. var currentCell = j + i * numberOfChannelsByLine;
  6551. var targetLine = height - i - 1;
  6552. var targetCell = j + targetLine * numberOfChannelsByLine;
  6553. var temp = data[currentCell];
  6554. data[currentCell] = data[targetCell];
  6555. data[targetCell] = temp;
  6556. }
  6557. }
  6558. // Create a 2D canvas to store the result
  6559. if (!screenshotCanvas) {
  6560. screenshotCanvas = document.createElement('canvas');
  6561. }
  6562. screenshotCanvas.width = width;
  6563. screenshotCanvas.height = height;
  6564. var context = screenshotCanvas.getContext('2d');
  6565. // Copy the pixels to a 2D canvas
  6566. var imageData = context.createImageData(width, height);
  6567. var castData = (imageData.data);
  6568. castData.set(data);
  6569. context.putImageData(imageData, 0, 0);
  6570. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6571. };
  6572. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6573. if (mimeType === void 0) { mimeType = "image/png"; }
  6574. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6575. if (successCallback) {
  6576. successCallback(base64Image);
  6577. }
  6578. else {
  6579. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6580. if (("download" in document.createElement("a"))) {
  6581. var a = window.document.createElement("a");
  6582. a.href = base64Image;
  6583. var date = new Date();
  6584. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6585. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6586. window.document.body.appendChild(a);
  6587. a.addEventListener("click", function () {
  6588. a.parentElement.removeChild(a);
  6589. });
  6590. a.click();
  6591. //Or opening a new tab with the image if it is not possible to automatically start download.
  6592. }
  6593. else {
  6594. var newWindow = window.open("");
  6595. var img = newWindow.document.createElement("img");
  6596. img.src = base64Image;
  6597. newWindow.document.body.appendChild(img);
  6598. }
  6599. }
  6600. };
  6601. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6602. if (mimeType === void 0) { mimeType = "image/png"; }
  6603. var width;
  6604. var height;
  6605. // If a precision value is specified
  6606. if (size.precision) {
  6607. width = Math.round(engine.getRenderWidth() * size.precision);
  6608. height = Math.round(width / engine.getAspectRatio(camera));
  6609. }
  6610. else if (size.width && size.height) {
  6611. width = size.width;
  6612. height = size.height;
  6613. }
  6614. else if (size.width && !size.height) {
  6615. width = size.width;
  6616. height = Math.round(width / engine.getAspectRatio(camera));
  6617. }
  6618. else if (size.height && !size.width) {
  6619. height = size.height;
  6620. width = Math.round(height * engine.getAspectRatio(camera));
  6621. }
  6622. else if (!isNaN(size)) {
  6623. height = size;
  6624. width = size;
  6625. }
  6626. else {
  6627. Tools.Error("Invalid 'size' parameter !");
  6628. return;
  6629. }
  6630. if (!screenshotCanvas) {
  6631. screenshotCanvas = document.createElement('canvas');
  6632. }
  6633. screenshotCanvas.width = width;
  6634. screenshotCanvas.height = height;
  6635. var renderContext = screenshotCanvas.getContext("2d");
  6636. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6637. var newWidth = width;
  6638. var newHeight = newWidth / ratio;
  6639. if (newHeight > height) {
  6640. newHeight = height;
  6641. newWidth = newHeight * ratio;
  6642. }
  6643. var offsetX = Math.max(0, width - newWidth) / 2;
  6644. var offsetY = Math.max(0, height - newHeight) / 2;
  6645. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6646. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6647. };
  6648. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6649. if (mimeType === void 0) { mimeType = "image/png"; }
  6650. if (samples === void 0) { samples = 1; }
  6651. var width;
  6652. var height;
  6653. //If a precision value is specified
  6654. if (size.precision) {
  6655. width = Math.round(engine.getRenderWidth() * size.precision);
  6656. height = Math.round(width / engine.getAspectRatio(camera));
  6657. size = { width: width, height: height };
  6658. }
  6659. else if (size.width && size.height) {
  6660. width = size.width;
  6661. height = size.height;
  6662. }
  6663. else if (size.width && !size.height) {
  6664. width = size.width;
  6665. height = Math.round(width / engine.getAspectRatio(camera));
  6666. size = { width: width, height: height };
  6667. }
  6668. else if (size.height && !size.width) {
  6669. height = size.height;
  6670. width = Math.round(height * engine.getAspectRatio(camera));
  6671. size = { width: width, height: height };
  6672. }
  6673. else if (!isNaN(size)) {
  6674. height = size;
  6675. width = size;
  6676. }
  6677. else {
  6678. Tools.Error("Invalid 'size' parameter !");
  6679. return;
  6680. }
  6681. var scene = camera.getScene();
  6682. var previousCamera = null;
  6683. if (scene.activeCamera !== camera) {
  6684. previousCamera = scene.activeCamera;
  6685. scene.activeCamera = camera;
  6686. }
  6687. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6688. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6689. texture.renderList = scene.meshes;
  6690. texture.samples = samples;
  6691. texture.onAfterRenderObservable.add(function () {
  6692. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6693. });
  6694. scene.incrementRenderId();
  6695. scene.resetCachedMaterial();
  6696. texture.render(true);
  6697. texture.dispose();
  6698. if (previousCamera) {
  6699. scene.activeCamera = previousCamera;
  6700. }
  6701. camera.getProjectionMatrix(true); // Force cache refresh;
  6702. };
  6703. // XHR response validator for local file scenario
  6704. Tools.ValidateXHRData = function (xhr, dataType) {
  6705. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6706. if (dataType === void 0) { dataType = 7; }
  6707. try {
  6708. if (dataType & 1) {
  6709. if (xhr.responseText && xhr.responseText.length > 0) {
  6710. return true;
  6711. }
  6712. else if (dataType === 1) {
  6713. return false;
  6714. }
  6715. }
  6716. if (dataType & 2) {
  6717. // Check header width and height since there is no "TGA" magic number
  6718. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6719. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6720. return true;
  6721. }
  6722. else if (dataType === 2) {
  6723. return false;
  6724. }
  6725. }
  6726. if (dataType & 4) {
  6727. // Check for the "DDS" magic number
  6728. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6729. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6730. return true;
  6731. }
  6732. else {
  6733. return false;
  6734. }
  6735. }
  6736. }
  6737. catch (e) {
  6738. // Global protection
  6739. }
  6740. return false;
  6741. };
  6742. /**
  6743. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6744. * Be aware Math.random() could cause collisions, but:
  6745. * "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"
  6746. */
  6747. Tools.RandomId = function () {
  6748. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6749. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6750. return v.toString(16);
  6751. });
  6752. };
  6753. Object.defineProperty(Tools, "NoneLogLevel", {
  6754. get: function () {
  6755. return Tools._NoneLogLevel;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. Object.defineProperty(Tools, "MessageLogLevel", {
  6761. get: function () {
  6762. return Tools._MessageLogLevel;
  6763. },
  6764. enumerable: true,
  6765. configurable: true
  6766. });
  6767. Object.defineProperty(Tools, "WarningLogLevel", {
  6768. get: function () {
  6769. return Tools._WarningLogLevel;
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. Object.defineProperty(Tools, "ErrorLogLevel", {
  6775. get: function () {
  6776. return Tools._ErrorLogLevel;
  6777. },
  6778. enumerable: true,
  6779. configurable: true
  6780. });
  6781. Object.defineProperty(Tools, "AllLogLevel", {
  6782. get: function () {
  6783. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6784. },
  6785. enumerable: true,
  6786. configurable: true
  6787. });
  6788. Tools._AddLogEntry = function (entry) {
  6789. Tools._LogCache = entry + Tools._LogCache;
  6790. if (Tools.OnNewCacheEntry) {
  6791. Tools.OnNewCacheEntry(entry);
  6792. }
  6793. };
  6794. Tools._FormatMessage = function (message) {
  6795. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6796. var date = new Date();
  6797. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6798. };
  6799. Tools._LogDisabled = function (message) {
  6800. // nothing to do
  6801. };
  6802. Tools._LogEnabled = function (message) {
  6803. var formattedMessage = Tools._FormatMessage(message);
  6804. console.log("BJS - " + formattedMessage);
  6805. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6806. Tools._AddLogEntry(entry);
  6807. };
  6808. Tools._WarnDisabled = function (message) {
  6809. // nothing to do
  6810. };
  6811. Tools._WarnEnabled = function (message) {
  6812. var formattedMessage = Tools._FormatMessage(message);
  6813. console.warn("BJS - " + formattedMessage);
  6814. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6815. Tools._AddLogEntry(entry);
  6816. };
  6817. Tools._ErrorDisabled = function (message) {
  6818. // nothing to do
  6819. };
  6820. Tools._ErrorEnabled = function (message) {
  6821. Tools.errorsCount++;
  6822. var formattedMessage = Tools._FormatMessage(message);
  6823. console.error("BJS - " + formattedMessage);
  6824. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6825. Tools._AddLogEntry(entry);
  6826. };
  6827. Object.defineProperty(Tools, "LogCache", {
  6828. get: function () {
  6829. return Tools._LogCache;
  6830. },
  6831. enumerable: true,
  6832. configurable: true
  6833. });
  6834. Tools.ClearLogCache = function () {
  6835. Tools._LogCache = "";
  6836. Tools.errorsCount = 0;
  6837. };
  6838. Object.defineProperty(Tools, "LogLevels", {
  6839. set: function (level) {
  6840. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6841. Tools.Log = Tools._LogEnabled;
  6842. }
  6843. else {
  6844. Tools.Log = Tools._LogDisabled;
  6845. }
  6846. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6847. Tools.Warn = Tools._WarnEnabled;
  6848. }
  6849. else {
  6850. Tools.Warn = Tools._WarnDisabled;
  6851. }
  6852. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6853. Tools.Error = Tools._ErrorEnabled;
  6854. }
  6855. else {
  6856. Tools.Error = Tools._ErrorDisabled;
  6857. }
  6858. },
  6859. enumerable: true,
  6860. configurable: true
  6861. });
  6862. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6863. get: function () {
  6864. return Tools._PerformanceNoneLogLevel;
  6865. },
  6866. enumerable: true,
  6867. configurable: true
  6868. });
  6869. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6870. get: function () {
  6871. return Tools._PerformanceUserMarkLogLevel;
  6872. },
  6873. enumerable: true,
  6874. configurable: true
  6875. });
  6876. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6877. get: function () {
  6878. return Tools._PerformanceConsoleLogLevel;
  6879. },
  6880. enumerable: true,
  6881. configurable: true
  6882. });
  6883. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6884. set: function (level) {
  6885. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6886. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6887. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6888. return;
  6889. }
  6890. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6891. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6892. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6893. return;
  6894. }
  6895. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6896. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6897. },
  6898. enumerable: true,
  6899. configurable: true
  6900. });
  6901. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6902. };
  6903. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6904. };
  6905. Tools._StartUserMark = function (counterName, condition) {
  6906. if (condition === void 0) { condition = true; }
  6907. if (!condition || !Tools._performance.mark) {
  6908. return;
  6909. }
  6910. Tools._performance.mark(counterName + "-Begin");
  6911. };
  6912. Tools._EndUserMark = function (counterName, condition) {
  6913. if (condition === void 0) { condition = true; }
  6914. if (!condition || !Tools._performance.mark) {
  6915. return;
  6916. }
  6917. Tools._performance.mark(counterName + "-End");
  6918. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6919. };
  6920. Tools._StartPerformanceConsole = function (counterName, condition) {
  6921. if (condition === void 0) { condition = true; }
  6922. if (!condition) {
  6923. return;
  6924. }
  6925. Tools._StartUserMark(counterName, condition);
  6926. if (console.time) {
  6927. console.time(counterName);
  6928. }
  6929. };
  6930. Tools._EndPerformanceConsole = function (counterName, condition) {
  6931. if (condition === void 0) { condition = true; }
  6932. if (!condition) {
  6933. return;
  6934. }
  6935. Tools._EndUserMark(counterName, condition);
  6936. if (console.time) {
  6937. console.timeEnd(counterName);
  6938. }
  6939. };
  6940. Object.defineProperty(Tools, "Now", {
  6941. get: function () {
  6942. if (window.performance && window.performance.now) {
  6943. return window.performance.now();
  6944. }
  6945. return new Date().getTime();
  6946. },
  6947. enumerable: true,
  6948. configurable: true
  6949. });
  6950. /**
  6951. * This method will return the name of the class used to create the instance of the given object.
  6952. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6953. * @param object the object to get the class name from
  6954. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6955. */
  6956. Tools.getClassName = function (object, isType) {
  6957. if (isType === void 0) { isType = false; }
  6958. var name = null;
  6959. if (!isType && object.getClassName) {
  6960. name = object.getClassName();
  6961. }
  6962. else {
  6963. if (object instanceof Object) {
  6964. var classObj = isType ? object : Object.getPrototypeOf(object);
  6965. name = classObj.constructor["__bjsclassName__"];
  6966. }
  6967. if (!name) {
  6968. name = typeof object;
  6969. }
  6970. }
  6971. return name;
  6972. };
  6973. Tools.first = function (array, predicate) {
  6974. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6975. var el = array_1[_i];
  6976. if (predicate(el)) {
  6977. return el;
  6978. }
  6979. }
  6980. };
  6981. /**
  6982. * This method will return the name of the full name of the class, including its owning module (if any).
  6983. * 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).
  6984. * @param object the object to get the class name from
  6985. * @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.
  6986. */
  6987. Tools.getFullClassName = function (object, isType) {
  6988. if (isType === void 0) { isType = false; }
  6989. var className = null;
  6990. var moduleName = null;
  6991. if (!isType && object.getClassName) {
  6992. className = object.getClassName();
  6993. }
  6994. else {
  6995. if (object instanceof Object) {
  6996. var classObj = isType ? object : Object.getPrototypeOf(object);
  6997. className = classObj.constructor["__bjsclassName__"];
  6998. moduleName = classObj.constructor["__bjsmoduleName__"];
  6999. }
  7000. if (!className) {
  7001. className = typeof object;
  7002. }
  7003. }
  7004. if (!className) {
  7005. return null;
  7006. }
  7007. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7008. };
  7009. /**
  7010. * 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.
  7011. * @param array
  7012. */
  7013. Tools.arrayOrStringFeeder = function (array) {
  7014. return function (index) {
  7015. if (index >= array.length) {
  7016. return null;
  7017. }
  7018. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7019. if (val && val.getHashCode) {
  7020. val = val.getHashCode();
  7021. }
  7022. if (typeof val === "string") {
  7023. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7024. }
  7025. return val;
  7026. };
  7027. };
  7028. /**
  7029. * Compute the hashCode of a stream of number
  7030. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7031. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7032. * @return the hash code computed
  7033. */
  7034. Tools.hashCodeFromStream = function (feeder) {
  7035. // Based from here: http://stackoverflow.com/a/7616484/802124
  7036. var hash = 0;
  7037. var index = 0;
  7038. var chr = feeder(index++);
  7039. while (chr != null) {
  7040. hash = ((hash << 5) - hash) + chr;
  7041. hash |= 0; // Convert to 32bit integer
  7042. chr = feeder(index++);
  7043. }
  7044. return hash;
  7045. };
  7046. return Tools;
  7047. }());
  7048. Tools.BaseUrl = "";
  7049. Tools.CorsBehavior = "anonymous";
  7050. Tools.UseFallbackTexture = true;
  7051. // Used in case of a texture loading problem
  7052. 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";
  7053. // Logs
  7054. Tools._NoneLogLevel = 0;
  7055. Tools._MessageLogLevel = 1;
  7056. Tools._WarningLogLevel = 2;
  7057. Tools._ErrorLogLevel = 4;
  7058. Tools._LogCache = "";
  7059. Tools.errorsCount = 0;
  7060. Tools.Log = Tools._LogEnabled;
  7061. Tools.Warn = Tools._WarnEnabled;
  7062. Tools.Error = Tools._ErrorEnabled;
  7063. // Performances
  7064. Tools._PerformanceNoneLogLevel = 0;
  7065. Tools._PerformanceUserMarkLogLevel = 1;
  7066. Tools._PerformanceConsoleLogLevel = 2;
  7067. Tools._performance = window.performance;
  7068. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7069. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7070. BABYLON.Tools = Tools;
  7071. /**
  7072. * This class is used to track a performance counter which is number based.
  7073. * The user has access to many properties which give statistics of different nature
  7074. *
  7075. * The implementer can track two kinds of Performance Counter: time and count
  7076. * 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.
  7077. * 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.
  7078. */
  7079. var PerfCounter = (function () {
  7080. function PerfCounter() {
  7081. this._startMonitoringTime = 0;
  7082. this._min = 0;
  7083. this._max = 0;
  7084. this._average = 0;
  7085. this._lastSecAverage = 0;
  7086. this._current = 0;
  7087. this._totalValueCount = 0;
  7088. this._totalAccumulated = 0;
  7089. this._lastSecAccumulated = 0;
  7090. this._lastSecTime = 0;
  7091. this._lastSecValueCount = 0;
  7092. }
  7093. Object.defineProperty(PerfCounter.prototype, "min", {
  7094. /**
  7095. * Returns the smallest value ever
  7096. */
  7097. get: function () {
  7098. return this._min;
  7099. },
  7100. enumerable: true,
  7101. configurable: true
  7102. });
  7103. Object.defineProperty(PerfCounter.prototype, "max", {
  7104. /**
  7105. * Returns the biggest value ever
  7106. */
  7107. get: function () {
  7108. return this._max;
  7109. },
  7110. enumerable: true,
  7111. configurable: true
  7112. });
  7113. Object.defineProperty(PerfCounter.prototype, "average", {
  7114. /**
  7115. * Returns the average value since the performance counter is running
  7116. */
  7117. get: function () {
  7118. return this._average;
  7119. },
  7120. enumerable: true,
  7121. configurable: true
  7122. });
  7123. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7124. /**
  7125. * Returns the average value of the last second the counter was monitored
  7126. */
  7127. get: function () {
  7128. return this._lastSecAverage;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(PerfCounter.prototype, "current", {
  7134. /**
  7135. * Returns the current value
  7136. */
  7137. get: function () {
  7138. return this._current;
  7139. },
  7140. enumerable: true,
  7141. configurable: true
  7142. });
  7143. Object.defineProperty(PerfCounter.prototype, "total", {
  7144. get: function () {
  7145. return this._totalAccumulated;
  7146. },
  7147. enumerable: true,
  7148. configurable: true
  7149. });
  7150. /**
  7151. * Call this method to start monitoring a new frame.
  7152. * 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.
  7153. */
  7154. PerfCounter.prototype.fetchNewFrame = function () {
  7155. this._totalValueCount++;
  7156. this._current = 0;
  7157. this._lastSecValueCount++;
  7158. };
  7159. /**
  7160. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7161. * @param newCount the count value to add to the monitored count
  7162. * @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.
  7163. */
  7164. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7165. if (!PerfCounter.Enabled) {
  7166. return;
  7167. }
  7168. this._current += newCount;
  7169. if (fetchResult) {
  7170. this._fetchResult();
  7171. }
  7172. };
  7173. /**
  7174. * Start monitoring this performance counter
  7175. */
  7176. PerfCounter.prototype.beginMonitoring = function () {
  7177. if (!PerfCounter.Enabled) {
  7178. return;
  7179. }
  7180. this._startMonitoringTime = Tools.Now;
  7181. };
  7182. /**
  7183. * Compute the time lapsed since the previous beginMonitoring() call.
  7184. * @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
  7185. */
  7186. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7187. if (newFrame === void 0) { newFrame = true; }
  7188. if (!PerfCounter.Enabled) {
  7189. return;
  7190. }
  7191. if (newFrame) {
  7192. this.fetchNewFrame();
  7193. }
  7194. var currentTime = Tools.Now;
  7195. this._current = currentTime - this._startMonitoringTime;
  7196. if (newFrame) {
  7197. this._fetchResult();
  7198. }
  7199. };
  7200. PerfCounter.prototype._fetchResult = function () {
  7201. this._totalAccumulated += this._current;
  7202. this._lastSecAccumulated += this._current;
  7203. // Min/Max update
  7204. this._min = Math.min(this._min, this._current);
  7205. this._max = Math.max(this._max, this._current);
  7206. this._average = this._totalAccumulated / this._totalValueCount;
  7207. // Reset last sec?
  7208. var now = Tools.Now;
  7209. if ((now - this._lastSecTime) > 1000) {
  7210. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7211. this._lastSecTime = now;
  7212. this._lastSecAccumulated = 0;
  7213. this._lastSecValueCount = 0;
  7214. }
  7215. };
  7216. return PerfCounter;
  7217. }());
  7218. PerfCounter.Enabled = true;
  7219. BABYLON.PerfCounter = PerfCounter;
  7220. /**
  7221. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7222. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7223. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7224. * @param name The name of the class, case should be preserved
  7225. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7226. */
  7227. function className(name, module) {
  7228. return function (target) {
  7229. target["__bjsclassName__"] = name;
  7230. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7231. };
  7232. }
  7233. BABYLON.className = className;
  7234. /**
  7235. * An implementation of a loop for asynchronous functions.
  7236. */
  7237. var AsyncLoop = (function () {
  7238. /**
  7239. * Constroctor.
  7240. * @param iterations the number of iterations.
  7241. * @param _fn the function to run each iteration
  7242. * @param _successCallback the callback that will be called upon succesful execution
  7243. * @param offset starting offset.
  7244. */
  7245. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7246. if (offset === void 0) { offset = 0; }
  7247. this.iterations = iterations;
  7248. this._fn = _fn;
  7249. this._successCallback = _successCallback;
  7250. this.index = offset - 1;
  7251. this._done = false;
  7252. }
  7253. /**
  7254. * Execute the next iteration. Must be called after the last iteration was finished.
  7255. */
  7256. AsyncLoop.prototype.executeNext = function () {
  7257. if (!this._done) {
  7258. if (this.index + 1 < this.iterations) {
  7259. ++this.index;
  7260. this._fn(this);
  7261. }
  7262. else {
  7263. this.breakLoop();
  7264. }
  7265. }
  7266. };
  7267. /**
  7268. * Break the loop and run the success callback.
  7269. */
  7270. AsyncLoop.prototype.breakLoop = function () {
  7271. this._done = true;
  7272. this._successCallback();
  7273. };
  7274. /**
  7275. * Helper function
  7276. */
  7277. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7278. if (offset === void 0) { offset = 0; }
  7279. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7280. loop.executeNext();
  7281. return loop;
  7282. };
  7283. /**
  7284. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7285. * @param iterations total number of iterations
  7286. * @param syncedIterations number of synchronous iterations in each async iteration.
  7287. * @param fn the function to call each iteration.
  7288. * @param callback a success call back that will be called when iterating stops.
  7289. * @param breakFunction a break condition (optional)
  7290. * @param timeout timeout settings for the setTimeout function. default - 0.
  7291. * @constructor
  7292. */
  7293. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7294. if (timeout === void 0) { timeout = 0; }
  7295. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7296. if (breakFunction && breakFunction())
  7297. loop.breakLoop();
  7298. else {
  7299. setTimeout(function () {
  7300. for (var i = 0; i < syncedIterations; ++i) {
  7301. var iteration = (loop.index * syncedIterations) + i;
  7302. if (iteration >= iterations)
  7303. break;
  7304. fn(iteration);
  7305. if (breakFunction && breakFunction()) {
  7306. loop.breakLoop();
  7307. break;
  7308. }
  7309. }
  7310. loop.executeNext();
  7311. }, timeout);
  7312. }
  7313. }, callback);
  7314. };
  7315. return AsyncLoop;
  7316. }());
  7317. BABYLON.AsyncLoop = AsyncLoop;
  7318. })(BABYLON || (BABYLON = {}));
  7319. //# sourceMappingURL=babylon.tools.js.map
  7320. var BABYLON;
  7321. (function (BABYLON) {
  7322. var Internals;
  7323. (function (Internals) {
  7324. var _AlphaState = (function () {
  7325. /**
  7326. * Initializes the state.
  7327. */
  7328. function _AlphaState() {
  7329. this._isAlphaBlendDirty = false;
  7330. this._isBlendFunctionParametersDirty = false;
  7331. this._alphaBlend = false;
  7332. this._blendFunctionParameters = new Array(4);
  7333. this.reset();
  7334. }
  7335. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7336. get: function () {
  7337. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7338. },
  7339. enumerable: true,
  7340. configurable: true
  7341. });
  7342. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7343. get: function () {
  7344. return this._alphaBlend;
  7345. },
  7346. set: function (value) {
  7347. if (this._alphaBlend === value) {
  7348. return;
  7349. }
  7350. this._alphaBlend = value;
  7351. this._isAlphaBlendDirty = true;
  7352. },
  7353. enumerable: true,
  7354. configurable: true
  7355. });
  7356. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7357. if (this._blendFunctionParameters[0] === value0 &&
  7358. this._blendFunctionParameters[1] === value1 &&
  7359. this._blendFunctionParameters[2] === value2 &&
  7360. this._blendFunctionParameters[3] === value3) {
  7361. return;
  7362. }
  7363. this._blendFunctionParameters[0] = value0;
  7364. this._blendFunctionParameters[1] = value1;
  7365. this._blendFunctionParameters[2] = value2;
  7366. this._blendFunctionParameters[3] = value3;
  7367. this._isBlendFunctionParametersDirty = true;
  7368. };
  7369. _AlphaState.prototype.reset = function () {
  7370. this._alphaBlend = false;
  7371. this._blendFunctionParameters[0] = null;
  7372. this._blendFunctionParameters[1] = null;
  7373. this._blendFunctionParameters[2] = null;
  7374. this._blendFunctionParameters[3] = null;
  7375. this._isAlphaBlendDirty = true;
  7376. this._isBlendFunctionParametersDirty = false;
  7377. };
  7378. _AlphaState.prototype.apply = function (gl) {
  7379. if (!this.isDirty) {
  7380. return;
  7381. }
  7382. // Alpha blend
  7383. if (this._isAlphaBlendDirty) {
  7384. if (this._alphaBlend) {
  7385. gl.enable(gl.BLEND);
  7386. }
  7387. else {
  7388. gl.disable(gl.BLEND);
  7389. }
  7390. this._isAlphaBlendDirty = false;
  7391. }
  7392. // Alpha function
  7393. if (this._isBlendFunctionParametersDirty) {
  7394. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7395. this._isBlendFunctionParametersDirty = false;
  7396. }
  7397. };
  7398. return _AlphaState;
  7399. }());
  7400. Internals._AlphaState = _AlphaState;
  7401. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7402. })(BABYLON || (BABYLON = {}));
  7403. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7404. var BABYLON;
  7405. (function (BABYLON) {
  7406. var Internals;
  7407. (function (Internals) {
  7408. var _DepthCullingState = (function () {
  7409. /**
  7410. * Initializes the state.
  7411. */
  7412. function _DepthCullingState() {
  7413. this._isDepthTestDirty = false;
  7414. this._isDepthMaskDirty = false;
  7415. this._isDepthFuncDirty = false;
  7416. this._isCullFaceDirty = false;
  7417. this._isCullDirty = false;
  7418. this._isZOffsetDirty = false;
  7419. this.reset();
  7420. }
  7421. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7422. get: function () {
  7423. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7424. },
  7425. enumerable: true,
  7426. configurable: true
  7427. });
  7428. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7429. get: function () {
  7430. return this._zOffset;
  7431. },
  7432. set: function (value) {
  7433. if (this._zOffset === value) {
  7434. return;
  7435. }
  7436. this._zOffset = value;
  7437. this._isZOffsetDirty = true;
  7438. },
  7439. enumerable: true,
  7440. configurable: true
  7441. });
  7442. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7443. get: function () {
  7444. return this._cullFace;
  7445. },
  7446. set: function (value) {
  7447. if (this._cullFace === value) {
  7448. return;
  7449. }
  7450. this._cullFace = value;
  7451. this._isCullFaceDirty = true;
  7452. },
  7453. enumerable: true,
  7454. configurable: true
  7455. });
  7456. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7457. get: function () {
  7458. return this._cull;
  7459. },
  7460. set: function (value) {
  7461. if (this._cull === value) {
  7462. return;
  7463. }
  7464. this._cull = value;
  7465. this._isCullDirty = true;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7471. get: function () {
  7472. return this._depthFunc;
  7473. },
  7474. set: function (value) {
  7475. if (this._depthFunc === value) {
  7476. return;
  7477. }
  7478. this._depthFunc = value;
  7479. this._isDepthFuncDirty = true;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7485. get: function () {
  7486. return this._depthMask;
  7487. },
  7488. set: function (value) {
  7489. if (this._depthMask === value) {
  7490. return;
  7491. }
  7492. this._depthMask = value;
  7493. this._isDepthMaskDirty = true;
  7494. },
  7495. enumerable: true,
  7496. configurable: true
  7497. });
  7498. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7499. get: function () {
  7500. return this._depthTest;
  7501. },
  7502. set: function (value) {
  7503. if (this._depthTest === value) {
  7504. return;
  7505. }
  7506. this._depthTest = value;
  7507. this._isDepthTestDirty = true;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. _DepthCullingState.prototype.reset = function () {
  7513. this._depthMask = true;
  7514. this._depthTest = true;
  7515. this._depthFunc = null;
  7516. this._cullFace = null;
  7517. this._cull = null;
  7518. this._zOffset = 0;
  7519. this._isDepthTestDirty = true;
  7520. this._isDepthMaskDirty = true;
  7521. this._isDepthFuncDirty = false;
  7522. this._isCullFaceDirty = false;
  7523. this._isCullDirty = false;
  7524. this._isZOffsetDirty = false;
  7525. };
  7526. _DepthCullingState.prototype.apply = function (gl) {
  7527. if (!this.isDirty) {
  7528. return;
  7529. }
  7530. // Cull
  7531. if (this._isCullDirty) {
  7532. if (this.cull) {
  7533. gl.enable(gl.CULL_FACE);
  7534. }
  7535. else {
  7536. gl.disable(gl.CULL_FACE);
  7537. }
  7538. this._isCullDirty = false;
  7539. }
  7540. // Cull face
  7541. if (this._isCullFaceDirty) {
  7542. gl.cullFace(this.cullFace);
  7543. this._isCullFaceDirty = false;
  7544. }
  7545. // Depth mask
  7546. if (this._isDepthMaskDirty) {
  7547. gl.depthMask(this.depthMask);
  7548. this._isDepthMaskDirty = false;
  7549. }
  7550. // Depth test
  7551. if (this._isDepthTestDirty) {
  7552. if (this.depthTest) {
  7553. gl.enable(gl.DEPTH_TEST);
  7554. }
  7555. else {
  7556. gl.disable(gl.DEPTH_TEST);
  7557. }
  7558. this._isDepthTestDirty = false;
  7559. }
  7560. // Depth func
  7561. if (this._isDepthFuncDirty) {
  7562. gl.depthFunc(this.depthFunc);
  7563. this._isDepthFuncDirty = false;
  7564. }
  7565. // zOffset
  7566. if (this._isZOffsetDirty) {
  7567. if (this.zOffset) {
  7568. gl.enable(gl.POLYGON_OFFSET_FILL);
  7569. gl.polygonOffset(this.zOffset, 0);
  7570. }
  7571. else {
  7572. gl.disable(gl.POLYGON_OFFSET_FILL);
  7573. }
  7574. this._isZOffsetDirty = false;
  7575. }
  7576. };
  7577. return _DepthCullingState;
  7578. }());
  7579. Internals._DepthCullingState = _DepthCullingState;
  7580. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7581. })(BABYLON || (BABYLON = {}));
  7582. //# sourceMappingURL=babylon.depthCullingState.js.map
  7583. var BABYLON;
  7584. (function (BABYLON) {
  7585. var Internals;
  7586. (function (Internals) {
  7587. var _StencilState = (function () {
  7588. function _StencilState() {
  7589. this._isStencilTestDirty = false;
  7590. this._isStencilMaskDirty = false;
  7591. this._isStencilFuncDirty = false;
  7592. this._isStencilOpDirty = false;
  7593. this.reset();
  7594. }
  7595. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7596. get: function () {
  7597. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7603. get: function () {
  7604. return this._stencilFunc;
  7605. },
  7606. set: function (value) {
  7607. if (this._stencilFunc === value) {
  7608. return;
  7609. }
  7610. this._stencilFunc = value;
  7611. this._isStencilFuncDirty = true;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7617. get: function () {
  7618. return this._stencilFuncRef;
  7619. },
  7620. set: function (value) {
  7621. if (this._stencilFuncRef === value) {
  7622. return;
  7623. }
  7624. this._stencilFuncRef = value;
  7625. this._isStencilFuncDirty = true;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7631. get: function () {
  7632. return this._stencilFuncMask;
  7633. },
  7634. set: function (value) {
  7635. if (this._stencilFuncMask === value) {
  7636. return;
  7637. }
  7638. this._stencilFuncMask = value;
  7639. this._isStencilFuncDirty = true;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7645. get: function () {
  7646. return this._stencilOpStencilFail;
  7647. },
  7648. set: function (value) {
  7649. if (this._stencilOpStencilFail === value) {
  7650. return;
  7651. }
  7652. this._stencilOpStencilFail = value;
  7653. this._isStencilOpDirty = true;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7659. get: function () {
  7660. return this._stencilOpDepthFail;
  7661. },
  7662. set: function (value) {
  7663. if (this._stencilOpDepthFail === value) {
  7664. return;
  7665. }
  7666. this._stencilOpDepthFail = value;
  7667. this._isStencilOpDirty = true;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7673. get: function () {
  7674. return this._stencilOpStencilDepthPass;
  7675. },
  7676. set: function (value) {
  7677. if (this._stencilOpStencilDepthPass === value) {
  7678. return;
  7679. }
  7680. this._stencilOpStencilDepthPass = value;
  7681. this._isStencilOpDirty = true;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7687. get: function () {
  7688. return this._stencilMask;
  7689. },
  7690. set: function (value) {
  7691. if (this._stencilMask === value) {
  7692. return;
  7693. }
  7694. this._stencilMask = value;
  7695. this._isStencilMaskDirty = true;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7701. get: function () {
  7702. return this._stencilTest;
  7703. },
  7704. set: function (value) {
  7705. if (this._stencilTest === value) {
  7706. return;
  7707. }
  7708. this._stencilTest = value;
  7709. this._isStencilTestDirty = true;
  7710. },
  7711. enumerable: true,
  7712. configurable: true
  7713. });
  7714. _StencilState.prototype.reset = function () {
  7715. this._stencilTest = false;
  7716. this._stencilMask = 0xFF;
  7717. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7718. this._stencilFuncRef = 1;
  7719. this._stencilFuncMask = 0xFF;
  7720. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7721. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7722. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7723. this._isStencilTestDirty = true;
  7724. this._isStencilMaskDirty = true;
  7725. this._isStencilFuncDirty = true;
  7726. this._isStencilOpDirty = true;
  7727. };
  7728. _StencilState.prototype.apply = function (gl) {
  7729. if (!this.isDirty) {
  7730. return;
  7731. }
  7732. // Stencil test
  7733. if (this._isStencilTestDirty) {
  7734. if (this.stencilTest) {
  7735. gl.enable(gl.STENCIL_TEST);
  7736. }
  7737. else {
  7738. gl.disable(gl.STENCIL_TEST);
  7739. }
  7740. this._isStencilTestDirty = false;
  7741. }
  7742. // Stencil mask
  7743. if (this._isStencilMaskDirty) {
  7744. gl.stencilMask(this.stencilMask);
  7745. this._isStencilMaskDirty = false;
  7746. }
  7747. // Stencil func
  7748. if (this._isStencilFuncDirty) {
  7749. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7750. this._isStencilFuncDirty = false;
  7751. }
  7752. // Stencil op
  7753. if (this._isStencilOpDirty) {
  7754. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7755. this._isStencilOpDirty = false;
  7756. }
  7757. };
  7758. return _StencilState;
  7759. }());
  7760. Internals._StencilState = _StencilState;
  7761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7762. })(BABYLON || (BABYLON = {}));
  7763. //# sourceMappingURL=babylon.stencilState.js.map
  7764. var BABYLON;
  7765. (function (BABYLON) {
  7766. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7767. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7768. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7769. gl.compileShader(shader);
  7770. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7771. throw new Error(gl.getShaderInfoLog(shader));
  7772. }
  7773. return shader;
  7774. };
  7775. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7776. var magFilter = gl.NEAREST;
  7777. var minFilter = gl.NEAREST;
  7778. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7779. magFilter = gl.LINEAR;
  7780. if (generateMipMaps) {
  7781. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7782. }
  7783. else {
  7784. minFilter = gl.LINEAR;
  7785. }
  7786. }
  7787. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7788. magFilter = gl.LINEAR;
  7789. if (generateMipMaps) {
  7790. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7791. }
  7792. else {
  7793. minFilter = gl.LINEAR;
  7794. }
  7795. }
  7796. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7797. magFilter = gl.NEAREST;
  7798. if (generateMipMaps) {
  7799. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7800. }
  7801. else {
  7802. minFilter = gl.NEAREST;
  7803. }
  7804. }
  7805. return {
  7806. min: minFilter,
  7807. mag: magFilter
  7808. };
  7809. };
  7810. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7812. var engine = scene.getEngine();
  7813. if (!engine) {
  7814. return;
  7815. }
  7816. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7817. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7818. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7819. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7820. texture._baseWidth = width;
  7821. texture._baseHeight = height;
  7822. texture._width = potWidth;
  7823. texture._height = potHeight;
  7824. texture.isReady = true;
  7825. processFunction(potWidth, potHeight);
  7826. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7827. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7828. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7829. if (!noMipmap && !isCompressed) {
  7830. gl.generateMipmap(gl.TEXTURE_2D);
  7831. }
  7832. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7833. engine.resetTextureCache();
  7834. scene._removePendingData(texture);
  7835. texture.onLoadedCallbacks.forEach(function (callback) {
  7836. callback();
  7837. });
  7838. texture.onLoadedCallbacks = [];
  7839. };
  7840. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7841. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7842. var img;
  7843. var onload = function () {
  7844. loadedImages[index] = img;
  7845. loadedImages._internalCount++;
  7846. scene._removePendingData(img);
  7847. if (loadedImages._internalCount === 6) {
  7848. onfinish(loadedImages);
  7849. }
  7850. };
  7851. var onerror = function () {
  7852. scene._removePendingData(img);
  7853. if (onErrorCallBack) {
  7854. onErrorCallBack();
  7855. }
  7856. };
  7857. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7858. scene._addPendingData(img);
  7859. };
  7860. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7861. if (onError === void 0) { onError = null; }
  7862. var loadedImages = [];
  7863. loadedImages._internalCount = 0;
  7864. for (var index = 0; index < 6; index++) {
  7865. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7866. }
  7867. };
  7868. var InstancingAttributeInfo = (function () {
  7869. function InstancingAttributeInfo() {
  7870. }
  7871. return InstancingAttributeInfo;
  7872. }());
  7873. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7874. var EngineCapabilities = (function () {
  7875. function EngineCapabilities() {
  7876. }
  7877. return EngineCapabilities;
  7878. }());
  7879. BABYLON.EngineCapabilities = EngineCapabilities;
  7880. /**
  7881. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7882. */
  7883. var Engine = (function () {
  7884. /**
  7885. * @constructor
  7886. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7887. * @param {boolean} [antialias] - enable antialias
  7888. * @param options - further options to be sent to the getContext function
  7889. */
  7890. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7891. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7892. var _this = this;
  7893. // Public members
  7894. this.isFullscreen = false;
  7895. this.isPointerLock = false;
  7896. this.cullBackFaces = true;
  7897. this.renderEvenInBackground = true;
  7898. this.preventCacheWipeBetweenFrames = false;
  7899. // To enable/disable IDB support and avoid XHR on .manifest
  7900. this.enableOfflineSupport = true;
  7901. this.scenes = new Array();
  7902. this._windowIsBackground = false;
  7903. this._webGLVersion = 1.0;
  7904. this._badOS = false;
  7905. this._drawCalls = new BABYLON.PerfCounter();
  7906. this._renderingQueueLaunched = false;
  7907. this._activeRenderLoops = [];
  7908. // FPS
  7909. this.fpsRange = 60;
  7910. this.previousFramesDuration = [];
  7911. this.fps = 60;
  7912. this.deltaTime = 0;
  7913. // States
  7914. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7915. this._stencilState = new BABYLON.Internals._StencilState();
  7916. this._alphaState = new BABYLON.Internals._AlphaState();
  7917. this._alphaMode = Engine.ALPHA_DISABLE;
  7918. // Cache
  7919. this._loadedTexturesCache = new Array();
  7920. this._maxTextureChannels = 16;
  7921. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7922. this._compiledEffects = {};
  7923. this._vertexAttribArraysEnabled = [];
  7924. this._uintIndicesCurrentlySet = false;
  7925. this._currentBoundBuffer = new Array();
  7926. this._currentBufferPointers = [];
  7927. this._currentInstanceLocations = new Array();
  7928. this._currentInstanceBuffers = new Array();
  7929. this._vaoRecordInProgress = false;
  7930. this._mustWipeVertexAttributes = false;
  7931. // Hardware supported Compressed Textures
  7932. this._texturesSupported = new Array();
  7933. this._onVRFullScreenTriggered = function () {
  7934. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7935. //get the old size before we change
  7936. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7937. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7938. //get the width and height, change the render size
  7939. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7940. var width, height;
  7941. _this.setHardwareScalingLevel(1);
  7942. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7943. }
  7944. else {
  7945. //When the specs are implemented, need to uncomment this.
  7946. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7947. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7948. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7949. _this._vrDisplayEnabled = undefined;
  7950. }
  7951. };
  7952. this._renderingCanvas = canvas;
  7953. Engine.Instances.push(this);
  7954. this._externalData = new BABYLON.StringDictionary();
  7955. options = options || {};
  7956. if (antialias != null) {
  7957. options.antialias = antialias;
  7958. }
  7959. if (options.preserveDrawingBuffer === undefined) {
  7960. options.preserveDrawingBuffer = false;
  7961. }
  7962. if (options.audioEngine === undefined) {
  7963. options.audioEngine = true;
  7964. }
  7965. if (options.stencil === undefined) {
  7966. options.stencil = true;
  7967. }
  7968. // GL
  7969. if (!options.disableWebGL2Support) {
  7970. try {
  7971. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7972. if (this._gl) {
  7973. this._webGLVersion = 2.0;
  7974. }
  7975. }
  7976. catch (e) {
  7977. // Do nothing
  7978. }
  7979. }
  7980. if (!this._gl) {
  7981. if (!canvas) {
  7982. throw new Error("The provided canvas is null or undefined.");
  7983. }
  7984. try {
  7985. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7986. }
  7987. catch (e) {
  7988. throw new Error("WebGL not supported");
  7989. }
  7990. }
  7991. if (!this._gl) {
  7992. throw new Error("WebGL not supported");
  7993. }
  7994. this._onBlur = function () {
  7995. _this._windowIsBackground = true;
  7996. };
  7997. this._onFocus = function () {
  7998. _this._windowIsBackground = false;
  7999. };
  8000. window.addEventListener("blur", this._onBlur);
  8001. window.addEventListener("focus", this._onFocus);
  8002. // Viewport
  8003. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8004. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8005. this.resize();
  8006. // Caps
  8007. this._isStencilEnable = options.stencil;
  8008. this._caps = new EngineCapabilities();
  8009. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8010. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8011. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8012. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8013. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8014. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8015. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8016. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8017. // Infos
  8018. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8019. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8020. if (rendererInfo != null) {
  8021. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8022. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8023. }
  8024. if (!this._glVendor) {
  8025. this._glVendor = "Unknown vendor";
  8026. }
  8027. if (!this._glRenderer) {
  8028. this._glRenderer = "Unknown renderer";
  8029. }
  8030. // Extensions
  8031. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8032. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8033. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8034. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8035. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8036. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8037. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8038. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  8039. 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');
  8040. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8041. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8042. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8043. this._caps.highPrecisionShaderSupported = true;
  8044. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8045. // Checks if some of the format renders first to allow the use of webgl inspector.
  8046. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8047. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8048. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8049. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8050. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8051. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8052. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8053. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8054. // Vertex array object
  8055. if (this._webGLVersion > 1) {
  8056. this._caps.vertexArrayObject = true;
  8057. }
  8058. else {
  8059. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8060. if (vertexArrayObjectExtension != null) {
  8061. this._caps.vertexArrayObject = true;
  8062. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8063. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8064. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8065. }
  8066. else {
  8067. this._caps.vertexArrayObject = false;
  8068. }
  8069. }
  8070. // Instances count
  8071. if (this._webGLVersion > 1) {
  8072. this._caps.instancedArrays = true;
  8073. }
  8074. else {
  8075. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8076. if (instanceExtension != null) {
  8077. this._caps.instancedArrays = true;
  8078. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8079. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8080. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8081. }
  8082. else {
  8083. this._caps.instancedArrays = false;
  8084. }
  8085. }
  8086. // Intelligently add supported compressed formats in order to check for.
  8087. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8088. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8089. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8090. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8091. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  8092. if (this._caps.astc)
  8093. this.texturesSupported.push('-astc.ktx');
  8094. if (this._caps.s3tc)
  8095. this.texturesSupported.push('-dxt.ktx');
  8096. if (this._caps.pvrtc)
  8097. this.texturesSupported.push('-pvrtc.ktx');
  8098. if (this._caps.etc2)
  8099. this.texturesSupported.push('-etc2.ktx');
  8100. if (this._caps.atc)
  8101. this.texturesSupported.push('-atc.ktx');
  8102. if (this._caps.etc1)
  8103. this.texturesSupported.push('-etc1.ktx');
  8104. if (this._gl.getShaderPrecisionFormat) {
  8105. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8106. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8107. }
  8108. // Depth buffer
  8109. this.setDepthBuffer(true);
  8110. this.setDepthFunctionToLessOrEqual();
  8111. this.setDepthWrite(true);
  8112. // Fullscreen
  8113. this._onFullscreenChange = function () {
  8114. if (document.fullscreen !== undefined) {
  8115. _this.isFullscreen = document.fullscreen;
  8116. }
  8117. else if (document.mozFullScreen !== undefined) {
  8118. _this.isFullscreen = document.mozFullScreen;
  8119. }
  8120. else if (document.webkitIsFullScreen !== undefined) {
  8121. _this.isFullscreen = document.webkitIsFullScreen;
  8122. }
  8123. else if (document.msIsFullScreen !== undefined) {
  8124. _this.isFullscreen = document.msIsFullScreen;
  8125. }
  8126. // Pointer lock
  8127. if (_this.isFullscreen && _this._pointerLockRequested) {
  8128. canvas.requestPointerLock = canvas.requestPointerLock ||
  8129. canvas.msRequestPointerLock ||
  8130. canvas.mozRequestPointerLock ||
  8131. canvas.webkitRequestPointerLock;
  8132. if (canvas.requestPointerLock) {
  8133. canvas.requestPointerLock();
  8134. }
  8135. }
  8136. };
  8137. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8138. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8139. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8140. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8141. // Pointer lock
  8142. this._onPointerLockChange = function () {
  8143. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8144. document.webkitPointerLockElement === canvas ||
  8145. document.msPointerLockElement === canvas ||
  8146. document.pointerLockElement === canvas);
  8147. };
  8148. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8149. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8150. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8151. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8152. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8153. Engine.audioEngine = new BABYLON.AudioEngine();
  8154. }
  8155. //default loading screen
  8156. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  8157. //Load WebVR Devices
  8158. if (options.autoEnableWebVR) {
  8159. this.initWebVR();
  8160. }
  8161. //Detect if we are running on a faulty buggy OS.
  8162. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  8163. //ua sniffing is the tool of the devil.
  8164. this._badOS = regexp.test(navigator.userAgent);
  8165. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8166. }
  8167. Object.defineProperty(Engine, "LastCreatedEngine", {
  8168. get: function () {
  8169. if (Engine.Instances.length === 0) {
  8170. return null;
  8171. }
  8172. return Engine.Instances[Engine.Instances.length - 1];
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(Engine, "LastCreatedScene", {
  8178. get: function () {
  8179. var lastCreatedEngine = Engine.LastCreatedEngine;
  8180. if (!lastCreatedEngine) {
  8181. return null;
  8182. }
  8183. if (lastCreatedEngine.scenes.length === 0) {
  8184. return null;
  8185. }
  8186. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(Engine, "NEVER", {
  8192. get: function () {
  8193. return Engine._NEVER;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. Object.defineProperty(Engine, "ALWAYS", {
  8199. get: function () {
  8200. return Engine._ALWAYS;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. Object.defineProperty(Engine, "LESS", {
  8206. get: function () {
  8207. return Engine._LESS;
  8208. },
  8209. enumerable: true,
  8210. configurable: true
  8211. });
  8212. Object.defineProperty(Engine, "EQUAL", {
  8213. get: function () {
  8214. return Engine._EQUAL;
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. Object.defineProperty(Engine, "LEQUAL", {
  8220. get: function () {
  8221. return Engine._LEQUAL;
  8222. },
  8223. enumerable: true,
  8224. configurable: true
  8225. });
  8226. Object.defineProperty(Engine, "GREATER", {
  8227. get: function () {
  8228. return Engine._GREATER;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Engine, "GEQUAL", {
  8234. get: function () {
  8235. return Engine._GEQUAL;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(Engine, "NOTEQUAL", {
  8241. get: function () {
  8242. return Engine._NOTEQUAL;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine, "KEEP", {
  8248. get: function () {
  8249. return Engine._KEEP;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Engine, "REPLACE", {
  8255. get: function () {
  8256. return Engine._REPLACE;
  8257. },
  8258. enumerable: true,
  8259. configurable: true
  8260. });
  8261. Object.defineProperty(Engine, "INCR", {
  8262. get: function () {
  8263. return Engine._INCR;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(Engine, "DECR", {
  8269. get: function () {
  8270. return Engine._DECR;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "INVERT", {
  8276. get: function () {
  8277. return Engine._INVERT;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "INCR_WRAP", {
  8283. get: function () {
  8284. return Engine._INCR_WRAP;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "DECR_WRAP", {
  8290. get: function () {
  8291. return Engine._DECR_WRAP;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8297. get: function () {
  8298. return Engine._ALPHA_DISABLE;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8304. get: function () {
  8305. return Engine._ALPHA_ONEONE;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "ALPHA_ADD", {
  8311. get: function () {
  8312. return Engine._ALPHA_ADD;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8318. get: function () {
  8319. return Engine._ALPHA_COMBINE;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8325. get: function () {
  8326. return Engine._ALPHA_SUBTRACT;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8332. get: function () {
  8333. return Engine._ALPHA_MULTIPLY;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8339. get: function () {
  8340. return Engine._ALPHA_MAXIMIZED;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8346. get: function () {
  8347. return Engine._ALPHA_PREMULTIPLIED;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8353. get: function () {
  8354. return Engine._DELAYLOADSTATE_NONE;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8360. get: function () {
  8361. return Engine._DELAYLOADSTATE_LOADED;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8367. get: function () {
  8368. return Engine._DELAYLOADSTATE_LOADING;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8374. get: function () {
  8375. return Engine._DELAYLOADSTATE_NOTLOADED;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8381. get: function () {
  8382. return Engine._TEXTUREFORMAT_ALPHA;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8388. get: function () {
  8389. return Engine._TEXTUREFORMAT_LUMINANCE;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8395. get: function () {
  8396. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8402. get: function () {
  8403. return Engine._TEXTUREFORMAT_RGB;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8409. get: function () {
  8410. return Engine._TEXTUREFORMAT_RGBA;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8416. get: function () {
  8417. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8423. get: function () {
  8424. return Engine._TEXTURETYPE_FLOAT;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8430. get: function () {
  8431. return Engine._TEXTURETYPE_HALF_FLOAT;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine, "Version", {
  8437. get: function () {
  8438. return "3.0-alpha";
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8444. get: function () {
  8445. return this._texturesSupported;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8451. get: function () {
  8452. return this._textureFormatInUse;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8458. get: function () {
  8459. return this._webGLVersion;
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8465. /**
  8466. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8467. */
  8468. get: function () {
  8469. return this._isStencilEnable;
  8470. },
  8471. enumerable: true,
  8472. configurable: true
  8473. });
  8474. Engine.prototype._prepareWorkingCanvas = function () {
  8475. if (this._workingCanvas) {
  8476. return;
  8477. }
  8478. this._workingCanvas = document.createElement("canvas");
  8479. this._workingContext = this._workingCanvas.getContext("2d");
  8480. };
  8481. Engine.prototype.resetTextureCache = function () {
  8482. for (var index = 0; index < this._maxTextureChannels; index++) {
  8483. this._activeTexturesCache[index] = null;
  8484. }
  8485. };
  8486. Engine.prototype.getGlInfo = function () {
  8487. return {
  8488. vendor: this._glVendor,
  8489. renderer: this._glRenderer,
  8490. version: this._glVersion
  8491. };
  8492. };
  8493. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8494. if (useScreen === void 0) { useScreen = false; }
  8495. var viewport = camera.viewport;
  8496. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8497. };
  8498. Engine.prototype.getRenderWidth = function (useScreen) {
  8499. if (useScreen === void 0) { useScreen = false; }
  8500. if (!useScreen && this._currentRenderTarget) {
  8501. return this._currentRenderTarget._width;
  8502. }
  8503. return this._renderingCanvas.width;
  8504. };
  8505. Engine.prototype.getRenderHeight = function (useScreen) {
  8506. if (useScreen === void 0) { useScreen = false; }
  8507. if (!useScreen && this._currentRenderTarget) {
  8508. return this._currentRenderTarget._height;
  8509. }
  8510. return this._renderingCanvas.height;
  8511. };
  8512. Engine.prototype.getRenderingCanvas = function () {
  8513. return this._renderingCanvas;
  8514. };
  8515. Engine.prototype.getRenderingCanvasClientRect = function () {
  8516. return this._renderingCanvas.getBoundingClientRect();
  8517. };
  8518. Engine.prototype.setHardwareScalingLevel = function (level) {
  8519. this._hardwareScalingLevel = level;
  8520. this.resize();
  8521. };
  8522. Engine.prototype.getHardwareScalingLevel = function () {
  8523. return this._hardwareScalingLevel;
  8524. };
  8525. Engine.prototype.getLoadedTexturesCache = function () {
  8526. return this._loadedTexturesCache;
  8527. };
  8528. Engine.prototype.getCaps = function () {
  8529. return this._caps;
  8530. };
  8531. Object.defineProperty(Engine.prototype, "drawCalls", {
  8532. get: function () {
  8533. return this._drawCalls.current;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8539. get: function () {
  8540. return this._drawCalls;
  8541. },
  8542. enumerable: true,
  8543. configurable: true
  8544. });
  8545. Engine.prototype.getDepthFunction = function () {
  8546. return this._depthCullingState.depthFunc;
  8547. };
  8548. Engine.prototype.setDepthFunction = function (depthFunc) {
  8549. this._depthCullingState.depthFunc = depthFunc;
  8550. };
  8551. Engine.prototype.setDepthFunctionToGreater = function () {
  8552. this._depthCullingState.depthFunc = this._gl.GREATER;
  8553. };
  8554. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8555. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8556. };
  8557. Engine.prototype.setDepthFunctionToLess = function () {
  8558. this._depthCullingState.depthFunc = this._gl.LESS;
  8559. };
  8560. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8561. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8562. };
  8563. Engine.prototype.getStencilBuffer = function () {
  8564. return this._stencilState.stencilTest;
  8565. };
  8566. Engine.prototype.setStencilBuffer = function (enable) {
  8567. this._stencilState.stencilTest = enable;
  8568. };
  8569. Engine.prototype.getStencilMask = function () {
  8570. return this._stencilState.stencilMask;
  8571. };
  8572. Engine.prototype.setStencilMask = function (mask) {
  8573. this._stencilState.stencilMask = mask;
  8574. };
  8575. Engine.prototype.getStencilFunction = function () {
  8576. return this._stencilState.stencilFunc;
  8577. };
  8578. Engine.prototype.getStencilFunctionReference = function () {
  8579. return this._stencilState.stencilFuncRef;
  8580. };
  8581. Engine.prototype.getStencilFunctionMask = function () {
  8582. return this._stencilState.stencilFuncMask;
  8583. };
  8584. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8585. this._stencilState.stencilFunc = stencilFunc;
  8586. };
  8587. Engine.prototype.setStencilFunctionReference = function (reference) {
  8588. this._stencilState.stencilFuncRef = reference;
  8589. };
  8590. Engine.prototype.setStencilFunctionMask = function (mask) {
  8591. this._stencilState.stencilFuncMask = mask;
  8592. };
  8593. Engine.prototype.getStencilOperationFail = function () {
  8594. return this._stencilState.stencilOpStencilFail;
  8595. };
  8596. Engine.prototype.getStencilOperationDepthFail = function () {
  8597. return this._stencilState.stencilOpDepthFail;
  8598. };
  8599. Engine.prototype.getStencilOperationPass = function () {
  8600. return this._stencilState.stencilOpStencilDepthPass;
  8601. };
  8602. Engine.prototype.setStencilOperationFail = function (operation) {
  8603. this._stencilState.stencilOpStencilFail = operation;
  8604. };
  8605. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8606. this._stencilState.stencilOpDepthFail = operation;
  8607. };
  8608. Engine.prototype.setStencilOperationPass = function (operation) {
  8609. this._stencilState.stencilOpStencilDepthPass = operation;
  8610. };
  8611. /**
  8612. * stop executing a render loop function and remove it from the execution array
  8613. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8614. */
  8615. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8616. if (!renderFunction) {
  8617. this._activeRenderLoops = [];
  8618. return;
  8619. }
  8620. var index = this._activeRenderLoops.indexOf(renderFunction);
  8621. if (index >= 0) {
  8622. this._activeRenderLoops.splice(index, 1);
  8623. }
  8624. };
  8625. Engine.prototype._renderLoop = function () {
  8626. var shouldRender = true;
  8627. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8628. shouldRender = false;
  8629. }
  8630. if (shouldRender) {
  8631. // Start new frame
  8632. this.beginFrame();
  8633. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8634. var renderFunction = this._activeRenderLoops[index];
  8635. renderFunction();
  8636. }
  8637. // Present
  8638. this.endFrame();
  8639. }
  8640. if (this._activeRenderLoops.length > 0) {
  8641. // Register new frame
  8642. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8643. }
  8644. else {
  8645. this._renderingQueueLaunched = false;
  8646. }
  8647. };
  8648. /**
  8649. * Register and execute a render loop. The engine can have more than one render function.
  8650. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8651. * @example
  8652. * engine.runRenderLoop(function () {
  8653. * scene.render()
  8654. * })
  8655. */
  8656. Engine.prototype.runRenderLoop = function (renderFunction) {
  8657. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8658. return;
  8659. }
  8660. this._activeRenderLoops.push(renderFunction);
  8661. if (!this._renderingQueueLaunched) {
  8662. this._renderingQueueLaunched = true;
  8663. this._bindedRenderFunction = this._renderLoop.bind(this);
  8664. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8665. }
  8666. };
  8667. /**
  8668. * Toggle full screen mode.
  8669. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8670. * @param {any} options - an options object to be sent to the requestFullscreen function
  8671. */
  8672. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8673. if (this.isFullscreen) {
  8674. BABYLON.Tools.ExitFullscreen();
  8675. }
  8676. else {
  8677. this._pointerLockRequested = requestPointerLock;
  8678. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8679. }
  8680. };
  8681. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8682. if (stencil === void 0) { stencil = false; }
  8683. this.applyStates();
  8684. var mode = 0;
  8685. if (backBuffer && color) {
  8686. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8687. mode |= this._gl.COLOR_BUFFER_BIT;
  8688. }
  8689. if (depth) {
  8690. this._gl.clearDepth(1.0);
  8691. mode |= this._gl.DEPTH_BUFFER_BIT;
  8692. }
  8693. if (stencil) {
  8694. this._gl.clearStencil(0);
  8695. mode |= this._gl.STENCIL_BUFFER_BIT;
  8696. }
  8697. this._gl.clear(mode);
  8698. };
  8699. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8700. var gl = this._gl;
  8701. // Save state
  8702. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8703. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8704. // Change state
  8705. gl.enable(gl.SCISSOR_TEST);
  8706. gl.scissor(x, y, width, height);
  8707. // Clear
  8708. this.clear(clearColor, true, true, true);
  8709. // Restore state
  8710. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8711. if (curScissor === true) {
  8712. gl.enable(gl.SCISSOR_TEST);
  8713. }
  8714. else {
  8715. gl.disable(gl.SCISSOR_TEST);
  8716. }
  8717. };
  8718. /**
  8719. * Set the WebGL's viewport
  8720. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8721. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8722. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8723. */
  8724. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8725. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8726. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8727. var x = viewport.x || 0;
  8728. var y = viewport.y || 0;
  8729. this._cachedViewport = viewport;
  8730. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8731. };
  8732. /**
  8733. * Directly set the WebGL Viewport
  8734. * The x, y, width & height are directly passed to the WebGL call
  8735. * @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.
  8736. */
  8737. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8738. var currentViewport = this._cachedViewport;
  8739. this._cachedViewport = null;
  8740. this._gl.viewport(x, y, width, height);
  8741. return currentViewport;
  8742. };
  8743. Engine.prototype.beginFrame = function () {
  8744. this._measureFps();
  8745. };
  8746. Engine.prototype.endFrame = function () {
  8747. //force a flush in case we are using a bad OS.
  8748. if (this._badOS) {
  8749. this.flushFramebuffer();
  8750. }
  8751. //submit frame to the vr device, if enabled
  8752. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8753. this._vrDisplayEnabled.submitFrame();
  8754. }
  8755. };
  8756. /**
  8757. * resize the view according to the canvas' size.
  8758. * @example
  8759. * window.addEventListener("resize", function () {
  8760. * engine.resize();
  8761. * });
  8762. */
  8763. Engine.prototype.resize = function () {
  8764. // We're not resizing the size of the canvas while in VR mode & presenting
  8765. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8766. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8767. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8768. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8769. }
  8770. };
  8771. /**
  8772. * force a specific size of the canvas
  8773. * @param {number} width - the new canvas' width
  8774. * @param {number} height - the new canvas' height
  8775. */
  8776. Engine.prototype.setSize = function (width, height) {
  8777. this._renderingCanvas.width = width;
  8778. this._renderingCanvas.height = height;
  8779. for (var index = 0; index < this.scenes.length; index++) {
  8780. var scene = this.scenes[index];
  8781. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8782. var cam = scene.cameras[camIndex];
  8783. cam._currentRenderId = 0;
  8784. }
  8785. }
  8786. };
  8787. //WebVR functions
  8788. Engine.prototype.initWebVR = function () {
  8789. if (!this.vrDisplaysPromise) {
  8790. this._getVRDisplays();
  8791. }
  8792. };
  8793. Engine.prototype.enableVR = function (vrDevice) {
  8794. this._vrDisplayEnabled = vrDevice;
  8795. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8796. };
  8797. Engine.prototype.disableVR = function () {
  8798. if (this._vrDisplayEnabled) {
  8799. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8800. }
  8801. };
  8802. Engine.prototype._getVRDisplays = function () {
  8803. var _this = this;
  8804. var getWebVRDevices = function (devices) {
  8805. var size = devices.length;
  8806. var i = 0;
  8807. _this._vrDisplays = devices.filter(function (device) {
  8808. return devices[i] instanceof VRDisplay;
  8809. });
  8810. return _this._vrDisplays;
  8811. };
  8812. //using a key due to typescript
  8813. if (navigator.getVRDisplays) {
  8814. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8815. }
  8816. };
  8817. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8818. this._currentRenderTarget = texture;
  8819. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8820. var gl = this._gl;
  8821. if (texture.isCube) {
  8822. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8823. }
  8824. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8825. this.wipeCaches();
  8826. };
  8827. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8828. if (this._currentFramebuffer !== framebuffer) {
  8829. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8830. this._currentFramebuffer = framebuffer;
  8831. }
  8832. };
  8833. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8834. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8835. this._currentRenderTarget = null;
  8836. // If MSAA, we need to bitblt back to main texture
  8837. var gl = this._gl;
  8838. if (texture._MSAAFramebuffer) {
  8839. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8840. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8841. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8842. }
  8843. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8844. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8845. gl.generateMipmap(gl.TEXTURE_2D);
  8846. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8847. }
  8848. if (onBeforeUnbind) {
  8849. if (texture._MSAAFramebuffer) {
  8850. // Bind the correct framebuffer
  8851. this.bindUnboundFramebuffer(texture._framebuffer);
  8852. }
  8853. onBeforeUnbind();
  8854. }
  8855. this.bindUnboundFramebuffer(null);
  8856. };
  8857. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8858. if (texture.generateMipMaps) {
  8859. var gl = this._gl;
  8860. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8861. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8862. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8863. }
  8864. };
  8865. Engine.prototype.flushFramebuffer = function () {
  8866. this._gl.flush();
  8867. };
  8868. Engine.prototype.restoreDefaultFramebuffer = function () {
  8869. this._currentRenderTarget = null;
  8870. this.bindUnboundFramebuffer(null);
  8871. this.setViewport(this._cachedViewport);
  8872. this.wipeCaches();
  8873. };
  8874. // VBOs
  8875. Engine.prototype._resetVertexBufferBinding = function () {
  8876. this.bindArrayBuffer(null);
  8877. this._cachedVertexBuffers = null;
  8878. };
  8879. Engine.prototype.createVertexBuffer = function (vertices) {
  8880. var vbo = this._gl.createBuffer();
  8881. this.bindArrayBuffer(vbo);
  8882. if (vertices instanceof Float32Array) {
  8883. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8884. }
  8885. else {
  8886. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8887. }
  8888. this._resetVertexBufferBinding();
  8889. vbo.references = 1;
  8890. return vbo;
  8891. };
  8892. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8893. var vbo = this._gl.createBuffer();
  8894. this.bindArrayBuffer(vbo);
  8895. if (vertices instanceof Float32Array) {
  8896. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8897. }
  8898. else {
  8899. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8900. }
  8901. this._resetVertexBufferBinding();
  8902. vbo.references = 1;
  8903. return vbo;
  8904. };
  8905. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8906. this.bindArrayBuffer(vertexBuffer);
  8907. if (offset === undefined) {
  8908. offset = 0;
  8909. }
  8910. if (count === undefined) {
  8911. if (vertices instanceof Float32Array) {
  8912. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8913. }
  8914. else {
  8915. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8916. }
  8917. }
  8918. else {
  8919. if (vertices instanceof Float32Array) {
  8920. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8921. }
  8922. else {
  8923. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8924. }
  8925. }
  8926. this._resetVertexBufferBinding();
  8927. };
  8928. Engine.prototype._resetIndexBufferBinding = function () {
  8929. this.bindIndexBuffer(null);
  8930. this._cachedIndexBuffer = null;
  8931. };
  8932. Engine.prototype.createIndexBuffer = function (indices) {
  8933. var vbo = this._gl.createBuffer();
  8934. this.bindIndexBuffer(vbo);
  8935. // Check for 32 bits indices
  8936. var arrayBuffer;
  8937. var need32Bits = false;
  8938. if (indices instanceof Uint16Array) {
  8939. arrayBuffer = indices;
  8940. }
  8941. else {
  8942. //check 32 bit support
  8943. if (this._caps.uintIndices) {
  8944. if (indices instanceof Uint32Array) {
  8945. arrayBuffer = indices;
  8946. need32Bits = true;
  8947. }
  8948. else {
  8949. //number[] or Int32Array, check if 32 bit is necessary
  8950. for (var index = 0; index < indices.length; index++) {
  8951. if (indices[index] > 65535) {
  8952. need32Bits = true;
  8953. break;
  8954. }
  8955. }
  8956. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8957. }
  8958. }
  8959. else {
  8960. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8961. arrayBuffer = new Uint16Array(indices);
  8962. }
  8963. }
  8964. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8965. this._resetIndexBufferBinding();
  8966. vbo.references = 1;
  8967. vbo.is32Bits = need32Bits;
  8968. return vbo;
  8969. };
  8970. Engine.prototype.bindArrayBuffer = function (buffer) {
  8971. if (!this._vaoRecordInProgress) {
  8972. this._unBindVertexArrayObject();
  8973. }
  8974. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8975. };
  8976. Engine.prototype.bindIndexBuffer = function (buffer) {
  8977. if (!this._vaoRecordInProgress) {
  8978. this._unBindVertexArrayObject();
  8979. }
  8980. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8981. };
  8982. Engine.prototype.bindBuffer = function (buffer, target) {
  8983. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8984. this._gl.bindBuffer(target, buffer);
  8985. this._currentBoundBuffer[target] = buffer;
  8986. }
  8987. };
  8988. Engine.prototype.updateArrayBuffer = function (data) {
  8989. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8990. };
  8991. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8992. var pointer = this._currentBufferPointers[indx];
  8993. var changed = false;
  8994. if (!pointer) {
  8995. changed = true;
  8996. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8997. }
  8998. else {
  8999. if (pointer.buffer !== buffer) {
  9000. pointer.buffer = buffer;
  9001. changed = true;
  9002. }
  9003. if (pointer.size !== size) {
  9004. pointer.size = size;
  9005. changed = true;
  9006. }
  9007. if (pointer.type !== type) {
  9008. pointer.type = type;
  9009. changed = true;
  9010. }
  9011. if (pointer.normalized !== normalized) {
  9012. pointer.normalized = normalized;
  9013. changed = true;
  9014. }
  9015. if (pointer.stride !== stride) {
  9016. pointer.stride = stride;
  9017. changed = true;
  9018. }
  9019. if (pointer.offset !== offset) {
  9020. pointer.offset = offset;
  9021. changed = true;
  9022. }
  9023. }
  9024. if (changed || this._vaoRecordInProgress) {
  9025. this.bindArrayBuffer(buffer);
  9026. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9027. }
  9028. };
  9029. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9030. if (indexBuffer == null) {
  9031. return;
  9032. }
  9033. if (this._cachedIndexBuffer !== indexBuffer) {
  9034. this._cachedIndexBuffer = indexBuffer;
  9035. this.bindIndexBuffer(indexBuffer);
  9036. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9037. }
  9038. };
  9039. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9040. var attributes = effect.getAttributesNames();
  9041. if (!this._vaoRecordInProgress) {
  9042. this._unBindVertexArrayObject();
  9043. }
  9044. this.unbindAllAttributes();
  9045. for (var index = 0; index < attributes.length; index++) {
  9046. var order = effect.getAttributeLocation(index);
  9047. if (order >= 0) {
  9048. var vertexBuffer = vertexBuffers[attributes[index]];
  9049. if (!vertexBuffer) {
  9050. continue;
  9051. }
  9052. this._gl.enableVertexAttribArray(order);
  9053. if (!this._vaoRecordInProgress) {
  9054. this._vertexAttribArraysEnabled[order] = true;
  9055. }
  9056. var buffer = vertexBuffer.getBuffer();
  9057. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9058. if (vertexBuffer.getIsInstanced()) {
  9059. this._gl.vertexAttribDivisor(order, 1);
  9060. if (!this._vaoRecordInProgress) {
  9061. this._currentInstanceLocations.push(order);
  9062. this._currentInstanceBuffers.push(buffer);
  9063. }
  9064. }
  9065. }
  9066. }
  9067. };
  9068. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9069. var vao = this._gl.createVertexArray();
  9070. this._vaoRecordInProgress = true;
  9071. this._gl.bindVertexArray(vao);
  9072. this._mustWipeVertexAttributes = true;
  9073. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9074. this.bindIndexBuffer(indexBuffer);
  9075. this._vaoRecordInProgress = false;
  9076. this._gl.bindVertexArray(null);
  9077. return vao;
  9078. };
  9079. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9080. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9081. this._cachedVertexArrayObject = vertexArrayObject;
  9082. this._gl.bindVertexArray(vertexArrayObject);
  9083. this._cachedVertexBuffers = null;
  9084. this._cachedIndexBuffer = null;
  9085. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9086. this._mustWipeVertexAttributes = true;
  9087. }
  9088. };
  9089. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9090. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9091. this._cachedVertexBuffers = vertexBuffer;
  9092. this._cachedEffectForVertexBuffers = effect;
  9093. var attributesCount = effect.getAttributesCount();
  9094. this._unBindVertexArrayObject();
  9095. this.unbindAllAttributes();
  9096. var offset = 0;
  9097. for (var index = 0; index < attributesCount; index++) {
  9098. if (index < vertexDeclaration.length) {
  9099. var order = effect.getAttributeLocation(index);
  9100. if (order >= 0) {
  9101. this._gl.enableVertexAttribArray(order);
  9102. this._vertexAttribArraysEnabled[order] = true;
  9103. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9104. }
  9105. offset += vertexDeclaration[index] * 4;
  9106. }
  9107. }
  9108. }
  9109. this._bindIndexBufferWithCache(indexBuffer);
  9110. };
  9111. Engine.prototype._unBindVertexArrayObject = function () {
  9112. if (!this._cachedVertexArrayObject) {
  9113. return;
  9114. }
  9115. this._cachedVertexArrayObject = null;
  9116. this._gl.bindVertexArray(null);
  9117. };
  9118. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9119. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9120. this._cachedVertexBuffers = vertexBuffers;
  9121. this._cachedEffectForVertexBuffers = effect;
  9122. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9123. }
  9124. this._bindIndexBufferWithCache(indexBuffer);
  9125. };
  9126. Engine.prototype.unbindInstanceAttributes = function () {
  9127. var boundBuffer;
  9128. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9129. var instancesBuffer = this._currentInstanceBuffers[i];
  9130. if (boundBuffer != instancesBuffer) {
  9131. boundBuffer = instancesBuffer;
  9132. this.bindArrayBuffer(instancesBuffer);
  9133. }
  9134. var offsetLocation = this._currentInstanceLocations[i];
  9135. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9136. }
  9137. this._currentInstanceBuffers.length = 0;
  9138. this._currentInstanceLocations.length = 0;
  9139. };
  9140. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9141. this._gl.deleteVertexArray(vao);
  9142. };
  9143. Engine.prototype._releaseBuffer = function (buffer) {
  9144. buffer.references--;
  9145. if (buffer.references === 0) {
  9146. this._gl.deleteBuffer(buffer);
  9147. return true;
  9148. }
  9149. return false;
  9150. };
  9151. Engine.prototype.createInstancesBuffer = function (capacity) {
  9152. var buffer = this._gl.createBuffer();
  9153. buffer.capacity = capacity;
  9154. this.bindArrayBuffer(buffer);
  9155. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9156. return buffer;
  9157. };
  9158. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9159. this._gl.deleteBuffer(buffer);
  9160. };
  9161. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9162. this.bindArrayBuffer(instancesBuffer);
  9163. if (data) {
  9164. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9165. }
  9166. if (offsetLocations[0].index !== undefined) {
  9167. var stride = 0;
  9168. for (var i = 0; i < offsetLocations.length; i++) {
  9169. var ai = offsetLocations[i];
  9170. stride += ai.attributeSize * 4;
  9171. }
  9172. for (var i = 0; i < offsetLocations.length; i++) {
  9173. var ai = offsetLocations[i];
  9174. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9175. this._gl.enableVertexAttribArray(ai.index);
  9176. this._vertexAttribArraysEnabled[ai.index] = true;
  9177. }
  9178. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9179. this._gl.vertexAttribDivisor(ai.index, 1);
  9180. this._currentInstanceLocations.push(ai.index);
  9181. this._currentInstanceBuffers.push(instancesBuffer);
  9182. }
  9183. }
  9184. else {
  9185. for (var index = 0; index < 4; index++) {
  9186. var offsetLocation = offsetLocations[index];
  9187. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9188. this._gl.enableVertexAttribArray(offsetLocation);
  9189. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9190. }
  9191. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9192. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9193. this._currentInstanceLocations.push(offsetLocation);
  9194. this._currentInstanceBuffers.push(instancesBuffer);
  9195. }
  9196. }
  9197. };
  9198. Engine.prototype.applyStates = function () {
  9199. this._depthCullingState.apply(this._gl);
  9200. this._stencilState.apply(this._gl);
  9201. this._alphaState.apply(this._gl);
  9202. };
  9203. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9204. // Apply states
  9205. this.applyStates();
  9206. this._drawCalls.addCount(1, false);
  9207. // Render
  9208. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9209. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9210. if (instancesCount) {
  9211. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9212. return;
  9213. }
  9214. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9215. };
  9216. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9217. // Apply states
  9218. this.applyStates();
  9219. this._drawCalls.addCount(1, false);
  9220. if (instancesCount) {
  9221. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9222. return;
  9223. }
  9224. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9225. };
  9226. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9227. // Apply states
  9228. this.applyStates();
  9229. this._drawCalls.addCount(1, false);
  9230. if (instancesCount) {
  9231. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9232. return;
  9233. }
  9234. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9235. };
  9236. // Shaders
  9237. Engine.prototype._releaseEffect = function (effect) {
  9238. if (this._compiledEffects[effect._key]) {
  9239. delete this._compiledEffects[effect._key];
  9240. if (effect.getProgram()) {
  9241. this._gl.deleteProgram(effect.getProgram());
  9242. }
  9243. }
  9244. };
  9245. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9246. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9247. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9248. var name = vertex + "+" + fragment + "@" + defines;
  9249. if (this._compiledEffects[name]) {
  9250. return this._compiledEffects[name];
  9251. }
  9252. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9253. effect._key = name;
  9254. this._compiledEffects[name] = effect;
  9255. return effect;
  9256. };
  9257. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9258. if (uniformsNames === void 0) { uniformsNames = []; }
  9259. if (samplers === void 0) { samplers = []; }
  9260. if (defines === void 0) { defines = ""; }
  9261. return this.createEffect({
  9262. vertex: "particles",
  9263. fragmentElement: fragmentName
  9264. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9265. };
  9266. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9267. context = context || this._gl;
  9268. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9269. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9270. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9271. var shaderProgram = context.createProgram();
  9272. context.attachShader(shaderProgram, vertexShader);
  9273. context.attachShader(shaderProgram, fragmentShader);
  9274. context.linkProgram(shaderProgram);
  9275. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9276. if (!linked) {
  9277. var error = context.getProgramInfoLog(shaderProgram);
  9278. if (error) {
  9279. throw new Error(error);
  9280. }
  9281. }
  9282. context.deleteShader(vertexShader);
  9283. context.deleteShader(fragmentShader);
  9284. return shaderProgram;
  9285. };
  9286. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9287. var results = [];
  9288. for (var index = 0; index < uniformsNames.length; index++) {
  9289. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9290. }
  9291. return results;
  9292. };
  9293. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9294. var results = [];
  9295. for (var index = 0; index < attributesNames.length; index++) {
  9296. try {
  9297. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9298. }
  9299. catch (e) {
  9300. results.push(-1);
  9301. }
  9302. }
  9303. return results;
  9304. };
  9305. Engine.prototype.enableEffect = function (effect) {
  9306. // Use program
  9307. this.setProgram(effect.getProgram());
  9308. this._currentEffect = effect;
  9309. if (effect.onBind) {
  9310. effect.onBind(effect);
  9311. }
  9312. };
  9313. Engine.prototype.setIntArray = function (uniform, array) {
  9314. if (!uniform)
  9315. return;
  9316. this._gl.uniform1iv(uniform, array);
  9317. };
  9318. Engine.prototype.setIntArray2 = function (uniform, array) {
  9319. if (!uniform || array.length % 2 !== 0)
  9320. return;
  9321. this._gl.uniform2iv(uniform, array);
  9322. };
  9323. Engine.prototype.setIntArray3 = function (uniform, array) {
  9324. if (!uniform || array.length % 3 !== 0)
  9325. return;
  9326. this._gl.uniform3iv(uniform, array);
  9327. };
  9328. Engine.prototype.setIntArray4 = function (uniform, array) {
  9329. if (!uniform || array.length % 4 !== 0)
  9330. return;
  9331. this._gl.uniform4iv(uniform, array);
  9332. };
  9333. Engine.prototype.setFloatArray = function (uniform, array) {
  9334. if (!uniform)
  9335. return;
  9336. this._gl.uniform1fv(uniform, array);
  9337. };
  9338. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9339. if (!uniform || array.length % 2 !== 0)
  9340. return;
  9341. this._gl.uniform2fv(uniform, array);
  9342. };
  9343. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9344. if (!uniform || array.length % 3 !== 0)
  9345. return;
  9346. this._gl.uniform3fv(uniform, array);
  9347. };
  9348. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9349. if (!uniform || array.length % 4 !== 0)
  9350. return;
  9351. this._gl.uniform4fv(uniform, array);
  9352. };
  9353. Engine.prototype.setArray = function (uniform, array) {
  9354. if (!uniform)
  9355. return;
  9356. this._gl.uniform1fv(uniform, array);
  9357. };
  9358. Engine.prototype.setArray2 = function (uniform, array) {
  9359. if (!uniform || array.length % 2 !== 0)
  9360. return;
  9361. this._gl.uniform2fv(uniform, array);
  9362. };
  9363. Engine.prototype.setArray3 = function (uniform, array) {
  9364. if (!uniform || array.length % 3 !== 0)
  9365. return;
  9366. this._gl.uniform3fv(uniform, array);
  9367. };
  9368. Engine.prototype.setArray4 = function (uniform, array) {
  9369. if (!uniform || array.length % 4 !== 0)
  9370. return;
  9371. this._gl.uniform4fv(uniform, array);
  9372. };
  9373. Engine.prototype.setMatrices = function (uniform, matrices) {
  9374. if (!uniform)
  9375. return;
  9376. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9377. };
  9378. Engine.prototype.setMatrix = function (uniform, matrix) {
  9379. if (!uniform)
  9380. return;
  9381. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9382. };
  9383. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9384. if (!uniform)
  9385. return;
  9386. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9387. };
  9388. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9389. if (!uniform)
  9390. return;
  9391. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9392. };
  9393. Engine.prototype.setFloat = function (uniform, value) {
  9394. if (!uniform)
  9395. return;
  9396. this._gl.uniform1f(uniform, value);
  9397. };
  9398. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9399. if (!uniform)
  9400. return;
  9401. this._gl.uniform2f(uniform, x, y);
  9402. };
  9403. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9404. if (!uniform)
  9405. return;
  9406. this._gl.uniform3f(uniform, x, y, z);
  9407. };
  9408. Engine.prototype.setBool = function (uniform, bool) {
  9409. if (!uniform)
  9410. return;
  9411. this._gl.uniform1i(uniform, bool);
  9412. };
  9413. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9414. if (!uniform)
  9415. return;
  9416. this._gl.uniform4f(uniform, x, y, z, w);
  9417. };
  9418. Engine.prototype.setColor3 = function (uniform, color3) {
  9419. if (!uniform)
  9420. return;
  9421. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9422. };
  9423. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9424. if (!uniform)
  9425. return;
  9426. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9427. };
  9428. // States
  9429. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9430. if (zOffset === void 0) { zOffset = 0; }
  9431. if (reverseSide === void 0) { reverseSide = false; }
  9432. // Culling
  9433. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9434. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9435. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9436. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9437. if (culling) {
  9438. this._depthCullingState.cullFace = cullFace;
  9439. this._depthCullingState.cull = true;
  9440. }
  9441. else {
  9442. this._depthCullingState.cull = false;
  9443. }
  9444. }
  9445. // Z offset
  9446. this._depthCullingState.zOffset = zOffset;
  9447. };
  9448. Engine.prototype.setDepthBuffer = function (enable) {
  9449. this._depthCullingState.depthTest = enable;
  9450. };
  9451. Engine.prototype.getDepthWrite = function () {
  9452. return this._depthCullingState.depthMask;
  9453. };
  9454. Engine.prototype.setDepthWrite = function (enable) {
  9455. this._depthCullingState.depthMask = enable;
  9456. };
  9457. Engine.prototype.setColorWrite = function (enable) {
  9458. this._gl.colorMask(enable, enable, enable, enable);
  9459. };
  9460. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9461. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9462. if (this._alphaMode === mode) {
  9463. return;
  9464. }
  9465. switch (mode) {
  9466. case Engine.ALPHA_DISABLE:
  9467. this._alphaState.alphaBlend = false;
  9468. break;
  9469. case Engine.ALPHA_PREMULTIPLIED:
  9470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9471. this._alphaState.alphaBlend = true;
  9472. break;
  9473. case Engine.ALPHA_COMBINE:
  9474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9475. this._alphaState.alphaBlend = true;
  9476. break;
  9477. case Engine.ALPHA_ONEONE:
  9478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9479. this._alphaState.alphaBlend = true;
  9480. break;
  9481. case Engine.ALPHA_ADD:
  9482. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9483. this._alphaState.alphaBlend = true;
  9484. break;
  9485. case Engine.ALPHA_SUBTRACT:
  9486. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9487. this._alphaState.alphaBlend = true;
  9488. break;
  9489. case Engine.ALPHA_MULTIPLY:
  9490. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9491. this._alphaState.alphaBlend = true;
  9492. break;
  9493. case Engine.ALPHA_MAXIMIZED:
  9494. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9495. this._alphaState.alphaBlend = true;
  9496. break;
  9497. }
  9498. if (!noDepthWriteChange) {
  9499. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9500. }
  9501. this._alphaMode = mode;
  9502. };
  9503. Engine.prototype.getAlphaMode = function () {
  9504. return this._alphaMode;
  9505. };
  9506. Engine.prototype.setAlphaTesting = function (enable) {
  9507. this._alphaTest = enable;
  9508. };
  9509. Engine.prototype.getAlphaTesting = function () {
  9510. return this._alphaTest;
  9511. };
  9512. // Textures
  9513. Engine.prototype.wipeCaches = function () {
  9514. if (this.preventCacheWipeBetweenFrames) {
  9515. return;
  9516. }
  9517. this.resetTextureCache();
  9518. this._currentEffect = null;
  9519. this._stencilState.reset();
  9520. this._depthCullingState.reset();
  9521. this.setDepthFunctionToLessOrEqual();
  9522. this._alphaState.reset();
  9523. this._cachedVertexBuffers = null;
  9524. this._cachedIndexBuffer = null;
  9525. this._cachedEffectForVertexBuffers = null;
  9526. this._unBindVertexArrayObject();
  9527. this.bindIndexBuffer(null);
  9528. this.bindArrayBuffer(null);
  9529. };
  9530. /**
  9531. * Set the compressed texture format to use, based on the formats you have, and the formats
  9532. * supported by the hardware / browser.
  9533. *
  9534. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9535. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9536. * to API arguments needed to compressed textures. This puts the burden on the container
  9537. * generator to house the arcane code for determining these for current & future formats.
  9538. *
  9539. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9540. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9541. *
  9542. * Note: The result of this call is not taken into account when a texture is base64.
  9543. *
  9544. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9545. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9546. *
  9547. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  9548. * @returns The extension selected.
  9549. */
  9550. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9551. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9552. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9553. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9554. return this._textureFormatInUse = this._texturesSupported[i];
  9555. }
  9556. }
  9557. }
  9558. // actively set format to nothing, to allow this to be called more than once
  9559. // and possibly fail the 2nd time
  9560. return this._textureFormatInUse = null;
  9561. };
  9562. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9563. var _this = this;
  9564. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9565. if (onLoad === void 0) { onLoad = null; }
  9566. if (onError === void 0) { onError = null; }
  9567. if (buffer === void 0) { buffer = null; }
  9568. var texture = fallBack ? fallBack : this._gl.createTexture();
  9569. var extension;
  9570. var isKTX = false;
  9571. var fromData = false;
  9572. var url = String(urlArg);
  9573. if (url.substr(0, 5) === "data:") {
  9574. fromData = true;
  9575. }
  9576. if (!fromData) {
  9577. var lastDot = url.lastIndexOf('.');
  9578. extension = url.substring(lastDot).toLowerCase();
  9579. if (this._textureFormatInUse && !fromData && !fallBack) {
  9580. extension = this._textureFormatInUse;
  9581. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9582. isKTX = true;
  9583. }
  9584. }
  9585. else {
  9586. var oldUrl = url;
  9587. fromData = oldUrl.split(':');
  9588. url = oldUrl;
  9589. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  9590. }
  9591. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9592. var isTGA = (extension === ".tga");
  9593. scene._addPendingData(texture);
  9594. texture.url = url;
  9595. texture.noMipmap = noMipmap;
  9596. texture.references = 1;
  9597. texture.samplingMode = samplingMode;
  9598. texture.onLoadedCallbacks = [];
  9599. if (onLoad) {
  9600. texture.onLoadedCallbacks.push(onLoad);
  9601. }
  9602. if (!fallBack)
  9603. this._loadedTexturesCache.push(texture);
  9604. var onerror = function () {
  9605. scene._removePendingData(texture);
  9606. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9607. if (isKTX) {
  9608. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  9609. }
  9610. else if (onError) {
  9611. onError();
  9612. }
  9613. };
  9614. var callback;
  9615. if (isKTX || isTGA || isDDS) {
  9616. if (isKTX) {
  9617. callback = function (data) {
  9618. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9619. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9620. ktx.uploadLevels(_this._gl, !noMipmap);
  9621. }, samplingMode);
  9622. };
  9623. }
  9624. else if (isTGA) {
  9625. callback = function (arrayBuffer) {
  9626. var data = new Uint8Array(arrayBuffer);
  9627. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9628. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9629. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9630. }, samplingMode);
  9631. };
  9632. }
  9633. else if (isDDS) {
  9634. callback = function (data) {
  9635. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9636. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9637. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9638. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9639. }, samplingMode);
  9640. };
  9641. }
  9642. if (!(fromData instanceof Array))
  9643. BABYLON.Tools.LoadFile(url, function (data) {
  9644. callback(data);
  9645. }, null, scene.database, true, onerror);
  9646. else
  9647. callback(buffer);
  9648. }
  9649. else {
  9650. var onload = function (img) {
  9651. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9652. var isPot = (img.width === potWidth && img.height === potHeight);
  9653. if (!isPot) {
  9654. _this._prepareWorkingCanvas();
  9655. _this._workingCanvas.width = potWidth;
  9656. _this._workingCanvas.height = potHeight;
  9657. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9658. _this._workingContext.imageSmoothingEnabled = false;
  9659. _this._workingContext.mozImageSmoothingEnabled = false;
  9660. _this._workingContext.oImageSmoothingEnabled = false;
  9661. _this._workingContext.webkitImageSmoothingEnabled = false;
  9662. _this._workingContext.msImageSmoothingEnabled = false;
  9663. }
  9664. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9665. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9666. _this._workingContext.imageSmoothingEnabled = true;
  9667. _this._workingContext.mozImageSmoothingEnabled = true;
  9668. _this._workingContext.oImageSmoothingEnabled = true;
  9669. _this._workingContext.webkitImageSmoothingEnabled = true;
  9670. _this._workingContext.msImageSmoothingEnabled = true;
  9671. }
  9672. }
  9673. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9674. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9675. }, samplingMode);
  9676. };
  9677. if (!(fromData instanceof Array))
  9678. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9679. else
  9680. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9681. }
  9682. return texture;
  9683. };
  9684. Engine.prototype._getInternalFormat = function (format) {
  9685. var internalFormat = this._gl.RGBA;
  9686. switch (format) {
  9687. case Engine.TEXTUREFORMAT_ALPHA:
  9688. internalFormat = this._gl.ALPHA;
  9689. break;
  9690. case Engine.TEXTUREFORMAT_LUMINANCE:
  9691. internalFormat = this._gl.LUMINANCE;
  9692. break;
  9693. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9694. internalFormat = this._gl.LUMINANCE_ALPHA;
  9695. break;
  9696. case Engine.TEXTUREFORMAT_RGB:
  9697. internalFormat = this._gl.RGB;
  9698. break;
  9699. case Engine.TEXTUREFORMAT_RGBA:
  9700. internalFormat = this._gl.RGBA;
  9701. break;
  9702. }
  9703. return internalFormat;
  9704. };
  9705. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9706. if (compression === void 0) { compression = null; }
  9707. var internalFormat = this._getInternalFormat(format);
  9708. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9709. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9710. if (texture._width % 4 !== 0) {
  9711. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9712. }
  9713. if (compression) {
  9714. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9715. }
  9716. else {
  9717. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9718. }
  9719. if (texture.generateMipMaps) {
  9720. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9721. }
  9722. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9723. this.resetTextureCache();
  9724. texture.isReady = true;
  9725. };
  9726. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9727. if (compression === void 0) { compression = null; }
  9728. var texture = this._gl.createTexture();
  9729. texture._baseWidth = width;
  9730. texture._baseHeight = height;
  9731. texture._width = width;
  9732. texture._height = height;
  9733. texture.references = 1;
  9734. this.updateRawTexture(texture, data, format, invertY, compression);
  9735. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9736. // Filters
  9737. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9738. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9739. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9740. if (generateMipMaps) {
  9741. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9742. }
  9743. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9744. texture.samplingMode = samplingMode;
  9745. this._loadedTexturesCache.push(texture);
  9746. return texture;
  9747. };
  9748. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9749. var texture = this._gl.createTexture();
  9750. texture._baseWidth = width;
  9751. texture._baseHeight = height;
  9752. if (generateMipMaps) {
  9753. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9754. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9755. }
  9756. this.resetTextureCache();
  9757. texture._width = width;
  9758. texture._height = height;
  9759. texture.isReady = false;
  9760. texture.generateMipMaps = generateMipMaps;
  9761. texture.references = 1;
  9762. texture.samplingMode = samplingMode;
  9763. this.updateTextureSamplingMode(samplingMode, texture);
  9764. this._loadedTexturesCache.push(texture);
  9765. return texture;
  9766. };
  9767. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9768. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9769. if (texture.isCube) {
  9770. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9771. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9772. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9773. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9774. }
  9775. else {
  9776. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9777. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9778. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9779. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9780. }
  9781. texture.samplingMode = samplingMode;
  9782. };
  9783. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9784. if (premulAlpha === void 0) { premulAlpha = false; }
  9785. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9786. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9787. if (premulAlpha) {
  9788. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9789. }
  9790. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9791. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9792. if (texture.generateMipMaps) {
  9793. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9794. }
  9795. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9796. if (premulAlpha) {
  9797. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9798. }
  9799. this.resetTextureCache();
  9800. texture.isReady = true;
  9801. };
  9802. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9803. if (texture._isDisabled) {
  9804. return;
  9805. }
  9806. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9807. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9808. try {
  9809. // Testing video texture support
  9810. if (this._videoTextureSupported === undefined) {
  9811. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9812. if (this._gl.getError() !== 0) {
  9813. this._videoTextureSupported = false;
  9814. }
  9815. else {
  9816. this._videoTextureSupported = true;
  9817. }
  9818. }
  9819. // Copy video through the current working canvas if video texture is not supported
  9820. if (!this._videoTextureSupported) {
  9821. if (!texture._workingCanvas) {
  9822. texture._workingCanvas = document.createElement("canvas");
  9823. texture._workingContext = texture._workingCanvas.getContext("2d");
  9824. texture._workingCanvas.width = texture._width;
  9825. texture._workingCanvas.height = texture._height;
  9826. }
  9827. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9828. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9829. }
  9830. else {
  9831. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9832. }
  9833. if (texture.generateMipMaps) {
  9834. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9835. }
  9836. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9837. this.resetTextureCache();
  9838. texture.isReady = true;
  9839. }
  9840. catch (ex) {
  9841. // Something unexpected
  9842. // Let's disable the texture
  9843. texture._isDisabled = true;
  9844. }
  9845. };
  9846. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9847. // old version had a "generateMipMaps" arg instead of options.
  9848. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9849. // in the same way, generateDepthBuffer is defaulted to true
  9850. var generateMipMaps = false;
  9851. var generateDepthBuffer = true;
  9852. var generateStencilBuffer = false;
  9853. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9854. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9855. if (options !== undefined) {
  9856. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9857. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9858. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9859. type = options.type === undefined ? type : options.type;
  9860. if (options.samplingMode !== undefined) {
  9861. samplingMode = options.samplingMode;
  9862. }
  9863. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9864. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9865. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9866. }
  9867. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9868. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9869. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9870. }
  9871. }
  9872. var gl = this._gl;
  9873. var texture = gl.createTexture();
  9874. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9875. var width = size.width || size;
  9876. var height = size.height || size;
  9877. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9878. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9879. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9880. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9881. }
  9882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9886. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9887. // Create the framebuffer
  9888. var framebuffer = gl.createFramebuffer();
  9889. this.bindUnboundFramebuffer(framebuffer);
  9890. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9891. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9892. if (generateMipMaps) {
  9893. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9894. }
  9895. // Unbind
  9896. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9897. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9898. this.bindUnboundFramebuffer(null);
  9899. texture._framebuffer = framebuffer;
  9900. texture._baseWidth = width;
  9901. texture._baseHeight = height;
  9902. texture._width = width;
  9903. texture._height = height;
  9904. texture.isReady = true;
  9905. texture.samples = 1;
  9906. texture.generateMipMaps = generateMipMaps;
  9907. texture.references = 1;
  9908. texture.samplingMode = samplingMode;
  9909. texture.type = type;
  9910. texture._generateDepthBuffer = generateDepthBuffer;
  9911. texture._generateStencilBuffer = generateStencilBuffer;
  9912. this.resetTextureCache();
  9913. this._loadedTexturesCache.push(texture);
  9914. return texture;
  9915. };
  9916. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9917. if (samples === void 0) { samples = 1; }
  9918. var depthStencilBuffer = null;
  9919. var gl = this._gl;
  9920. // Create the depth/stencil buffer
  9921. if (generateStencilBuffer) {
  9922. depthStencilBuffer = gl.createRenderbuffer();
  9923. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9924. if (samples > 1) {
  9925. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9926. }
  9927. else {
  9928. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9929. }
  9930. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9931. }
  9932. else if (generateDepthBuffer) {
  9933. depthStencilBuffer = gl.createRenderbuffer();
  9934. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9935. if (samples > 1) {
  9936. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9937. }
  9938. else {
  9939. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9940. }
  9941. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9942. }
  9943. return depthStencilBuffer;
  9944. };
  9945. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9946. if (this.webGLVersion < 2) {
  9947. return 1;
  9948. }
  9949. if (texture.samples === samples) {
  9950. return samples;
  9951. }
  9952. var gl = this._gl;
  9953. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9954. // Dispose previous render buffers
  9955. if (texture._depthStencilBuffer) {
  9956. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9957. }
  9958. if (texture._MSAAFramebuffer) {
  9959. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9960. }
  9961. if (texture._MSAARenderBuffer) {
  9962. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9963. }
  9964. if (samples > 1) {
  9965. texture._MSAAFramebuffer = gl.createFramebuffer();
  9966. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9967. var colorRenderbuffer = gl.createRenderbuffer();
  9968. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9969. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9970. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9971. texture._MSAARenderBuffer = colorRenderbuffer;
  9972. }
  9973. else {
  9974. this.bindUnboundFramebuffer(texture._framebuffer);
  9975. }
  9976. texture.samples = samples;
  9977. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9978. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9979. this.bindUnboundFramebuffer(null);
  9980. return samples;
  9981. };
  9982. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9983. var gl = this._gl;
  9984. var texture = gl.createTexture();
  9985. var generateMipMaps = true;
  9986. var generateDepthBuffer = true;
  9987. var generateStencilBuffer = false;
  9988. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9989. if (options !== undefined) {
  9990. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9991. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9992. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9993. if (options.samplingMode !== undefined) {
  9994. samplingMode = options.samplingMode;
  9995. }
  9996. }
  9997. texture.isCube = true;
  9998. texture.references = 1;
  9999. texture.generateMipMaps = generateMipMaps;
  10000. texture.references = 1;
  10001. texture.samples = 1;
  10002. texture.samplingMode = samplingMode;
  10003. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10004. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10005. for (var face = 0; face < 6; face++) {
  10006. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10007. }
  10008. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10009. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10010. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10011. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10012. // Create the framebuffer
  10013. var framebuffer = gl.createFramebuffer();
  10014. this.bindUnboundFramebuffer(framebuffer);
  10015. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10016. // Mipmaps
  10017. if (texture.generateMipMaps) {
  10018. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10019. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10020. }
  10021. // Unbind
  10022. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10023. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10024. this.bindUnboundFramebuffer(null);
  10025. texture._framebuffer = framebuffer;
  10026. texture._width = size;
  10027. texture._height = size;
  10028. texture.isReady = true;
  10029. this.resetTextureCache();
  10030. this._loadedTexturesCache.push(texture);
  10031. return texture;
  10032. };
  10033. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  10034. var _this = this;
  10035. if (onLoad === void 0) { onLoad = null; }
  10036. if (onError === void 0) { onError = null; }
  10037. var gl = this._gl;
  10038. var texture = gl.createTexture();
  10039. texture.isCube = true;
  10040. texture.url = rootUrl;
  10041. texture.references = 1;
  10042. texture.onLoadedCallbacks = [];
  10043. var isKTX = false;
  10044. var lastDot = rootUrl.lastIndexOf('.');
  10045. var extension = rootUrl.substring(lastDot).toLowerCase();
  10046. if (this._textureFormatInUse) {
  10047. extension = this._textureFormatInUse;
  10048. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10049. isKTX = true;
  10050. }
  10051. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10052. if (isKTX) {
  10053. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10054. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10055. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10056. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10057. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10058. ktx.uploadLevels(_this._gl, !noMipmap);
  10059. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10060. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10061. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10062. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10063. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10064. _this.resetTextureCache();
  10065. texture._width = ktx.pixelWidth;
  10066. texture._height = ktx.pixelHeight;
  10067. texture.isReady = true;
  10068. }, null, null, true, onError);
  10069. }
  10070. else if (isDDS) {
  10071. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10072. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10073. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10074. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10075. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10076. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  10077. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10078. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10079. }
  10080. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10081. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10082. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10084. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10085. _this.resetTextureCache();
  10086. texture._width = info.width;
  10087. texture._height = info.height;
  10088. texture.isReady = true;
  10089. }, null, null, true, onError);
  10090. }
  10091. else {
  10092. cascadeLoad(rootUrl, scene, function (imgs) {
  10093. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  10094. var height = width;
  10095. _this._prepareWorkingCanvas();
  10096. _this._workingCanvas.width = width;
  10097. _this._workingCanvas.height = height;
  10098. var faces = [
  10099. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10100. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10101. ];
  10102. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10103. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10104. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10105. for (var index = 0; index < faces.length; index++) {
  10106. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10107. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10108. }
  10109. if (!noMipmap) {
  10110. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10111. }
  10112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10113. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10114. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10115. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10116. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10117. _this.resetTextureCache();
  10118. texture._width = width;
  10119. texture._height = height;
  10120. texture.isReady = true;
  10121. texture.onLoadedCallbacks.forEach(function (callback) {
  10122. callback();
  10123. });
  10124. if (onLoad) {
  10125. onLoad();
  10126. }
  10127. }, files, onError);
  10128. }
  10129. this._loadedTexturesCache.push(texture);
  10130. return texture;
  10131. };
  10132. Engine.prototype.updateTextureSize = function (texture, width, height) {
  10133. texture._width = width;
  10134. texture._height = height;
  10135. texture._size = width * height;
  10136. texture._baseWidth = width;
  10137. texture._baseHeight = height;
  10138. };
  10139. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  10140. var _this = this;
  10141. if (onLoad === void 0) { onLoad = null; }
  10142. if (onError === void 0) { onError = null; }
  10143. var gl = this._gl;
  10144. var texture = gl.createTexture();
  10145. scene._addPendingData(texture);
  10146. texture.isCube = true;
  10147. texture.references = 1;
  10148. texture.url = url;
  10149. var textureType = gl.UNSIGNED_BYTE;
  10150. if (type === Engine.TEXTURETYPE_FLOAT) {
  10151. textureType = gl.FLOAT;
  10152. }
  10153. var internalFormat = this._getInternalFormat(format);
  10154. var needConversion = false;
  10155. if (internalFormat === gl.RGB) {
  10156. internalFormat = gl.RGBA;
  10157. needConversion = true;
  10158. }
  10159. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10160. var width = size;
  10161. var height = width;
  10162. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10163. texture._width = width;
  10164. texture._height = height;
  10165. var onerror = function () {
  10166. scene._removePendingData(texture);
  10167. if (onError) {
  10168. onError();
  10169. }
  10170. };
  10171. var internalCallback = function (data) {
  10172. var rgbeDataArrays = callback(data);
  10173. var facesIndex = [
  10174. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10175. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10176. ];
  10177. width = texture._width;
  10178. height = texture._height;
  10179. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  10180. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10181. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10182. if (mipmmapGenerator) {
  10183. var arrayTemp = [];
  10184. // Data are known to be in +X +Y +Z -X -Y -Z
  10185. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  10186. arrayTemp.push(rgbeDataArrays[0]); // +X
  10187. arrayTemp.push(rgbeDataArrays[3]); // -X
  10188. arrayTemp.push(rgbeDataArrays[1]); // +Y
  10189. arrayTemp.push(rgbeDataArrays[4]); // -Y
  10190. arrayTemp.push(rgbeDataArrays[2]); // +Z
  10191. arrayTemp.push(rgbeDataArrays[5]); // -Z
  10192. var mipData = mipmmapGenerator(arrayTemp);
  10193. // mipData is order in +X -X +Y -Y +Z -Z
  10194. var mipFaces = [0, 2, 4, 1, 3, 5];
  10195. for (var level = 0; level < mipData.length; level++) {
  10196. var mipSize = width >> level;
  10197. for (var mipIndex in mipFaces) {
  10198. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  10199. if (needConversion) {
  10200. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10201. }
  10202. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10203. }
  10204. }
  10205. }
  10206. else {
  10207. // Data are known to be in +X +Y +Z -X -Y -Z
  10208. for (var index = 0; index < facesIndex.length; index++) {
  10209. var faceData = rgbeDataArrays[index];
  10210. if (needConversion) {
  10211. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  10212. }
  10213. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  10214. }
  10215. if (!noMipmap && isPot) {
  10216. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10217. }
  10218. else {
  10219. noMipmap = true;
  10220. }
  10221. }
  10222. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  10223. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10224. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10225. }
  10226. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  10227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10229. }
  10230. else {
  10231. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10232. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10233. }
  10234. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10235. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10236. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10237. texture.isReady = true;
  10238. _this.resetTextureCache();
  10239. scene._removePendingData(texture);
  10240. if (onLoad) {
  10241. onLoad();
  10242. }
  10243. };
  10244. BABYLON.Tools.LoadFile(url, function (data) {
  10245. internalCallback(data);
  10246. }, onerror, scene.database, true);
  10247. return texture;
  10248. };
  10249. ;
  10250. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10251. // Create new RGBA data container.
  10252. var rgbaData;
  10253. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10254. rgbaData = new Float32Array(width * height * 4);
  10255. }
  10256. else {
  10257. rgbaData = new Uint32Array(width * height * 4);
  10258. }
  10259. // Convert each pixel.
  10260. for (var x = 0; x < width; x++) {
  10261. for (var y = 0; y < height; y++) {
  10262. var index = (y * width + x) * 3;
  10263. var newIndex = (y * width + x) * 4;
  10264. // Map Old Value to new value.
  10265. rgbaData[newIndex + 0] = rgbData[index + 0];
  10266. rgbaData[newIndex + 1] = rgbData[index + 1];
  10267. rgbaData[newIndex + 2] = rgbData[index + 2];
  10268. // Add fully opaque alpha channel.
  10269. rgbaData[newIndex + 3] = 1;
  10270. }
  10271. }
  10272. return rgbaData;
  10273. };
  10274. Engine.prototype._releaseTexture = function (texture) {
  10275. var gl = this._gl;
  10276. if (texture._framebuffer) {
  10277. gl.deleteFramebuffer(texture._framebuffer);
  10278. }
  10279. if (texture._depthStencilBuffer) {
  10280. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10281. }
  10282. if (texture._MSAAFramebuffer) {
  10283. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10284. }
  10285. if (texture._MSAARenderBuffer) {
  10286. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10287. }
  10288. gl.deleteTexture(texture);
  10289. // Unbind channels
  10290. this.unbindAllTextures();
  10291. var index = this._loadedTexturesCache.indexOf(texture);
  10292. if (index !== -1) {
  10293. this._loadedTexturesCache.splice(index, 1);
  10294. }
  10295. };
  10296. Engine.prototype.setProgram = function (program) {
  10297. if (this._currentProgram !== program) {
  10298. this._gl.useProgram(program);
  10299. this._currentProgram = program;
  10300. }
  10301. };
  10302. Engine.prototype.bindSamplers = function (effect) {
  10303. this.setProgram(effect.getProgram());
  10304. var samplers = effect.getSamplers();
  10305. for (var index = 0; index < samplers.length; index++) {
  10306. var uniform = effect.getUniform(samplers[index]);
  10307. this._gl.uniform1i(uniform, index);
  10308. }
  10309. this._currentEffect = null;
  10310. };
  10311. Engine.prototype.activateTexture = function (texture) {
  10312. if (this._activeTexture !== texture) {
  10313. this._gl.activeTexture(texture);
  10314. this._activeTexture = texture;
  10315. }
  10316. };
  10317. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10318. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10319. this._gl.bindTexture(target, texture);
  10320. this._activeTexturesCache[this._activeTexture] = texture;
  10321. }
  10322. };
  10323. Engine.prototype._bindTexture = function (channel, texture) {
  10324. if (channel < 0) {
  10325. return;
  10326. }
  10327. this.activateTexture(this._gl.TEXTURE0 + channel);
  10328. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10329. };
  10330. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10331. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10332. };
  10333. Engine.prototype.unbindAllTextures = function () {
  10334. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10335. this.activateTexture(this._gl["TEXTURE" + channel]);
  10336. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10337. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10338. }
  10339. };
  10340. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10341. if (channel < 0) {
  10342. return;
  10343. }
  10344. this._gl.uniform1i(uniform, channel);
  10345. this._setTexture(channel, texture);
  10346. };
  10347. Engine.prototype._setTexture = function (channel, texture) {
  10348. // Not ready?
  10349. if (!texture || !texture.isReady()) {
  10350. if (this._activeTexturesCache[channel] != null) {
  10351. this.activateTexture(this._gl["TEXTURE" + channel]);
  10352. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10353. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10354. }
  10355. return;
  10356. }
  10357. // Video
  10358. var alreadyActivated = false;
  10359. if (texture instanceof BABYLON.VideoTexture) {
  10360. this.activateTexture(this._gl["TEXTURE" + channel]);
  10361. alreadyActivated = true;
  10362. texture.update();
  10363. }
  10364. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10365. texture.delayLoad();
  10366. return;
  10367. }
  10368. var internalTexture = texture.getInternalTexture();
  10369. if (this._activeTexturesCache[channel] === internalTexture) {
  10370. return;
  10371. }
  10372. if (!alreadyActivated) {
  10373. this.activateTexture(this._gl["TEXTURE" + channel]);
  10374. }
  10375. if (internalTexture.isCube) {
  10376. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10377. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10378. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10379. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10380. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10381. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10382. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10383. }
  10384. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10385. }
  10386. else {
  10387. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10388. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10389. internalTexture._cachedWrapU = texture.wrapU;
  10390. switch (texture.wrapU) {
  10391. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10392. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10393. break;
  10394. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10395. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10396. break;
  10397. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10399. break;
  10400. }
  10401. }
  10402. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10403. internalTexture._cachedWrapV = texture.wrapV;
  10404. switch (texture.wrapV) {
  10405. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10406. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10407. break;
  10408. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10409. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10410. break;
  10411. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10412. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10413. break;
  10414. }
  10415. }
  10416. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10417. }
  10418. };
  10419. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10420. if (channel < 0) {
  10421. return;
  10422. }
  10423. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10424. this._textureUnits = new Int32Array(textures.length);
  10425. }
  10426. for (var i = 0; i < textures.length; i++) {
  10427. this._textureUnits[i] = channel + i;
  10428. }
  10429. this._gl.uniform1iv(uniform, this._textureUnits);
  10430. for (var index = 0; index < textures.length; index++) {
  10431. this._setTexture(channel + index, textures[index]);
  10432. }
  10433. };
  10434. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10435. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10436. var value = texture.anisotropicFilteringLevel;
  10437. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10438. value = 1;
  10439. }
  10440. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10441. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10442. texture._cachedAnisotropicFilteringLevel = value;
  10443. }
  10444. };
  10445. Engine.prototype.readPixels = function (x, y, width, height) {
  10446. var data = new Uint8Array(height * width * 4);
  10447. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10448. return data;
  10449. };
  10450. /**
  10451. * Add an externaly attached data from its key.
  10452. * This method call will fail and return false, if such key already exists.
  10453. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10454. * @param key the unique key that identifies the data
  10455. * @param data the data object to associate to the key for this Engine instance
  10456. * @return true if no such key were already present and the data was added successfully, false otherwise
  10457. */
  10458. Engine.prototype.addExternalData = function (key, data) {
  10459. return this._externalData.add(key, data);
  10460. };
  10461. /**
  10462. * Get an externaly attached data from its key
  10463. * @param key the unique key that identifies the data
  10464. * @return the associated data, if present (can be null), or undefined if not present
  10465. */
  10466. Engine.prototype.getExternalData = function (key) {
  10467. return this._externalData.get(key);
  10468. };
  10469. /**
  10470. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10471. * @param key the unique key that identifies the data
  10472. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10473. * @return the associated data, can be null if the factory returned null.
  10474. */
  10475. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10476. return this._externalData.getOrAddWithFactory(key, factory);
  10477. };
  10478. /**
  10479. * Remove an externaly attached data from the Engine instance
  10480. * @param key the unique key that identifies the data
  10481. * @return true if the data was successfully removed, false if it doesn't exist
  10482. */
  10483. Engine.prototype.removeExternalData = function (key) {
  10484. return this._externalData.remove(key);
  10485. };
  10486. Engine.prototype.releaseInternalTexture = function (texture) {
  10487. if (!texture) {
  10488. return;
  10489. }
  10490. texture.references--;
  10491. // Final reference ?
  10492. if (texture.references === 0) {
  10493. var texturesCache = this.getLoadedTexturesCache();
  10494. var index = texturesCache.indexOf(texture);
  10495. if (index > -1) {
  10496. texturesCache.splice(index, 1);
  10497. }
  10498. this._releaseTexture(texture);
  10499. }
  10500. };
  10501. Engine.prototype.unbindAllAttributes = function () {
  10502. if (this._mustWipeVertexAttributes) {
  10503. this._mustWipeVertexAttributes = false;
  10504. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10505. this._gl.disableVertexAttribArray(i);
  10506. this._vertexAttribArraysEnabled[i] = false;
  10507. this._currentBufferPointers[i] = null;
  10508. }
  10509. return;
  10510. }
  10511. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10512. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10513. continue;
  10514. }
  10515. this._gl.disableVertexAttribArray(i);
  10516. this._vertexAttribArraysEnabled[i] = false;
  10517. this._currentBufferPointers[i] = null;
  10518. }
  10519. };
  10520. // Dispose
  10521. Engine.prototype.dispose = function () {
  10522. this.hideLoadingUI();
  10523. this.stopRenderLoop();
  10524. // Release scenes
  10525. while (this.scenes.length) {
  10526. this.scenes[0].dispose();
  10527. }
  10528. // Release audio engine
  10529. Engine.audioEngine.dispose();
  10530. // Release effects
  10531. for (var name in this._compiledEffects) {
  10532. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10533. }
  10534. // Unbind
  10535. this.unbindAllAttributes();
  10536. this._gl = null;
  10537. //WebVR
  10538. this.disableVR();
  10539. // Events
  10540. window.removeEventListener("blur", this._onBlur);
  10541. window.removeEventListener("focus", this._onFocus);
  10542. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10543. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10544. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10545. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10546. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10547. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10548. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10549. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10550. // Remove from Instances
  10551. var index = Engine.Instances.indexOf(this);
  10552. if (index >= 0) {
  10553. Engine.Instances.splice(index, 1);
  10554. }
  10555. };
  10556. // Loading screen
  10557. Engine.prototype.displayLoadingUI = function () {
  10558. this._loadingScreen.displayLoadingUI();
  10559. };
  10560. Engine.prototype.hideLoadingUI = function () {
  10561. this._loadingScreen.hideLoadingUI();
  10562. };
  10563. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10564. get: function () {
  10565. return this._loadingScreen;
  10566. },
  10567. set: function (loadingScreen) {
  10568. this._loadingScreen = loadingScreen;
  10569. },
  10570. enumerable: true,
  10571. configurable: true
  10572. });
  10573. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10574. set: function (text) {
  10575. this._loadingScreen.loadingUIText = text;
  10576. },
  10577. enumerable: true,
  10578. configurable: true
  10579. });
  10580. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10581. set: function (color) {
  10582. this._loadingScreen.loadingUIBackgroundColor = color;
  10583. },
  10584. enumerable: true,
  10585. configurable: true
  10586. });
  10587. Engine.prototype.attachContextLostEvent = function (callback) {
  10588. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10589. };
  10590. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10591. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10592. };
  10593. Engine.prototype.getVertexShaderSource = function (program) {
  10594. var shaders = this._gl.getAttachedShaders(program);
  10595. return this._gl.getShaderSource(shaders[0]);
  10596. };
  10597. Engine.prototype.getFragmentShaderSource = function (program) {
  10598. var shaders = this._gl.getAttachedShaders(program);
  10599. return this._gl.getShaderSource(shaders[1]);
  10600. };
  10601. // FPS
  10602. Engine.prototype.getFps = function () {
  10603. return this.fps;
  10604. };
  10605. Engine.prototype.getDeltaTime = function () {
  10606. return this.deltaTime;
  10607. };
  10608. Engine.prototype._measureFps = function () {
  10609. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10610. var length = this.previousFramesDuration.length;
  10611. if (length >= 2) {
  10612. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10613. }
  10614. if (length >= this.fpsRange) {
  10615. if (length > this.fpsRange) {
  10616. this.previousFramesDuration.splice(0, 1);
  10617. length = this.previousFramesDuration.length;
  10618. }
  10619. var sum = 0;
  10620. for (var id = 0; id < length - 1; id++) {
  10621. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10622. }
  10623. this.fps = 1000.0 / (sum / (length - 1));
  10624. }
  10625. };
  10626. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10627. if (this._webGLVersion > 1) {
  10628. return this._caps.colorBufferFloat;
  10629. }
  10630. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10631. };
  10632. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10633. if (this._webGLVersion > 1) {
  10634. return this._caps.colorBufferFloat;
  10635. }
  10636. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10637. };
  10638. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10639. Engine.prototype._canRenderToFramebuffer = function (type) {
  10640. var gl = this._gl;
  10641. //clear existing errors
  10642. while (gl.getError() !== gl.NO_ERROR) { }
  10643. var successful = true;
  10644. var texture = gl.createTexture();
  10645. gl.bindTexture(gl.TEXTURE_2D, texture);
  10646. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10647. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10648. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10649. var fb = gl.createFramebuffer();
  10650. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10651. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10652. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10653. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10654. successful = successful && (gl.getError() === gl.NO_ERROR);
  10655. //try render by clearing frame buffer's color buffer
  10656. if (successful) {
  10657. gl.clear(gl.COLOR_BUFFER_BIT);
  10658. successful = successful && (gl.getError() === gl.NO_ERROR);
  10659. }
  10660. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10661. if (successful) {
  10662. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10663. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10664. var readFormat = gl.RGBA;
  10665. var readType = gl.UNSIGNED_BYTE;
  10666. var buffer = new Uint8Array(4);
  10667. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10668. successful = successful && (gl.getError() === gl.NO_ERROR);
  10669. }
  10670. //clean up
  10671. gl.deleteTexture(texture);
  10672. gl.deleteFramebuffer(fb);
  10673. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10674. //clear accumulated errors
  10675. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10676. return successful;
  10677. };
  10678. Engine.prototype._getWebGLTextureType = function (type) {
  10679. if (type === Engine.TEXTURETYPE_FLOAT) {
  10680. return this._gl.FLOAT;
  10681. }
  10682. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10683. // Add Half Float Constant.
  10684. return Engine.HALF_FLOAT_OES;
  10685. }
  10686. return this._gl.UNSIGNED_BYTE;
  10687. };
  10688. ;
  10689. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10690. if (this._webGLVersion === 1) {
  10691. return this._gl.RGBA;
  10692. }
  10693. if (type === Engine.TEXTURETYPE_FLOAT) {
  10694. return Engine.RGBA32F;
  10695. }
  10696. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10697. return Engine.RGBA16F;
  10698. }
  10699. return this._gl.RGBA;
  10700. };
  10701. ;
  10702. // Statics
  10703. Engine.isSupported = function () {
  10704. try {
  10705. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10706. if (navigator.isCocoonJS) {
  10707. return true;
  10708. }
  10709. var tempcanvas = document.createElement("canvas");
  10710. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10711. return gl != null && !!window.WebGLRenderingContext;
  10712. }
  10713. catch (e) {
  10714. return false;
  10715. }
  10716. };
  10717. return Engine;
  10718. }());
  10719. Engine.Instances = new Array();
  10720. // Const statics
  10721. Engine._ALPHA_DISABLE = 0;
  10722. Engine._ALPHA_ADD = 1;
  10723. Engine._ALPHA_COMBINE = 2;
  10724. Engine._ALPHA_SUBTRACT = 3;
  10725. Engine._ALPHA_MULTIPLY = 4;
  10726. Engine._ALPHA_MAXIMIZED = 5;
  10727. Engine._ALPHA_ONEONE = 6;
  10728. Engine._ALPHA_PREMULTIPLIED = 7;
  10729. Engine._DELAYLOADSTATE_NONE = 0;
  10730. Engine._DELAYLOADSTATE_LOADED = 1;
  10731. Engine._DELAYLOADSTATE_LOADING = 2;
  10732. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10733. Engine._TEXTUREFORMAT_ALPHA = 0;
  10734. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10735. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10736. Engine._TEXTUREFORMAT_RGB = 4;
  10737. Engine._TEXTUREFORMAT_RGBA = 5;
  10738. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10739. Engine._TEXTURETYPE_FLOAT = 1;
  10740. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10741. // Depht or Stencil test Constants.
  10742. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10743. 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.
  10744. 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.
  10745. 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.
  10746. 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.
  10747. 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.
  10748. 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.
  10749. 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.
  10750. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10751. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10752. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10753. // Stencil Actions Constants.
  10754. Engine._KEEP = 0x1E00;
  10755. Engine._REPLACE = 0x1E01;
  10756. Engine._INCR = 0x1E02;
  10757. Engine._DECR = 0x1E03;
  10758. Engine._INVERT = 0x150A;
  10759. Engine._INCR_WRAP = 0x8507;
  10760. Engine._DECR_WRAP = 0x8508;
  10761. // Updatable statics so stick with vars here
  10762. Engine.CollisionsEpsilon = 0.001;
  10763. Engine.CodeRepository = "src/";
  10764. Engine.ShadersRepository = "src/Shaders/";
  10765. BABYLON.Engine = Engine;
  10766. })(BABYLON || (BABYLON = {}));
  10767. //# sourceMappingURL=babylon.engine.js.map
  10768. /// <reference path="Tools\babylon.decorators.ts" />
  10769. var BABYLON;
  10770. (function (BABYLON) {
  10771. /**
  10772. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10773. */
  10774. var Node = (function () {
  10775. /**
  10776. * @constructor
  10777. * @param {string} name - the name and id to be given to this node
  10778. * @param {BABYLON.Scene} the scene this node will be added to
  10779. */
  10780. function Node(name, scene) {
  10781. this.state = "";
  10782. this.metadata = null;
  10783. this.doNotSerialize = false;
  10784. this.animations = new Array();
  10785. this._ranges = {};
  10786. this._childrenFlag = -1;
  10787. this._isEnabled = true;
  10788. this._isReady = true;
  10789. this._currentRenderId = -1;
  10790. this._parentRenderId = -1;
  10791. /**
  10792. * An event triggered when the mesh is disposed.
  10793. * @type {BABYLON.Observable}
  10794. */
  10795. this.onDisposeObservable = new BABYLON.Observable();
  10796. this.name = name;
  10797. this.id = name;
  10798. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10799. this._initCache();
  10800. }
  10801. Object.defineProperty(Node.prototype, "parent", {
  10802. get: function () {
  10803. return this._parentNode;
  10804. },
  10805. set: function (parent) {
  10806. if (this._parentNode === parent) {
  10807. return;
  10808. }
  10809. if (this._parentNode) {
  10810. var index = this._parentNode._children.indexOf(this);
  10811. if (index !== -1) {
  10812. this._parentNode._children.splice(index, 1);
  10813. }
  10814. }
  10815. this._parentNode = parent;
  10816. if (this._parentNode) {
  10817. if (!this._parentNode._children) {
  10818. this._parentNode._children = new Array();
  10819. }
  10820. this._parentNode._children.push(this);
  10821. }
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Node.prototype.getClassName = function () {
  10827. return "Node";
  10828. };
  10829. Object.defineProperty(Node.prototype, "onDispose", {
  10830. set: function (callback) {
  10831. if (this._onDisposeObserver) {
  10832. this.onDisposeObservable.remove(this._onDisposeObserver);
  10833. }
  10834. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10835. },
  10836. enumerable: true,
  10837. configurable: true
  10838. });
  10839. Node.prototype.getScene = function () {
  10840. return this._scene;
  10841. };
  10842. Node.prototype.getEngine = function () {
  10843. return this._scene.getEngine();
  10844. };
  10845. // override it in derived class
  10846. Node.prototype.getWorldMatrix = function () {
  10847. return BABYLON.Matrix.Identity();
  10848. };
  10849. // override it in derived class if you add new variables to the cache
  10850. // and call the parent class method
  10851. Node.prototype._initCache = function () {
  10852. this._cache = {};
  10853. this._cache.parent = undefined;
  10854. };
  10855. Node.prototype.updateCache = function (force) {
  10856. if (!force && this.isSynchronized())
  10857. return;
  10858. this._cache.parent = this.parent;
  10859. this._updateCache();
  10860. };
  10861. // override it in derived class if you add new variables to the cache
  10862. // and call the parent class method if !ignoreParentClass
  10863. Node.prototype._updateCache = function (ignoreParentClass) {
  10864. };
  10865. // override it in derived class if you add new variables to the cache
  10866. Node.prototype._isSynchronized = function () {
  10867. return true;
  10868. };
  10869. Node.prototype._markSyncedWithParent = function () {
  10870. this._parentRenderId = this.parent._currentRenderId;
  10871. };
  10872. Node.prototype.isSynchronizedWithParent = function () {
  10873. if (!this.parent) {
  10874. return true;
  10875. }
  10876. if (this._parentRenderId !== this.parent._currentRenderId) {
  10877. return false;
  10878. }
  10879. return this.parent.isSynchronized();
  10880. };
  10881. Node.prototype.isSynchronized = function (updateCache) {
  10882. var check = this.hasNewParent();
  10883. check = check || !this.isSynchronizedWithParent();
  10884. check = check || !this._isSynchronized();
  10885. if (updateCache)
  10886. this.updateCache(true);
  10887. return !check;
  10888. };
  10889. Node.prototype.hasNewParent = function (update) {
  10890. if (this._cache.parent === this.parent)
  10891. return false;
  10892. if (update)
  10893. this._cache.parent = this.parent;
  10894. return true;
  10895. };
  10896. /**
  10897. * Is this node ready to be used/rendered
  10898. * @return {boolean} is it ready
  10899. */
  10900. Node.prototype.isReady = function () {
  10901. return this._isReady;
  10902. };
  10903. /**
  10904. * Is this node enabled.
  10905. * If the node has a parent and is enabled, the parent will be inspected as well.
  10906. * @return {boolean} whether this node (and its parent) is enabled.
  10907. * @see setEnabled
  10908. */
  10909. Node.prototype.isEnabled = function () {
  10910. if (!this._isEnabled) {
  10911. return false;
  10912. }
  10913. if (this.parent) {
  10914. return this.parent.isEnabled();
  10915. }
  10916. return true;
  10917. };
  10918. /**
  10919. * Set the enabled state of this node.
  10920. * @param {boolean} value - the new enabled state
  10921. * @see isEnabled
  10922. */
  10923. Node.prototype.setEnabled = function (value) {
  10924. this._isEnabled = value;
  10925. };
  10926. /**
  10927. * Is this node a descendant of the given node.
  10928. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10929. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10930. * @see parent
  10931. */
  10932. Node.prototype.isDescendantOf = function (ancestor) {
  10933. if (this.parent) {
  10934. if (this.parent === ancestor) {
  10935. return true;
  10936. }
  10937. return this.parent.isDescendantOf(ancestor);
  10938. }
  10939. return false;
  10940. };
  10941. /**
  10942. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10943. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10944. * @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.
  10945. * @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.
  10946. */
  10947. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10948. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10949. if (!this._children) {
  10950. return;
  10951. }
  10952. for (var index = 0; index < this._children.length; index++) {
  10953. var item = this._children[index];
  10954. if (!predicate || predicate(item)) {
  10955. results.push(item);
  10956. }
  10957. if (!directDescendantsOnly) {
  10958. item._getDescendants(results, false, predicate);
  10959. }
  10960. }
  10961. };
  10962. /**
  10963. * Will return all nodes that have this node as ascendant.
  10964. * @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.
  10965. * @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.
  10966. * @return {BABYLON.Node[]} all children nodes of all types.
  10967. */
  10968. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10969. var results = [];
  10970. this._getDescendants(results, directDescendantsOnly, predicate);
  10971. return results;
  10972. };
  10973. /**
  10974. * Get all child-meshes of this node.
  10975. */
  10976. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10977. var results = [];
  10978. this._getDescendants(results, directDecendantsOnly, function (node) {
  10979. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10980. });
  10981. return results;
  10982. };
  10983. /**
  10984. * Get all direct children of this node.
  10985. */
  10986. Node.prototype.getChildren = function (predicate) {
  10987. return this.getDescendants(true, predicate);
  10988. };
  10989. Node.prototype._setReady = function (state) {
  10990. if (state === this._isReady) {
  10991. return;
  10992. }
  10993. if (!state) {
  10994. this._isReady = false;
  10995. return;
  10996. }
  10997. this._isReady = true;
  10998. if (this.onReady) {
  10999. this.onReady(this);
  11000. }
  11001. };
  11002. Node.prototype.getAnimationByName = function (name) {
  11003. for (var i = 0; i < this.animations.length; i++) {
  11004. var animation = this.animations[i];
  11005. if (animation.name === name) {
  11006. return animation;
  11007. }
  11008. }
  11009. return null;
  11010. };
  11011. Node.prototype.createAnimationRange = function (name, from, to) {
  11012. // check name not already in use
  11013. if (!this._ranges[name]) {
  11014. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11015. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11016. if (this.animations[i]) {
  11017. this.animations[i].createRange(name, from, to);
  11018. }
  11019. }
  11020. }
  11021. };
  11022. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11023. if (deleteFrames === void 0) { deleteFrames = true; }
  11024. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11025. if (this.animations[i]) {
  11026. this.animations[i].deleteRange(name, deleteFrames);
  11027. }
  11028. }
  11029. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11030. };
  11031. Node.prototype.getAnimationRange = function (name) {
  11032. return this._ranges[name];
  11033. };
  11034. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11035. var range = this.getAnimationRange(name);
  11036. if (!range) {
  11037. return null;
  11038. }
  11039. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11040. };
  11041. Node.prototype.serializeAnimationRanges = function () {
  11042. var serializationRanges = [];
  11043. for (var name in this._ranges) {
  11044. var range = {};
  11045. range.name = name;
  11046. range.from = this._ranges[name].from;
  11047. range.to = this._ranges[name].to;
  11048. serializationRanges.push(range);
  11049. }
  11050. return serializationRanges;
  11051. };
  11052. Node.prototype.dispose = function () {
  11053. this.parent = null;
  11054. // Callback
  11055. this.onDisposeObservable.notifyObservers(this);
  11056. this.onDisposeObservable.clear();
  11057. };
  11058. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11059. if (parsedNode.ranges) {
  11060. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11061. var data = parsedNode.ranges[index];
  11062. node.createAnimationRange(data.name, data.from, data.to);
  11063. }
  11064. }
  11065. };
  11066. return Node;
  11067. }());
  11068. __decorate([
  11069. BABYLON.serialize()
  11070. ], Node.prototype, "name", void 0);
  11071. __decorate([
  11072. BABYLON.serialize()
  11073. ], Node.prototype, "id", void 0);
  11074. __decorate([
  11075. BABYLON.serialize()
  11076. ], Node.prototype, "uniqueId", void 0);
  11077. __decorate([
  11078. BABYLON.serialize()
  11079. ], Node.prototype, "state", void 0);
  11080. __decorate([
  11081. BABYLON.serialize()
  11082. ], Node.prototype, "metadata", void 0);
  11083. BABYLON.Node = Node;
  11084. })(BABYLON || (BABYLON = {}));
  11085. //# sourceMappingURL=babylon.node.js.map
  11086. var BABYLON;
  11087. (function (BABYLON) {
  11088. var FilesInput = (function () {
  11089. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  11090. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  11091. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  11092. this._engine = p_engine;
  11093. this._canvas = p_canvas;
  11094. this._currentScene = p_scene;
  11095. this._sceneLoadedCallback = p_sceneLoadedCallback;
  11096. this._progressCallback = p_progressCallback;
  11097. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  11098. this._textureLoadingCallback = p_textureLoadingCallback;
  11099. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  11100. }
  11101. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  11102. var _this = this;
  11103. if (p_elementToMonitor) {
  11104. this._elementToMonitor = p_elementToMonitor;
  11105. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  11106. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  11107. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  11108. }
  11109. };
  11110. FilesInput.prototype.renderFunction = function () {
  11111. if (this._additionnalRenderLoopLogicCallback) {
  11112. this._additionnalRenderLoopLogicCallback();
  11113. }
  11114. if (this._currentScene) {
  11115. if (this._textureLoadingCallback) {
  11116. var remaining = this._currentScene.getWaitingItemsCount();
  11117. if (remaining > 0) {
  11118. this._textureLoadingCallback(remaining);
  11119. }
  11120. }
  11121. this._currentScene.render();
  11122. }
  11123. };
  11124. FilesInput.prototype.drag = function (e) {
  11125. e.stopPropagation();
  11126. e.preventDefault();
  11127. };
  11128. FilesInput.prototype.drop = function (eventDrop) {
  11129. eventDrop.stopPropagation();
  11130. eventDrop.preventDefault();
  11131. this.loadFiles(eventDrop);
  11132. };
  11133. FilesInput.prototype.loadFiles = function (event) {
  11134. if (this._startingProcessingFilesCallback)
  11135. this._startingProcessingFilesCallback();
  11136. // Handling data transfer via drag'n'drop
  11137. if (event && event.dataTransfer && event.dataTransfer.files) {
  11138. this._filesToLoad = event.dataTransfer.files;
  11139. }
  11140. // Handling files from input files
  11141. if (event && event.target && event.target.files) {
  11142. this._filesToLoad = event.target.files;
  11143. }
  11144. if (this._filesToLoad && this._filesToLoad.length > 0) {
  11145. for (var i = 0; i < this._filesToLoad.length; i++) {
  11146. var name_1 = this._filesToLoad[i].name.toLowerCase();
  11147. var extension = name_1.split('.').pop();
  11148. var type = this._filesToLoad[i].type;
  11149. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  11150. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  11151. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  11152. }
  11153. else {
  11154. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  11155. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  11156. this._sceneFileToLoad = this._filesToLoad[i];
  11157. }
  11158. else {
  11159. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  11160. }
  11161. }
  11162. }
  11163. this.reload();
  11164. }
  11165. };
  11166. FilesInput.prototype.reload = function () {
  11167. var _this = this;
  11168. var that = this;
  11169. // If a ".babylon" file has been provided
  11170. if (this._sceneFileToLoad) {
  11171. if (this._currentScene) {
  11172. if (BABYLON.Tools.errorsCount > 0) {
  11173. BABYLON.Tools.ClearLogCache();
  11174. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  11175. }
  11176. this._engine.stopRenderLoop();
  11177. this._currentScene.dispose();
  11178. }
  11179. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  11180. that._currentScene = newScene;
  11181. // Wait for textures and shaders to be ready
  11182. that._currentScene.executeWhenReady(function () {
  11183. // Attach camera to canvas inputs
  11184. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  11185. that._currentScene.createDefaultCameraOrLight();
  11186. }
  11187. that._currentScene.activeCamera.attachControl(that._canvas);
  11188. if (that._sceneLoadedCallback) {
  11189. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  11190. }
  11191. that._engine.runRenderLoop(function () { that.renderFunction(); });
  11192. });
  11193. }, function (progress) {
  11194. if (_this._progressCallback) {
  11195. _this._progressCallback(progress);
  11196. }
  11197. });
  11198. }
  11199. else {
  11200. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  11201. }
  11202. };
  11203. return FilesInput;
  11204. }());
  11205. FilesInput.FilesTextures = new Array();
  11206. FilesInput.FilesToLoad = new Array();
  11207. BABYLON.FilesInput = FilesInput;
  11208. })(BABYLON || (BABYLON = {}));
  11209. //# sourceMappingURL=babylon.filesInput.js.map
  11210. var BABYLON;
  11211. (function (BABYLON) {
  11212. var IntersectionInfo = (function () {
  11213. function IntersectionInfo(bu, bv, distance) {
  11214. this.bu = bu;
  11215. this.bv = bv;
  11216. this.distance = distance;
  11217. this.faceId = 0;
  11218. this.subMeshId = 0;
  11219. }
  11220. return IntersectionInfo;
  11221. }());
  11222. BABYLON.IntersectionInfo = IntersectionInfo;
  11223. var PickingInfo = (function () {
  11224. function PickingInfo() {
  11225. this.hit = false;
  11226. this.distance = 0;
  11227. this.pickedPoint = null;
  11228. this.pickedMesh = null;
  11229. this.bu = 0;
  11230. this.bv = 0;
  11231. this.faceId = -1;
  11232. this.subMeshId = 0;
  11233. this.pickedSprite = null;
  11234. }
  11235. // Methods
  11236. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  11237. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  11238. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  11239. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11240. return null;
  11241. }
  11242. var indices = this.pickedMesh.getIndices();
  11243. var result;
  11244. if (useVerticesNormals) {
  11245. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11246. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  11247. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  11248. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  11249. normal0 = normal0.scale(this.bu);
  11250. normal1 = normal1.scale(this.bv);
  11251. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  11252. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  11253. }
  11254. else {
  11255. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11256. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  11257. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  11258. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  11259. var p1p2 = vertex1.subtract(vertex2);
  11260. var p3p2 = vertex3.subtract(vertex2);
  11261. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  11262. }
  11263. if (useWorldCoordinates) {
  11264. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  11265. }
  11266. return BABYLON.Vector3.Normalize(result);
  11267. };
  11268. PickingInfo.prototype.getTextureCoordinates = function () {
  11269. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11270. return null;
  11271. }
  11272. var indices = this.pickedMesh.getIndices();
  11273. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11274. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  11275. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  11276. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  11277. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  11278. uv1 = uv1.scale(this.bu);
  11279. uv2 = uv2.scale(this.bv);
  11280. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  11281. };
  11282. return PickingInfo;
  11283. }());
  11284. BABYLON.PickingInfo = PickingInfo;
  11285. })(BABYLON || (BABYLON = {}));
  11286. //# sourceMappingURL=babylon.pickingInfo.js.map
  11287. var BABYLON;
  11288. (function (BABYLON) {
  11289. var BoundingSphere = (function () {
  11290. function BoundingSphere(minimum, maximum) {
  11291. this.minimum = minimum;
  11292. this.maximum = maximum;
  11293. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11294. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11295. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11296. this.radius = distance * 0.5;
  11297. this.centerWorld = BABYLON.Vector3.Zero();
  11298. this._update(BABYLON.Matrix.Identity());
  11299. }
  11300. // Methods
  11301. BoundingSphere.prototype._update = function (world) {
  11302. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11303. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11304. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11305. };
  11306. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11307. for (var i = 0; i < 6; i++) {
  11308. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11309. return false;
  11310. }
  11311. return true;
  11312. };
  11313. BoundingSphere.prototype.intersectsPoint = function (point) {
  11314. var x = this.centerWorld.x - point.x;
  11315. var y = this.centerWorld.y - point.y;
  11316. var z = this.centerWorld.z - point.z;
  11317. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11318. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11319. return false;
  11320. return true;
  11321. };
  11322. // Statics
  11323. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11324. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11325. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11326. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11327. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11328. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11329. return false;
  11330. return true;
  11331. };
  11332. return BoundingSphere;
  11333. }());
  11334. BABYLON.BoundingSphere = BoundingSphere;
  11335. })(BABYLON || (BABYLON = {}));
  11336. //# sourceMappingURL=babylon.boundingSphere.js.map
  11337. var BABYLON;
  11338. (function (BABYLON) {
  11339. var BoundingBox = (function () {
  11340. function BoundingBox(minimum, maximum) {
  11341. this.minimum = minimum;
  11342. this.maximum = maximum;
  11343. this.vectors = new Array();
  11344. this.vectorsWorld = new Array();
  11345. // Bounding vectors
  11346. this.vectors.push(this.minimum.clone());
  11347. this.vectors.push(this.maximum.clone());
  11348. this.vectors.push(this.minimum.clone());
  11349. this.vectors[2].x = this.maximum.x;
  11350. this.vectors.push(this.minimum.clone());
  11351. this.vectors[3].y = this.maximum.y;
  11352. this.vectors.push(this.minimum.clone());
  11353. this.vectors[4].z = this.maximum.z;
  11354. this.vectors.push(this.maximum.clone());
  11355. this.vectors[5].z = this.minimum.z;
  11356. this.vectors.push(this.maximum.clone());
  11357. this.vectors[6].x = this.minimum.x;
  11358. this.vectors.push(this.maximum.clone());
  11359. this.vectors[7].y = this.minimum.y;
  11360. // OBB
  11361. this.center = this.maximum.add(this.minimum).scale(0.5);
  11362. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11363. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11364. // World
  11365. for (var index = 0; index < this.vectors.length; index++) {
  11366. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11367. }
  11368. this.minimumWorld = BABYLON.Vector3.Zero();
  11369. this.maximumWorld = BABYLON.Vector3.Zero();
  11370. this.centerWorld = BABYLON.Vector3.Zero();
  11371. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11372. this._update(BABYLON.Matrix.Identity());
  11373. }
  11374. // Methods
  11375. BoundingBox.prototype.getWorldMatrix = function () {
  11376. return this._worldMatrix;
  11377. };
  11378. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11379. this._worldMatrix.copyFrom(matrix);
  11380. return this;
  11381. };
  11382. BoundingBox.prototype._update = function (world) {
  11383. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11384. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11385. for (var index = 0; index < this.vectors.length; index++) {
  11386. var v = this.vectorsWorld[index];
  11387. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11388. if (v.x < this.minimumWorld.x)
  11389. this.minimumWorld.x = v.x;
  11390. if (v.y < this.minimumWorld.y)
  11391. this.minimumWorld.y = v.y;
  11392. if (v.z < this.minimumWorld.z)
  11393. this.minimumWorld.z = v.z;
  11394. if (v.x > this.maximumWorld.x)
  11395. this.maximumWorld.x = v.x;
  11396. if (v.y > this.maximumWorld.y)
  11397. this.maximumWorld.y = v.y;
  11398. if (v.z > this.maximumWorld.z)
  11399. this.maximumWorld.z = v.z;
  11400. }
  11401. // Extend
  11402. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11403. this.extendSizeWorld.scaleInPlace(0.5);
  11404. // OBB
  11405. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11406. this.centerWorld.scaleInPlace(0.5);
  11407. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11408. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11409. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11410. this._worldMatrix = world;
  11411. };
  11412. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11413. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11414. };
  11415. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11416. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11417. };
  11418. BoundingBox.prototype.intersectsPoint = function (point) {
  11419. var delta = -BABYLON.Epsilon;
  11420. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11421. return false;
  11422. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11423. return false;
  11424. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11425. return false;
  11426. return true;
  11427. };
  11428. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11429. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11430. };
  11431. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11432. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11433. return false;
  11434. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11435. return false;
  11436. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11437. return false;
  11438. return true;
  11439. };
  11440. // Statics
  11441. BoundingBox.Intersects = function (box0, box1) {
  11442. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11443. return false;
  11444. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11445. return false;
  11446. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11447. return false;
  11448. return true;
  11449. };
  11450. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11451. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11452. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11453. return (num <= (sphereRadius * sphereRadius));
  11454. };
  11455. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11456. for (var p = 0; p < 6; p++) {
  11457. for (var i = 0; i < 8; i++) {
  11458. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11459. return false;
  11460. }
  11461. }
  11462. }
  11463. return true;
  11464. };
  11465. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11466. for (var p = 0; p < 6; p++) {
  11467. var inCount = 8;
  11468. for (var i = 0; i < 8; i++) {
  11469. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11470. --inCount;
  11471. }
  11472. else {
  11473. break;
  11474. }
  11475. }
  11476. if (inCount === 0)
  11477. return false;
  11478. }
  11479. return true;
  11480. };
  11481. return BoundingBox;
  11482. }());
  11483. BABYLON.BoundingBox = BoundingBox;
  11484. })(BABYLON || (BABYLON = {}));
  11485. //# sourceMappingURL=babylon.boundingBox.js.map
  11486. var BABYLON;
  11487. (function (BABYLON) {
  11488. var computeBoxExtents = function (axis, box) {
  11489. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11490. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11491. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11492. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11493. var r = r0 + r1 + r2;
  11494. return {
  11495. min: p - r,
  11496. max: p + r
  11497. };
  11498. };
  11499. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11500. var axisOverlap = function (axis, box0, box1) {
  11501. var result0 = computeBoxExtents(axis, box0);
  11502. var result1 = computeBoxExtents(axis, box1);
  11503. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11504. };
  11505. var BoundingInfo = (function () {
  11506. function BoundingInfo(minimum, maximum) {
  11507. this.minimum = minimum;
  11508. this.maximum = maximum;
  11509. this._isLocked = false;
  11510. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11511. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11512. }
  11513. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11514. get: function () {
  11515. return this._isLocked;
  11516. },
  11517. set: function (value) {
  11518. this._isLocked = value;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. // Methods
  11524. BoundingInfo.prototype.update = function (world) {
  11525. if (this._isLocked) {
  11526. return;
  11527. }
  11528. this.boundingBox._update(world);
  11529. this.boundingSphere._update(world);
  11530. };
  11531. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11532. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11533. return false;
  11534. return this.boundingBox.isInFrustum(frustumPlanes);
  11535. };
  11536. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11537. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11538. };
  11539. BoundingInfo.prototype._checkCollision = function (collider) {
  11540. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11541. };
  11542. BoundingInfo.prototype.intersectsPoint = function (point) {
  11543. if (!this.boundingSphere.centerWorld) {
  11544. return false;
  11545. }
  11546. if (!this.boundingSphere.intersectsPoint(point)) {
  11547. return false;
  11548. }
  11549. if (!this.boundingBox.intersectsPoint(point)) {
  11550. return false;
  11551. }
  11552. return true;
  11553. };
  11554. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11555. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11556. return false;
  11557. }
  11558. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11559. return false;
  11560. }
  11561. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11562. return false;
  11563. }
  11564. if (!precise) {
  11565. return true;
  11566. }
  11567. var box0 = this.boundingBox;
  11568. var box1 = boundingInfo.boundingBox;
  11569. if (!axisOverlap(box0.directions[0], box0, box1))
  11570. return false;
  11571. if (!axisOverlap(box0.directions[1], box0, box1))
  11572. return false;
  11573. if (!axisOverlap(box0.directions[2], box0, box1))
  11574. return false;
  11575. if (!axisOverlap(box1.directions[0], box0, box1))
  11576. return false;
  11577. if (!axisOverlap(box1.directions[1], box0, box1))
  11578. return false;
  11579. if (!axisOverlap(box1.directions[2], box0, box1))
  11580. return false;
  11581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11582. return false;
  11583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11584. return false;
  11585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11586. return false;
  11587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11588. return false;
  11589. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11590. return false;
  11591. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11592. return false;
  11593. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11594. return false;
  11595. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11596. return false;
  11597. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11598. return false;
  11599. return true;
  11600. };
  11601. return BoundingInfo;
  11602. }());
  11603. BABYLON.BoundingInfo = BoundingInfo;
  11604. })(BABYLON || (BABYLON = {}));
  11605. //# sourceMappingURL=babylon.boundingInfo.js.map
  11606. var BABYLON;
  11607. (function (BABYLON) {
  11608. var Ray = (function () {
  11609. function Ray(origin, direction, length) {
  11610. if (length === void 0) { length = Number.MAX_VALUE; }
  11611. this.origin = origin;
  11612. this.direction = direction;
  11613. this.length = length;
  11614. }
  11615. // Methods
  11616. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  11617. var d = 0.0;
  11618. var maxValue = Number.MAX_VALUE;
  11619. var inv;
  11620. var min;
  11621. var max;
  11622. var temp;
  11623. if (Math.abs(this.direction.x) < 0.0000001) {
  11624. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  11625. return false;
  11626. }
  11627. }
  11628. else {
  11629. inv = 1.0 / this.direction.x;
  11630. min = (minimum.x - this.origin.x) * inv;
  11631. max = (maximum.x - this.origin.x) * inv;
  11632. if (max === -Infinity) {
  11633. max = Infinity;
  11634. }
  11635. if (min > max) {
  11636. temp = min;
  11637. min = max;
  11638. max = temp;
  11639. }
  11640. d = Math.max(min, d);
  11641. maxValue = Math.min(max, maxValue);
  11642. if (d > maxValue) {
  11643. return false;
  11644. }
  11645. }
  11646. if (Math.abs(this.direction.y) < 0.0000001) {
  11647. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  11648. return false;
  11649. }
  11650. }
  11651. else {
  11652. inv = 1.0 / this.direction.y;
  11653. min = (minimum.y - this.origin.y) * inv;
  11654. max = (maximum.y - this.origin.y) * inv;
  11655. if (max === -Infinity) {
  11656. max = Infinity;
  11657. }
  11658. if (min > max) {
  11659. temp = min;
  11660. min = max;
  11661. max = temp;
  11662. }
  11663. d = Math.max(min, d);
  11664. maxValue = Math.min(max, maxValue);
  11665. if (d > maxValue) {
  11666. return false;
  11667. }
  11668. }
  11669. if (Math.abs(this.direction.z) < 0.0000001) {
  11670. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  11671. return false;
  11672. }
  11673. }
  11674. else {
  11675. inv = 1.0 / this.direction.z;
  11676. min = (minimum.z - this.origin.z) * inv;
  11677. max = (maximum.z - this.origin.z) * inv;
  11678. if (max === -Infinity) {
  11679. max = Infinity;
  11680. }
  11681. if (min > max) {
  11682. temp = min;
  11683. min = max;
  11684. max = temp;
  11685. }
  11686. d = Math.max(min, d);
  11687. maxValue = Math.min(max, maxValue);
  11688. if (d > maxValue) {
  11689. return false;
  11690. }
  11691. }
  11692. return true;
  11693. };
  11694. Ray.prototype.intersectsBox = function (box) {
  11695. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  11696. };
  11697. Ray.prototype.intersectsSphere = function (sphere) {
  11698. var x = sphere.center.x - this.origin.x;
  11699. var y = sphere.center.y - this.origin.y;
  11700. var z = sphere.center.z - this.origin.z;
  11701. var pyth = (x * x) + (y * y) + (z * z);
  11702. var rr = sphere.radius * sphere.radius;
  11703. if (pyth <= rr) {
  11704. return true;
  11705. }
  11706. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  11707. if (dot < 0.0) {
  11708. return false;
  11709. }
  11710. var temp = pyth - (dot * dot);
  11711. return temp <= rr;
  11712. };
  11713. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  11714. if (!this._edge1) {
  11715. this._edge1 = BABYLON.Vector3.Zero();
  11716. this._edge2 = BABYLON.Vector3.Zero();
  11717. this._pvec = BABYLON.Vector3.Zero();
  11718. this._tvec = BABYLON.Vector3.Zero();
  11719. this._qvec = BABYLON.Vector3.Zero();
  11720. }
  11721. vertex1.subtractToRef(vertex0, this._edge1);
  11722. vertex2.subtractToRef(vertex0, this._edge2);
  11723. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  11724. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  11725. if (det === 0) {
  11726. return null;
  11727. }
  11728. var invdet = 1 / det;
  11729. this.origin.subtractToRef(vertex0, this._tvec);
  11730. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  11731. if (bu < 0 || bu > 1.0) {
  11732. return null;
  11733. }
  11734. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  11735. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  11736. if (bv < 0 || bu + bv > 1.0) {
  11737. return null;
  11738. }
  11739. //check if the distance is longer than the predefined length.
  11740. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  11741. if (distance > this.length) {
  11742. return null;
  11743. }
  11744. return new BABYLON.IntersectionInfo(bu, bv, distance);
  11745. };
  11746. Ray.prototype.intersectsPlane = function (plane) {
  11747. var distance;
  11748. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  11749. if (Math.abs(result1) < 9.99999997475243E-07) {
  11750. return null;
  11751. }
  11752. else {
  11753. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  11754. distance = (-plane.d - result2) / result1;
  11755. if (distance < 0.0) {
  11756. if (distance < -9.99999997475243E-07) {
  11757. return null;
  11758. }
  11759. else {
  11760. return 0;
  11761. }
  11762. }
  11763. return distance;
  11764. }
  11765. };
  11766. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  11767. var tm = BABYLON.Tmp.Matrix[0];
  11768. mesh.getWorldMatrix().invertToRef(tm);
  11769. if (this._tmpRay) {
  11770. Ray.TransformToRef(this, tm, this._tmpRay);
  11771. }
  11772. else {
  11773. this._tmpRay = Ray.Transform(this, tm);
  11774. }
  11775. return mesh.intersects(this._tmpRay, fastCheck);
  11776. };
  11777. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  11778. if (results) {
  11779. results.length = 0;
  11780. }
  11781. else {
  11782. results = [];
  11783. }
  11784. for (var i = 0; i < meshes.length; i++) {
  11785. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  11786. if (pickInfo.hit) {
  11787. results.push(pickInfo);
  11788. }
  11789. }
  11790. results.sort(this._comparePickingInfo);
  11791. return results;
  11792. };
  11793. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  11794. if (pickingInfoA.distance < pickingInfoB.distance) {
  11795. return -1;
  11796. }
  11797. else if (pickingInfoA.distance > pickingInfoB.distance) {
  11798. return 1;
  11799. }
  11800. else {
  11801. return 0;
  11802. }
  11803. };
  11804. /**
  11805. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  11806. * @param sega the first point of the segment to test the intersection against
  11807. * @param segb the second point of the segment to test the intersection against
  11808. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  11809. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  11810. */
  11811. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  11812. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  11813. var u = segb.subtract(sega);
  11814. var v = rsegb.subtract(this.origin);
  11815. var w = sega.subtract(this.origin);
  11816. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  11817. var b = BABYLON.Vector3.Dot(u, v);
  11818. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  11819. var d = BABYLON.Vector3.Dot(u, w);
  11820. var e = BABYLON.Vector3.Dot(v, w);
  11821. var D = a * c - b * b; // always >= 0
  11822. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  11823. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  11824. // compute the line parameters of the two closest points
  11825. if (D < Ray.smallnum) {
  11826. sN = 0.0; // force using point P0 on segment S1
  11827. sD = 1.0; // to prevent possible division by 0.0 later
  11828. tN = e;
  11829. tD = c;
  11830. }
  11831. else {
  11832. sN = (b * e - c * d);
  11833. tN = (a * e - b * d);
  11834. if (sN < 0.0) {
  11835. sN = 0.0;
  11836. tN = e;
  11837. tD = c;
  11838. }
  11839. else if (sN > sD) {
  11840. sN = sD;
  11841. tN = e + b;
  11842. tD = c;
  11843. }
  11844. }
  11845. if (tN < 0.0) {
  11846. tN = 0.0;
  11847. // recompute sc for this edge
  11848. if (-d < 0.0) {
  11849. sN = 0.0;
  11850. }
  11851. else if (-d > a)
  11852. sN = sD;
  11853. else {
  11854. sN = -d;
  11855. sD = a;
  11856. }
  11857. }
  11858. else if (tN > tD) {
  11859. tN = tD;
  11860. // recompute sc for this edge
  11861. if ((-d + b) < 0.0) {
  11862. sN = 0;
  11863. }
  11864. else if ((-d + b) > a) {
  11865. sN = sD;
  11866. }
  11867. else {
  11868. sN = (-d + b);
  11869. sD = a;
  11870. }
  11871. }
  11872. // finally do the division to get sc and tc
  11873. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  11874. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  11875. // get the difference of the two closest points
  11876. var qtc = v.multiplyByFloats(tc, tc, tc);
  11877. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  11878. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  11879. if (isIntersected) {
  11880. return qtc.length();
  11881. }
  11882. return -1;
  11883. };
  11884. // Statics
  11885. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  11886. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  11887. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  11888. var direction = end.subtract(start);
  11889. direction.normalize();
  11890. return new Ray(start, direction);
  11891. };
  11892. /**
  11893. * 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
  11894. * transformed to the given world matrix.
  11895. * @param origin The origin point
  11896. * @param end The end point
  11897. * @param world a matrix to transform the ray to. Default is the identity matrix.
  11898. */
  11899. Ray.CreateNewFromTo = function (origin, end, world) {
  11900. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  11901. var direction = end.subtract(origin);
  11902. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  11903. direction.normalize();
  11904. return Ray.Transform(new Ray(origin, direction, length), world);
  11905. };
  11906. Ray.Transform = function (ray, matrix) {
  11907. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  11908. Ray.TransformToRef(ray, matrix, result);
  11909. return result;
  11910. };
  11911. Ray.TransformToRef = function (ray, matrix, result) {
  11912. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  11913. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  11914. result.length = ray.length;
  11915. var dir = result.direction;
  11916. var len = dir.length();
  11917. if (!(len === 0 || len === 1)) {
  11918. var num = 1.0 / len;
  11919. dir.x *= num;
  11920. dir.y *= num;
  11921. dir.z *= num;
  11922. result.length *= len;
  11923. }
  11924. };
  11925. return Ray;
  11926. }());
  11927. Ray.smallnum = 0.00000001;
  11928. Ray.rayl = 10e8;
  11929. BABYLON.Ray = Ray;
  11930. })(BABYLON || (BABYLON = {}));
  11931. //# sourceMappingURL=babylon.ray.js.map
  11932. var BABYLON;
  11933. (function (BABYLON) {
  11934. var RayHelper = (function () {
  11935. function RayHelper(ray) {
  11936. this.ray = ray;
  11937. }
  11938. RayHelper.CreateAndShow = function (ray, scene, color) {
  11939. var helper = new RayHelper(ray);
  11940. helper.show(scene, color);
  11941. return helper;
  11942. };
  11943. RayHelper.prototype.show = function (scene, color) {
  11944. if (!this._renderFunction) {
  11945. var ray = this.ray;
  11946. this._renderFunction = this._render.bind(this);
  11947. this._scene = scene;
  11948. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  11949. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  11950. this._scene.registerBeforeRender(this._renderFunction);
  11951. }
  11952. if (color) {
  11953. this._renderLine.color.copyFrom(color);
  11954. }
  11955. };
  11956. RayHelper.prototype.hide = function () {
  11957. if (this._renderFunction) {
  11958. this._scene.unregisterBeforeRender(this._renderFunction);
  11959. this._scene = null;
  11960. this._renderFunction = null;
  11961. this._renderLine.dispose();
  11962. this._renderLine = null;
  11963. this._renderPoints = null;
  11964. }
  11965. };
  11966. RayHelper.prototype._render = function () {
  11967. var ray = this.ray;
  11968. var point = this._renderPoints[1];
  11969. var len = Math.min(ray.length, 1000000);
  11970. point.copyFrom(ray.direction);
  11971. point.scaleInPlace(len);
  11972. point.addInPlace(ray.origin);
  11973. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  11974. };
  11975. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  11976. this._attachedToMesh = mesh;
  11977. var ray = this.ray;
  11978. if (!ray.direction) {
  11979. ray.direction = BABYLON.Vector3.Zero();
  11980. }
  11981. if (!ray.origin) {
  11982. ray.origin = BABYLON.Vector3.Zero();
  11983. }
  11984. if (length) {
  11985. ray.length = length;
  11986. }
  11987. if (!meshSpaceOrigin) {
  11988. meshSpaceOrigin = BABYLON.Vector3.Zero();
  11989. }
  11990. if (!meshSpaceDirection) {
  11991. // -1 so that this will work with Mesh.lookAt
  11992. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  11993. }
  11994. if (!this._meshSpaceDirection) {
  11995. this._meshSpaceDirection = meshSpaceDirection.clone();
  11996. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  11997. }
  11998. else {
  11999. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  12000. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  12001. }
  12002. if (!this._updateToMeshFunction) {
  12003. this._updateToMeshFunction = this._updateToMesh.bind(this);
  12004. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  12005. }
  12006. this._updateToMesh();
  12007. };
  12008. RayHelper.prototype.detachFromMesh = function () {
  12009. if (this._attachedToMesh) {
  12010. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  12011. this._attachedToMesh = null;
  12012. this._updateToMeshFunction = null;
  12013. }
  12014. };
  12015. RayHelper.prototype._updateToMesh = function () {
  12016. var ray = this.ray;
  12017. if (this._attachedToMesh._isDisposed) {
  12018. this.detachFromMesh();
  12019. return;
  12020. }
  12021. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  12022. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  12023. };
  12024. RayHelper.prototype.dispose = function () {
  12025. this.hide();
  12026. this.detachFromMesh();
  12027. this.ray = null;
  12028. };
  12029. return RayHelper;
  12030. }());
  12031. BABYLON.RayHelper = RayHelper;
  12032. })(BABYLON || (BABYLON = {}));
  12033. //# sourceMappingURL=babylon.rayHelper.js.map
  12034. var BABYLON;
  12035. (function (BABYLON) {
  12036. var AbstractMesh = (function (_super) {
  12037. __extends(AbstractMesh, _super);
  12038. // Constructor
  12039. function AbstractMesh(name, scene) {
  12040. var _this = _super.call(this, name, scene) || this;
  12041. _this._facetNb = 0; // facet number
  12042. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12043. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12044. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12045. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12046. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12047. _this._subDiv = {
  12048. max: 1,
  12049. X: 1,
  12050. Y: 1,
  12051. Z: 1
  12052. };
  12053. // Events
  12054. /**
  12055. * An event triggered when this mesh collides with another one
  12056. * @type {BABYLON.Observable}
  12057. */
  12058. _this.onCollideObservable = new BABYLON.Observable();
  12059. /**
  12060. * An event triggered when the collision's position changes
  12061. * @type {BABYLON.Observable}
  12062. */
  12063. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12064. /**
  12065. * An event triggered after the world matrix is updated
  12066. * @type {BABYLON.Observable}
  12067. */
  12068. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12069. // Properties
  12070. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12071. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12072. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  12073. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  12074. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12075. _this.visibility = 1.0;
  12076. _this.alphaIndex = Number.MAX_VALUE;
  12077. _this.infiniteDistance = false;
  12078. _this.isVisible = true;
  12079. _this.isPickable = true;
  12080. _this.showBoundingBox = false;
  12081. _this.showSubMeshesBoundingBox = false;
  12082. _this.isBlocker = false;
  12083. _this.renderingGroupId = 0;
  12084. _this.receiveShadows = false;
  12085. _this.renderOutline = false;
  12086. _this.outlineColor = BABYLON.Color3.Red();
  12087. _this.outlineWidth = 0.02;
  12088. _this.renderOverlay = false;
  12089. _this.overlayColor = BABYLON.Color3.Red();
  12090. _this.overlayAlpha = 0.5;
  12091. _this.hasVertexAlpha = false;
  12092. _this.useVertexColors = true;
  12093. _this.applyFog = true;
  12094. _this.computeBonesUsingShaders = true;
  12095. _this.scalingDeterminant = 1;
  12096. _this.numBoneInfluencers = 4;
  12097. _this.useOctreeForRenderingSelection = true;
  12098. _this.useOctreeForPicking = true;
  12099. _this.useOctreeForCollisions = true;
  12100. _this.layerMask = 0x0FFFFFFF;
  12101. /**
  12102. * True if the mesh must be rendered in any case.
  12103. */
  12104. _this.alwaysSelectAsActiveMesh = false;
  12105. // Collisions
  12106. _this._checkCollisions = false;
  12107. _this._collisionMask = -1;
  12108. _this._collisionGroup = -1;
  12109. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12110. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12111. _this._collider = new BABYLON.Collider();
  12112. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12113. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12114. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  12115. // Edges
  12116. _this.edgesWidth = 1;
  12117. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  12118. // Cache
  12119. _this._localWorld = BABYLON.Matrix.Zero();
  12120. _this._worldMatrix = BABYLON.Matrix.Zero();
  12121. _this._absolutePosition = BABYLON.Vector3.Zero();
  12122. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  12123. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  12124. _this._isDirty = false;
  12125. _this._pivotMatrix = BABYLON.Matrix.Identity();
  12126. _this._isDisposed = false;
  12127. _this._renderId = 0;
  12128. _this._intersectionsInProgress = new Array();
  12129. _this._isWorldMatrixFrozen = false;
  12130. _this._unIndexed = false;
  12131. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12132. if (collidedMesh === void 0) { collidedMesh = null; }
  12133. //TODO move this to the collision coordinator!
  12134. if (_this.getScene().workerCollisions)
  12135. newPosition.multiplyInPlace(_this._collider.radius);
  12136. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  12137. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  12138. _this.position.addInPlace(_this._diffPositionForCollisions);
  12139. }
  12140. if (collidedMesh) {
  12141. _this.onCollideObservable.notifyObservers(collidedMesh);
  12142. }
  12143. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12144. };
  12145. _this.getScene().addMesh(_this);
  12146. return _this;
  12147. }
  12148. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12149. get: function () {
  12150. return AbstractMesh._BILLBOARDMODE_NONE;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12156. get: function () {
  12157. return AbstractMesh._BILLBOARDMODE_X;
  12158. },
  12159. enumerable: true,
  12160. configurable: true
  12161. });
  12162. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12163. get: function () {
  12164. return AbstractMesh._BILLBOARDMODE_Y;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12170. get: function () {
  12171. return AbstractMesh._BILLBOARDMODE_Z;
  12172. },
  12173. enumerable: true,
  12174. configurable: true
  12175. });
  12176. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12177. get: function () {
  12178. return AbstractMesh._BILLBOARDMODE_ALL;
  12179. },
  12180. enumerable: true,
  12181. configurable: true
  12182. });
  12183. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12184. /**
  12185. * Read-only : the number of facets in the mesh
  12186. */
  12187. get: function () {
  12188. return this._facetNb;
  12189. },
  12190. enumerable: true,
  12191. configurable: true
  12192. });
  12193. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12194. /**
  12195. * The number (integer) of subdivisions per axis in the partioning space
  12196. */
  12197. get: function () {
  12198. return this._partitioningSubdivisions;
  12199. },
  12200. set: function (nb) {
  12201. this._partitioningSubdivisions = nb;
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12207. /**
  12208. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12209. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12210. */
  12211. get: function () {
  12212. return this._partitioningBBoxRatio;
  12213. },
  12214. set: function (ratio) {
  12215. this._partitioningBBoxRatio = ratio;
  12216. },
  12217. enumerable: true,
  12218. configurable: true
  12219. });
  12220. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12221. /**
  12222. * Read-only boolean : is the feature facetData enabled ?
  12223. */
  12224. get: function () {
  12225. return this._facetDataEnabled;
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12231. set: function (callback) {
  12232. if (this._onCollideObserver) {
  12233. this.onCollideObservable.remove(this._onCollideObserver);
  12234. }
  12235. this._onCollideObserver = this.onCollideObservable.add(callback);
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12241. set: function (callback) {
  12242. if (this._onCollisionPositionChangeObserver) {
  12243. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12244. }
  12245. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12251. get: function () {
  12252. return this._collisionMask;
  12253. },
  12254. set: function (mask) {
  12255. this._collisionMask = !isNaN(mask) ? mask : -1;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12261. get: function () {
  12262. return this._collisionGroup;
  12263. },
  12264. set: function (mask) {
  12265. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12266. },
  12267. enumerable: true,
  12268. configurable: true
  12269. });
  12270. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12271. get: function () {
  12272. return this._skeleton;
  12273. },
  12274. set: function (value) {
  12275. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12276. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12277. }
  12278. if (value && value.needInitialSkinMatrix) {
  12279. value._registerMeshWithPoseMatrix(this);
  12280. }
  12281. this._skeleton = value;
  12282. if (!this._skeleton) {
  12283. this._bonesTransformMatrices = null;
  12284. }
  12285. },
  12286. enumerable: true,
  12287. configurable: true
  12288. });
  12289. /**
  12290. * Returns the string "AbstractMesh"
  12291. */
  12292. AbstractMesh.prototype.getClassName = function () {
  12293. return "AbstractMesh";
  12294. };
  12295. /**
  12296. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12297. */
  12298. AbstractMesh.prototype.toString = function (fullDetails) {
  12299. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12300. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12301. if (this._skeleton) {
  12302. ret += ", skeleton: " + this._skeleton.name;
  12303. }
  12304. if (fullDetails) {
  12305. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12306. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12307. }
  12308. return ret;
  12309. };
  12310. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12311. /**
  12312. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12313. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12314. * Default : (0.0, 0.0, 0.0)
  12315. */
  12316. get: function () {
  12317. return this._rotation;
  12318. },
  12319. set: function (newRotation) {
  12320. this._rotation = newRotation;
  12321. },
  12322. enumerable: true,
  12323. configurable: true
  12324. });
  12325. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12326. /**
  12327. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12328. * Default : (1.0, 1.0, 1.0)
  12329. */
  12330. get: function () {
  12331. return this._scaling;
  12332. },
  12333. set: function (newScaling) {
  12334. this._scaling = newScaling;
  12335. if (this.physicsImpostor) {
  12336. this.physicsImpostor.forceUpdate();
  12337. }
  12338. },
  12339. enumerable: true,
  12340. configurable: true
  12341. });
  12342. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12343. /**
  12344. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12345. * It's null by default.
  12346. * 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)
  12347. */
  12348. get: function () {
  12349. return this._rotationQuaternion;
  12350. },
  12351. set: function (quaternion) {
  12352. this._rotationQuaternion = quaternion;
  12353. //reset the rotation vector.
  12354. if (quaternion && this.rotation.length()) {
  12355. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12356. }
  12357. },
  12358. enumerable: true,
  12359. configurable: true
  12360. });
  12361. // Methods
  12362. /**
  12363. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12364. * Returns the AbstractMesh.
  12365. */
  12366. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12367. this._poseMatrix.copyFrom(matrix);
  12368. return this;
  12369. };
  12370. /**
  12371. * Returns the mesh Pose matrix.
  12372. * Returned object : Matrix
  12373. */
  12374. AbstractMesh.prototype.getPoseMatrix = function () {
  12375. return this._poseMatrix;
  12376. };
  12377. /**
  12378. * Disables the mesh edger rendering mode.
  12379. * Returns the AbstractMesh.
  12380. */
  12381. AbstractMesh.prototype.disableEdgesRendering = function () {
  12382. if (this._edgesRenderer !== undefined) {
  12383. this._edgesRenderer.dispose();
  12384. this._edgesRenderer = undefined;
  12385. }
  12386. return this;
  12387. };
  12388. /**
  12389. * Enables the edge rendering mode on the mesh.
  12390. * This mode makes the mesh edges visible.
  12391. * Returns the AbstractMesh.
  12392. */
  12393. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12394. if (epsilon === void 0) { epsilon = 0.95; }
  12395. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12396. this.disableEdgesRendering();
  12397. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12398. return this;
  12399. };
  12400. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12401. /**
  12402. * Returns true if the mesh is blocked. Used by the class Mesh.
  12403. * Returns the boolean `false` by default.
  12404. */
  12405. get: function () {
  12406. return false;
  12407. },
  12408. enumerable: true,
  12409. configurable: true
  12410. });
  12411. /**
  12412. * Returns the mesh itself by default, used by the class Mesh.
  12413. * Returned type : AbstractMesh
  12414. */
  12415. AbstractMesh.prototype.getLOD = function (camera) {
  12416. return this;
  12417. };
  12418. /**
  12419. * Returns 0 by default, used by the class Mesh.
  12420. * Returns an integer.
  12421. */
  12422. AbstractMesh.prototype.getTotalVertices = function () {
  12423. return 0;
  12424. };
  12425. /**
  12426. * Returns null by default, used by the class Mesh.
  12427. * Returned type : integer array
  12428. */
  12429. AbstractMesh.prototype.getIndices = function () {
  12430. return null;
  12431. };
  12432. /**
  12433. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12434. * Returned type : float array or Float32Array
  12435. */
  12436. AbstractMesh.prototype.getVerticesData = function (kind) {
  12437. return null;
  12438. };
  12439. /** Returns false by default, used by the class Mesh.
  12440. * Returns a boolean
  12441. */
  12442. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12443. return false;
  12444. };
  12445. /**
  12446. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12447. * Returns a BoundingInfo
  12448. */
  12449. AbstractMesh.prototype.getBoundingInfo = function () {
  12450. if (this._masterMesh) {
  12451. return this._masterMesh.getBoundingInfo();
  12452. }
  12453. if (!this._boundingInfo) {
  12454. this._updateBoundingInfo();
  12455. }
  12456. return this._boundingInfo;
  12457. };
  12458. /**
  12459. * Sets a mesh new object BoundingInfo.
  12460. * Returns the AbstractMesh.
  12461. */
  12462. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12463. this._boundingInfo = boundingInfo;
  12464. return this;
  12465. };
  12466. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12467. get: function () {
  12468. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12469. },
  12470. enumerable: true,
  12471. configurable: true
  12472. });
  12473. AbstractMesh.prototype._preActivate = function () {
  12474. };
  12475. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12476. };
  12477. AbstractMesh.prototype._activate = function (renderId) {
  12478. this._renderId = renderId;
  12479. };
  12480. /**
  12481. * Returns the last update of the World matrix
  12482. * Returns a Matrix.
  12483. */
  12484. AbstractMesh.prototype.getWorldMatrix = function () {
  12485. if (this._masterMesh) {
  12486. return this._masterMesh.getWorldMatrix();
  12487. }
  12488. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12489. this.computeWorldMatrix();
  12490. }
  12491. return this._worldMatrix;
  12492. };
  12493. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12494. /**
  12495. * Returns directly the last state of the mesh World matrix.
  12496. * A Matrix is returned.
  12497. */
  12498. get: function () {
  12499. return this._worldMatrix;
  12500. },
  12501. enumerable: true,
  12502. configurable: true
  12503. });
  12504. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12505. /**
  12506. * Returns the current mesh absolute position.
  12507. * Retuns a Vector3.
  12508. */
  12509. get: function () {
  12510. return this._absolutePosition;
  12511. },
  12512. enumerable: true,
  12513. configurable: true
  12514. });
  12515. /**
  12516. * Prevents the World matrix to be computed any longer.
  12517. * Returns the AbstractMesh.
  12518. */
  12519. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12520. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12521. this.computeWorldMatrix(true);
  12522. this._isWorldMatrixFrozen = true;
  12523. return this;
  12524. };
  12525. /**
  12526. * Allows back the World matrix computation.
  12527. * Returns the AbstractMesh.
  12528. */
  12529. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12530. this._isWorldMatrixFrozen = false;
  12531. this.computeWorldMatrix(true);
  12532. return this;
  12533. };
  12534. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12535. /**
  12536. * True if the World matrix has been frozen.
  12537. * Returns a boolean.
  12538. */
  12539. get: function () {
  12540. return this._isWorldMatrixFrozen;
  12541. },
  12542. enumerable: true,
  12543. configurable: true
  12544. });
  12545. /**
  12546. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12547. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12548. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12549. * The passed axis is also normalized.
  12550. * Returns the AbstractMesh.
  12551. */
  12552. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12553. axis.normalize();
  12554. if (!this.rotationQuaternion) {
  12555. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12556. this.rotation = BABYLON.Vector3.Zero();
  12557. }
  12558. var rotationQuaternion;
  12559. if (!space || space === BABYLON.Space.LOCAL) {
  12560. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12561. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12562. }
  12563. else {
  12564. if (this.parent) {
  12565. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12566. invertParentWorldMatrix.invert();
  12567. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12568. }
  12569. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12570. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12571. }
  12572. return this;
  12573. };
  12574. /**
  12575. * Translates the mesh along the axis vector for the passed distance in the given space.
  12576. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12577. * Returns the AbstractMesh.
  12578. */
  12579. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12580. var displacementVector = axis.scale(distance);
  12581. if (!space || space === BABYLON.Space.LOCAL) {
  12582. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12583. this.setPositionWithLocalVector(tempV3);
  12584. }
  12585. else {
  12586. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12587. }
  12588. return this;
  12589. };
  12590. /**
  12591. * Adds a rotation step to the mesh current rotation.
  12592. * x, y, z are Euler angles expressed in radians.
  12593. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12594. * This means this rotation is made in the mesh local space only.
  12595. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12596. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12597. * ```javascript
  12598. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12599. * ```
  12600. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12601. * 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.
  12602. * Returns the AbstractMesh.
  12603. */
  12604. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12605. var rotationQuaternion;
  12606. if (this.rotationQuaternion) {
  12607. rotationQuaternion = this.rotationQuaternion;
  12608. }
  12609. else {
  12610. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12611. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12612. }
  12613. var accumulation = BABYLON.Tmp.Quaternion[0];
  12614. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12615. rotationQuaternion.multiplyInPlace(accumulation);
  12616. if (!this.rotationQuaternion) {
  12617. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12618. }
  12619. return this;
  12620. };
  12621. /**
  12622. * Retuns the mesh absolute position in the World.
  12623. * Returns a Vector3.
  12624. */
  12625. AbstractMesh.prototype.getAbsolutePosition = function () {
  12626. this.computeWorldMatrix();
  12627. return this._absolutePosition;
  12628. };
  12629. /**
  12630. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12631. * Returns the AbstractMesh.
  12632. */
  12633. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12634. if (!absolutePosition) {
  12635. return;
  12636. }
  12637. var absolutePositionX;
  12638. var absolutePositionY;
  12639. var absolutePositionZ;
  12640. if (absolutePosition.x === undefined) {
  12641. if (arguments.length < 3) {
  12642. return;
  12643. }
  12644. absolutePositionX = arguments[0];
  12645. absolutePositionY = arguments[1];
  12646. absolutePositionZ = arguments[2];
  12647. }
  12648. else {
  12649. absolutePositionX = absolutePosition.x;
  12650. absolutePositionY = absolutePosition.y;
  12651. absolutePositionZ = absolutePosition.z;
  12652. }
  12653. if (this.parent) {
  12654. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12655. invertParentWorldMatrix.invert();
  12656. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12657. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12658. }
  12659. else {
  12660. this.position.x = absolutePositionX;
  12661. this.position.y = absolutePositionY;
  12662. this.position.z = absolutePositionZ;
  12663. }
  12664. return this;
  12665. };
  12666. // ================================== Point of View Movement =================================
  12667. /**
  12668. * Perform relative position change from the point of view of behind the front of the mesh.
  12669. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12670. * Supports definition of mesh facing forward or backward.
  12671. * @param {number} amountRight
  12672. * @param {number} amountUp
  12673. * @param {number} amountForward
  12674. *
  12675. * Returns the AbstractMesh.
  12676. */
  12677. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12678. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12679. return this;
  12680. };
  12681. /**
  12682. * Calculate relative position change from the point of view of behind the front of the mesh.
  12683. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12684. * Supports definition of mesh facing forward or backward.
  12685. * @param {number} amountRight
  12686. * @param {number} amountUp
  12687. * @param {number} amountForward
  12688. *
  12689. * Returns a new Vector3.
  12690. */
  12691. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12692. var rotMatrix = new BABYLON.Matrix();
  12693. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12694. rotQuaternion.toRotationMatrix(rotMatrix);
  12695. var translationDelta = BABYLON.Vector3.Zero();
  12696. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12697. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12698. return translationDelta;
  12699. };
  12700. // ================================== Point of View Rotation =================================
  12701. /**
  12702. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12703. * Supports definition of mesh facing forward or backward.
  12704. * @param {number} flipBack
  12705. * @param {number} twirlClockwise
  12706. * @param {number} tiltRight
  12707. *
  12708. * Returns the AbstractMesh.
  12709. */
  12710. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12711. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12712. return this;
  12713. };
  12714. /**
  12715. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12716. * Supports definition of mesh facing forward or backward.
  12717. * @param {number} flipBack
  12718. * @param {number} twirlClockwise
  12719. * @param {number} tiltRight
  12720. *
  12721. * Returns a new Vector3.
  12722. */
  12723. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12724. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12725. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12726. };
  12727. /**
  12728. * Sets a new pivot matrix to the mesh.
  12729. * Returns the AbstractMesh.
  12730. */
  12731. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12732. this._pivotMatrix = matrix;
  12733. this._cache.pivotMatrixUpdated = true;
  12734. return this;
  12735. };
  12736. /**
  12737. * Returns the mesh pivot matrix.
  12738. * Default : Identity.
  12739. * A Matrix is returned.
  12740. */
  12741. AbstractMesh.prototype.getPivotMatrix = function () {
  12742. return this._pivotMatrix;
  12743. };
  12744. AbstractMesh.prototype._isSynchronized = function () {
  12745. if (this._isDirty) {
  12746. return false;
  12747. }
  12748. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12749. return false;
  12750. if (this._cache.pivotMatrixUpdated) {
  12751. return false;
  12752. }
  12753. if (this.infiniteDistance) {
  12754. return false;
  12755. }
  12756. if (!this._cache.position.equals(this.position))
  12757. return false;
  12758. if (this.rotationQuaternion) {
  12759. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12760. return false;
  12761. }
  12762. if (!this._cache.rotation.equals(this.rotation))
  12763. return false;
  12764. if (!this._cache.scaling.equals(this.scaling))
  12765. return false;
  12766. return true;
  12767. };
  12768. AbstractMesh.prototype._initCache = function () {
  12769. _super.prototype._initCache.call(this);
  12770. this._cache.localMatrixUpdated = false;
  12771. this._cache.position = BABYLON.Vector3.Zero();
  12772. this._cache.scaling = BABYLON.Vector3.Zero();
  12773. this._cache.rotation = BABYLON.Vector3.Zero();
  12774. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12775. this._cache.billboardMode = -1;
  12776. };
  12777. AbstractMesh.prototype.markAsDirty = function (property) {
  12778. if (property === "rotation") {
  12779. this.rotationQuaternion = null;
  12780. }
  12781. this._currentRenderId = Number.MAX_VALUE;
  12782. this._isDirty = true;
  12783. return this;
  12784. };
  12785. /**
  12786. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12787. * Returns the AbstractMesh.
  12788. */
  12789. AbstractMesh.prototype._updateBoundingInfo = function () {
  12790. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12791. this._boundingInfo.update(this.worldMatrixFromCache);
  12792. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12793. return this;
  12794. };
  12795. /**
  12796. * Update a mesh's children BoundingInfo objects only.
  12797. * Returns the AbstractMesh.
  12798. */
  12799. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12800. if (!this.subMeshes) {
  12801. return;
  12802. }
  12803. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12804. var subMesh = this.subMeshes[subIndex];
  12805. if (!subMesh.IsGlobal) {
  12806. subMesh.updateBoundingInfo(matrix);
  12807. }
  12808. }
  12809. return this;
  12810. };
  12811. /**
  12812. * Computes the mesh World matrix and returns it.
  12813. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12814. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12815. * If the parameter `force`is set to `true`, the actual computation is done.
  12816. * Returns the mesh World Matrix.
  12817. */
  12818. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12819. if (this._isWorldMatrixFrozen) {
  12820. return this._worldMatrix;
  12821. }
  12822. if (!force && ((this._currentRenderId === this.getScene().getRenderId() && this.isSynchronized(true)))) {
  12823. this._currentRenderId = this.getScene().getRenderId();
  12824. return this._worldMatrix;
  12825. }
  12826. this._cache.position.copyFrom(this.position);
  12827. this._cache.scaling.copyFrom(this.scaling);
  12828. this._cache.pivotMatrixUpdated = false;
  12829. this._cache.billboardMode = this.billboardMode;
  12830. this._currentRenderId = this.getScene().getRenderId();
  12831. this._isDirty = false;
  12832. // Scaling
  12833. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12834. // Rotation
  12835. //rotate, if quaternion is set and rotation was used
  12836. if (this.rotationQuaternion) {
  12837. var len = this.rotation.length();
  12838. if (len) {
  12839. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12840. this.rotation.copyFromFloats(0, 0, 0);
  12841. }
  12842. }
  12843. if (this.rotationQuaternion) {
  12844. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12845. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12846. }
  12847. else {
  12848. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12849. this._cache.rotation.copyFrom(this.rotation);
  12850. }
  12851. // Translation
  12852. if (this.infiniteDistance && !this.parent) {
  12853. var camera = this.getScene().activeCamera;
  12854. if (camera) {
  12855. var cameraWorldMatrix = camera.getWorldMatrix();
  12856. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12857. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12858. }
  12859. }
  12860. else {
  12861. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12862. }
  12863. // Composing transformations
  12864. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12865. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12866. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12867. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12868. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12869. // Need to decompose each rotation here
  12870. var currentPosition = BABYLON.Tmp.Vector3[3];
  12871. if (this.parent && this.parent.getWorldMatrix) {
  12872. if (this._meshToBoneReferal) {
  12873. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12874. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12875. }
  12876. else {
  12877. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12878. }
  12879. }
  12880. else {
  12881. currentPosition.copyFrom(this.position);
  12882. }
  12883. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12884. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12885. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12886. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12887. }
  12888. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12889. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12890. }
  12891. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12892. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12893. }
  12894. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12895. }
  12896. else {
  12897. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12898. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12899. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12900. }
  12901. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12902. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12903. }
  12904. // Local world
  12905. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12906. // Parent
  12907. if (this.parent && this.parent.getWorldMatrix) {
  12908. this._markSyncedWithParent();
  12909. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12910. if (this._meshToBoneReferal) {
  12911. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12912. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12913. }
  12914. else {
  12915. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12916. }
  12917. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12918. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12919. this._worldMatrix.copyFrom(this._localWorld);
  12920. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12921. }
  12922. else {
  12923. if (this._meshToBoneReferal) {
  12924. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12925. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12926. }
  12927. else {
  12928. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12929. }
  12930. }
  12931. }
  12932. else {
  12933. this._worldMatrix.copyFrom(this._localWorld);
  12934. }
  12935. // Bounding info
  12936. this._updateBoundingInfo();
  12937. // Absolute position
  12938. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12939. // Callbacks
  12940. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12941. if (!this._poseMatrix) {
  12942. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12943. }
  12944. return this._worldMatrix;
  12945. };
  12946. /**
  12947. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12948. * @param func: callback function to add
  12949. *
  12950. * Returns the AbstractMesh.
  12951. */
  12952. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12953. this.onAfterWorldMatrixUpdateObservable.add(func);
  12954. return this;
  12955. };
  12956. /**
  12957. * Removes a registered callback function.
  12958. * Returns the AbstractMesh.
  12959. */
  12960. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12961. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12962. return this;
  12963. };
  12964. /**
  12965. * Sets the mesh position in its local space.
  12966. * Returns the AbstractMesh.
  12967. */
  12968. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12969. this.computeWorldMatrix();
  12970. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12971. return this;
  12972. };
  12973. /**
  12974. * Returns the mesh position in the local space from the current World matrix values.
  12975. * Returns a new Vector3.
  12976. */
  12977. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12978. this.computeWorldMatrix();
  12979. var invLocalWorldMatrix = this._localWorld.clone();
  12980. invLocalWorldMatrix.invert();
  12981. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12982. };
  12983. /**
  12984. * Translates the mesh along the passed Vector3 in its local space.
  12985. * Returns the AbstractMesh.
  12986. */
  12987. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12988. this.computeWorldMatrix(true);
  12989. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12990. return this;
  12991. };
  12992. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12993. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12994. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12995. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12996. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12997. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12998. /// <returns>Mesh oriented towards targetMesh</returns>
  12999. if (yawCor === void 0) { yawCor = 0; }
  13000. if (pitchCor === void 0) { pitchCor = 0; }
  13001. if (rollCor === void 0) { rollCor = 0; }
  13002. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13003. var dv = AbstractMesh._lookAtVectorCache;
  13004. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13005. targetPoint.subtractToRef(pos, dv);
  13006. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13007. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13008. var pitch = Math.atan2(dv.y, len);
  13009. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13010. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13011. return this;
  13012. };
  13013. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13014. this._meshToBoneReferal = affectedMesh;
  13015. this.parent = bone;
  13016. if (bone.getWorldMatrix().determinant() < 0) {
  13017. this.scalingDeterminant *= -1;
  13018. }
  13019. return this;
  13020. };
  13021. AbstractMesh.prototype.detachFromBone = function () {
  13022. if (this.parent.getWorldMatrix().determinant() < 0) {
  13023. this.scalingDeterminant *= -1;
  13024. }
  13025. this._meshToBoneReferal = null;
  13026. this.parent = null;
  13027. return this;
  13028. };
  13029. /**
  13030. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13031. * A mesh is in the frustum if its bounding box intersects the frustum.
  13032. * Boolean returned.
  13033. */
  13034. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13035. return this._boundingInfo.isInFrustum(frustumPlanes);
  13036. };
  13037. /**
  13038. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13039. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13040. * Boolean returned.
  13041. */
  13042. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13043. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13044. ;
  13045. };
  13046. /**
  13047. * True if the mesh intersects another mesh or a SolidParticle object.
  13048. * 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)
  13049. * Returns a boolean.
  13050. */
  13051. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13052. if (!this._boundingInfo || !mesh._boundingInfo) {
  13053. return false;
  13054. }
  13055. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13056. };
  13057. /**
  13058. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13059. * Returns a boolean.
  13060. */
  13061. AbstractMesh.prototype.intersectsPoint = function (point) {
  13062. if (!this._boundingInfo) {
  13063. return false;
  13064. }
  13065. return this._boundingInfo.intersectsPoint(point);
  13066. };
  13067. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13068. return this.physicsImpostor;
  13069. };
  13070. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13071. if (!camera) {
  13072. camera = this.getScene().activeCamera;
  13073. }
  13074. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13075. };
  13076. /**
  13077. * Returns the distance from the mesh to the active camera.
  13078. * Returns a float.
  13079. */
  13080. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13081. if (!camera) {
  13082. camera = this.getScene().activeCamera;
  13083. }
  13084. return this.absolutePosition.subtract(camera.position).length();
  13085. };
  13086. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13087. if (!this.physicsImpostor) {
  13088. return;
  13089. }
  13090. this.physicsImpostor.applyImpulse(force, contactPoint);
  13091. return this;
  13092. };
  13093. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13094. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13095. return;
  13096. }
  13097. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13098. mainPivot: pivot1,
  13099. connectedPivot: pivot2,
  13100. nativeParams: options
  13101. });
  13102. return this;
  13103. };
  13104. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13105. // Collisions
  13106. /**
  13107. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13108. * Default `false`.
  13109. */
  13110. get: function () {
  13111. return this._checkCollisions;
  13112. },
  13113. set: function (collisionEnabled) {
  13114. this._checkCollisions = collisionEnabled;
  13115. if (this.getScene().workerCollisions) {
  13116. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13117. }
  13118. },
  13119. enumerable: true,
  13120. configurable: true
  13121. });
  13122. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  13123. var globalPosition = this.getAbsolutePosition();
  13124. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13125. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13126. this._collider.radius = this.ellipsoid;
  13127. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13128. return this;
  13129. };
  13130. // Submeshes octree
  13131. /**
  13132. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13133. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13134. * Returns an Octree of submeshes.
  13135. */
  13136. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13137. if (maxCapacity === void 0) { maxCapacity = 64; }
  13138. if (maxDepth === void 0) { maxDepth = 2; }
  13139. if (!this._submeshesOctree) {
  13140. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13141. }
  13142. this.computeWorldMatrix(true);
  13143. // Update octree
  13144. var bbox = this.getBoundingInfo().boundingBox;
  13145. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13146. return this._submeshesOctree;
  13147. };
  13148. // Collisions
  13149. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13150. this._generatePointsArray();
  13151. // Transformation
  13152. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13153. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13154. subMesh._lastColliderWorldVertices = [];
  13155. subMesh._trianglePlanes = [];
  13156. var start = subMesh.verticesStart;
  13157. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13158. for (var i = start; i < end; i++) {
  13159. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13160. }
  13161. }
  13162. // Collide
  13163. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13164. if (collider.collisionFound) {
  13165. collider.collidedMesh = this;
  13166. }
  13167. return this;
  13168. };
  13169. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13170. var subMeshes;
  13171. var len;
  13172. // Octrees
  13173. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13174. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13175. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13176. len = intersections.length;
  13177. subMeshes = intersections.data;
  13178. }
  13179. else {
  13180. subMeshes = this.subMeshes;
  13181. len = subMeshes.length;
  13182. }
  13183. for (var index = 0; index < len; index++) {
  13184. var subMesh = subMeshes[index];
  13185. // Bounding test
  13186. if (len > 1 && !subMesh._checkCollision(collider))
  13187. continue;
  13188. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13189. }
  13190. return this;
  13191. };
  13192. AbstractMesh.prototype._checkCollision = function (collider) {
  13193. // Bounding box test
  13194. if (!this._boundingInfo._checkCollision(collider))
  13195. return this;
  13196. // Transformation matrix
  13197. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13198. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13199. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13200. return this;
  13201. };
  13202. // Picking
  13203. AbstractMesh.prototype._generatePointsArray = function () {
  13204. return false;
  13205. };
  13206. /**
  13207. * Checks if the passed Ray intersects with the mesh.
  13208. * Returns an object PickingInfo.
  13209. */
  13210. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13211. var pickingInfo = new BABYLON.PickingInfo();
  13212. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13213. return pickingInfo;
  13214. }
  13215. if (!this._generatePointsArray()) {
  13216. return pickingInfo;
  13217. }
  13218. var intersectInfo = null;
  13219. // Octrees
  13220. var subMeshes;
  13221. var len;
  13222. if (this._submeshesOctree && this.useOctreeForPicking) {
  13223. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13224. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13225. len = intersections.length;
  13226. subMeshes = intersections.data;
  13227. }
  13228. else {
  13229. subMeshes = this.subMeshes;
  13230. len = subMeshes.length;
  13231. }
  13232. for (var index = 0; index < len; index++) {
  13233. var subMesh = subMeshes[index];
  13234. // Bounding test
  13235. if (len > 1 && !subMesh.canIntersects(ray))
  13236. continue;
  13237. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13238. if (currentIntersectInfo) {
  13239. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13240. intersectInfo = currentIntersectInfo;
  13241. intersectInfo.subMeshId = index;
  13242. if (fastCheck) {
  13243. break;
  13244. }
  13245. }
  13246. }
  13247. }
  13248. if (intersectInfo) {
  13249. // Get picked point
  13250. var world = this.getWorldMatrix();
  13251. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13252. var direction = ray.direction.clone();
  13253. direction = direction.scale(intersectInfo.distance);
  13254. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13255. var pickedPoint = worldOrigin.add(worldDirection);
  13256. // Return result
  13257. pickingInfo.hit = true;
  13258. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13259. pickingInfo.pickedPoint = pickedPoint;
  13260. pickingInfo.pickedMesh = this;
  13261. pickingInfo.bu = intersectInfo.bu;
  13262. pickingInfo.bv = intersectInfo.bv;
  13263. pickingInfo.faceId = intersectInfo.faceId;
  13264. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13265. return pickingInfo;
  13266. }
  13267. return pickingInfo;
  13268. };
  13269. /**
  13270. * Clones the mesh, used by the class Mesh.
  13271. * Just returns `null` for an AbstractMesh.
  13272. */
  13273. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13274. return null;
  13275. };
  13276. /**
  13277. * Disposes all the mesh submeshes.
  13278. * Returns the AbstractMesh.
  13279. */
  13280. AbstractMesh.prototype.releaseSubMeshes = function () {
  13281. if (this.subMeshes) {
  13282. while (this.subMeshes.length) {
  13283. this.subMeshes[0].dispose();
  13284. }
  13285. }
  13286. else {
  13287. this.subMeshes = new Array();
  13288. }
  13289. return this;
  13290. };
  13291. /**
  13292. * Disposes the AbstractMesh.
  13293. * Some internal references are kept for further use.
  13294. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13295. * Returns nothing.
  13296. */
  13297. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13298. var _this = this;
  13299. var index;
  13300. // Action manager
  13301. if (this.actionManager) {
  13302. this.actionManager.dispose();
  13303. this.actionManager = null;
  13304. }
  13305. // Skeleton
  13306. this.skeleton = null;
  13307. // Animations
  13308. this.getScene().stopAnimation(this);
  13309. // Physics
  13310. if (this.physicsImpostor) {
  13311. this.physicsImpostor.dispose();
  13312. }
  13313. // Intersections in progress
  13314. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13315. var other = this._intersectionsInProgress[index];
  13316. var pos = other._intersectionsInProgress.indexOf(this);
  13317. other._intersectionsInProgress.splice(pos, 1);
  13318. }
  13319. this._intersectionsInProgress = [];
  13320. // Lights
  13321. var lights = this.getScene().lights;
  13322. lights.forEach(function (light) {
  13323. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13324. if (meshIndex !== -1) {
  13325. light.includedOnlyMeshes.splice(meshIndex, 1);
  13326. }
  13327. meshIndex = light.excludedMeshes.indexOf(_this);
  13328. if (meshIndex !== -1) {
  13329. light.excludedMeshes.splice(meshIndex, 1);
  13330. }
  13331. // Shadow generators
  13332. var generator = light.getShadowGenerator();
  13333. if (generator) {
  13334. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  13335. if (meshIndex !== -1) {
  13336. generator.getShadowMap().renderList.splice(meshIndex, 1);
  13337. }
  13338. }
  13339. });
  13340. // Edges
  13341. if (this._edgesRenderer) {
  13342. this._edgesRenderer.dispose();
  13343. this._edgesRenderer = null;
  13344. }
  13345. // SubMeshes
  13346. if (this.getClassName() !== "InstancedMesh") {
  13347. this.releaseSubMeshes();
  13348. }
  13349. // Engine
  13350. this.getScene().getEngine().wipeCaches();
  13351. // Remove from scene
  13352. this.getScene().removeMesh(this);
  13353. if (!doNotRecurse) {
  13354. // Particles
  13355. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13356. if (this.getScene().particleSystems[index].emitter === this) {
  13357. this.getScene().particleSystems[index].dispose();
  13358. index--;
  13359. }
  13360. }
  13361. // Children
  13362. var objects = this.getDescendants(true);
  13363. for (index = 0; index < objects.length; index++) {
  13364. objects[index].dispose();
  13365. }
  13366. }
  13367. else {
  13368. var childMeshes = this.getChildMeshes(true);
  13369. for (index = 0; index < childMeshes.length; index++) {
  13370. var child = childMeshes[index];
  13371. child.parent = null;
  13372. child.computeWorldMatrix(true);
  13373. }
  13374. }
  13375. // facet data
  13376. if (this._facetDataEnabled) {
  13377. this.disableFacetData();
  13378. }
  13379. this.onAfterWorldMatrixUpdateObservable.clear();
  13380. this.onCollideObservable.clear();
  13381. this.onCollisionPositionChangeObservable.clear();
  13382. this._isDisposed = true;
  13383. _super.prototype.dispose.call(this);
  13384. };
  13385. /**
  13386. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13387. * This Vector3 is expressed in the World space.
  13388. */
  13389. AbstractMesh.prototype.getDirection = function (localAxis) {
  13390. var result = BABYLON.Vector3.Zero();
  13391. this.getDirectionToRef(localAxis, result);
  13392. return result;
  13393. };
  13394. /**
  13395. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13396. * localAxis is expressed in the mesh local space.
  13397. * result is computed in the Wordl space from the mesh World matrix.
  13398. * Returns the AbstractMesh.
  13399. */
  13400. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13401. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13402. return this;
  13403. };
  13404. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13405. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13406. if (this.getScene().getRenderId() == 0) {
  13407. this.computeWorldMatrix(true);
  13408. }
  13409. var wm = this.getWorldMatrix();
  13410. if (space == BABYLON.Space.WORLD) {
  13411. var tmat = BABYLON.Tmp.Matrix[0];
  13412. wm.invertToRef(tmat);
  13413. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13414. }
  13415. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13416. this._pivotMatrix.m[12] = -point.x;
  13417. this._pivotMatrix.m[13] = -point.y;
  13418. this._pivotMatrix.m[14] = -point.z;
  13419. this._cache.pivotMatrixUpdated = true;
  13420. return this;
  13421. };
  13422. /**
  13423. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13424. */
  13425. AbstractMesh.prototype.getPivotPoint = function () {
  13426. var point = BABYLON.Vector3.Zero();
  13427. this.getPivotPointToRef(point);
  13428. return point;
  13429. };
  13430. /**
  13431. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13432. * Returns the AbstractMesh.
  13433. */
  13434. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13435. result.x = -this._pivotMatrix.m[12];
  13436. result.y = -this._pivotMatrix.m[13];
  13437. result.z = -this._pivotMatrix.m[14];
  13438. return this;
  13439. };
  13440. /**
  13441. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13442. */
  13443. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13444. var point = BABYLON.Vector3.Zero();
  13445. this.getAbsolutePivotPointToRef(point);
  13446. return point;
  13447. };
  13448. /**
  13449. * Defines the passed mesh as the parent of the current mesh.
  13450. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  13451. * Returns the AbstractMesh.
  13452. */
  13453. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  13454. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13455. var child = this;
  13456. var parent = mesh;
  13457. if (mesh == null) {
  13458. if (child.parent && keepWorldPositionRotation) {
  13459. var rotation = BABYLON.Tmp.Quaternion[0];
  13460. var position = BABYLON.Tmp.Vector3[0];
  13461. var scale = BABYLON.Tmp.Vector3[1];
  13462. child.getWorldMatrix().decompose(scale, rotation, position);
  13463. if (child.rotationQuaternion) {
  13464. child.rotationQuaternion.copyFrom(rotation);
  13465. }
  13466. else {
  13467. rotation.toEulerAnglesToRef(child.rotation);
  13468. }
  13469. child.position.x = position.x;
  13470. child.position.y = position.y;
  13471. child.position.z = position.z;
  13472. }
  13473. }
  13474. else {
  13475. if (keepWorldPositionRotation) {
  13476. var rotation = BABYLON.Tmp.Quaternion[0];
  13477. var position = BABYLON.Tmp.Vector3[0];
  13478. var scale = BABYLON.Tmp.Vector3[1];
  13479. var m1 = BABYLON.Tmp.Matrix[0];
  13480. var m2 = BABYLON.Tmp.Matrix[1];
  13481. parent.getWorldMatrix().decompose(scale, rotation, position);
  13482. rotation.toRotationMatrix(m1);
  13483. m2.setTranslation(position);
  13484. m2.multiplyToRef(m1, m1);
  13485. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13486. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13487. m.decompose(scale, rotation, position);
  13488. if (child.rotationQuaternion) {
  13489. child.rotationQuaternion.copyFrom(rotation);
  13490. }
  13491. else {
  13492. rotation.toEulerAnglesToRef(child.rotation);
  13493. }
  13494. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13495. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13496. m.decompose(scale, rotation, position);
  13497. child.position.x = position.x;
  13498. child.position.y = position.y;
  13499. child.position.z = position.z;
  13500. }
  13501. }
  13502. child.parent = parent;
  13503. return this;
  13504. };
  13505. /**
  13506. * Adds the passed mesh as a child to the current mesh.
  13507. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  13508. * Returns the AbstractMesh.
  13509. */
  13510. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  13511. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13512. mesh.setParent(this, keepWorldPositionRotation);
  13513. return this;
  13514. };
  13515. /**
  13516. * Removes the passed mesh from the current mesh children list.
  13517. * Returns the AbstractMesh.
  13518. */
  13519. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  13520. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  13521. mesh.setParent(null, keepWorldPositionRotation);
  13522. return this;
  13523. };
  13524. /**
  13525. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13526. * Returns the AbstractMesh.
  13527. */
  13528. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13529. result.x = this._pivotMatrix.m[12];
  13530. result.y = this._pivotMatrix.m[13];
  13531. result.z = this._pivotMatrix.m[14];
  13532. this.getPivotPointToRef(result);
  13533. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13534. return this;
  13535. };
  13536. // Facet data
  13537. /**
  13538. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13539. * Returns the AbstractMesh.
  13540. */
  13541. AbstractMesh.prototype._initFacetData = function () {
  13542. if (!this._facetNormals) {
  13543. this._facetNormals = new Array();
  13544. }
  13545. if (!this._facetPositions) {
  13546. this._facetPositions = new Array();
  13547. }
  13548. if (!this._facetPartitioning) {
  13549. this._facetPartitioning = new Array();
  13550. }
  13551. this._facetNb = this.getIndices().length / 3;
  13552. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13553. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13554. for (var f = 0; f < this._facetNb; f++) {
  13555. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13556. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13557. }
  13558. this._facetDataEnabled = true;
  13559. return this;
  13560. };
  13561. /**
  13562. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13563. * This method can be called within the render loop.
  13564. * 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.
  13565. * Returns the AbstractMesh.
  13566. */
  13567. AbstractMesh.prototype.updateFacetData = function () {
  13568. if (!this._facetDataEnabled) {
  13569. this._initFacetData();
  13570. }
  13571. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13572. var indices = this.getIndices();
  13573. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13574. var bInfo = this.getBoundingInfo();
  13575. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13576. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13577. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13578. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13579. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13580. this._subDiv.max = this._partitioningSubdivisions;
  13581. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13582. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13583. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13584. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13585. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13586. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13587. // set the parameters for ComputeNormals()
  13588. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13589. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13590. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13591. this._facetParameters.bInfo = bInfo;
  13592. this._facetParameters.bbSize = this._bbSize;
  13593. this._facetParameters.subDiv = this._subDiv;
  13594. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13595. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13596. return this;
  13597. };
  13598. /**
  13599. * Returns the facetLocalNormals array.
  13600. * The normals are expressed in the mesh local space.
  13601. */
  13602. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13603. if (!this._facetNormals) {
  13604. this.updateFacetData();
  13605. }
  13606. return this._facetNormals;
  13607. };
  13608. /**
  13609. * Returns the facetLocalPositions array.
  13610. * The facet positions are expressed in the mesh local space.
  13611. */
  13612. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13613. if (!this._facetPositions) {
  13614. this.updateFacetData();
  13615. }
  13616. return this._facetPositions;
  13617. };
  13618. /**
  13619. * Returns the facetLocalPartioning array.
  13620. */
  13621. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13622. if (!this._facetPartitioning) {
  13623. this.updateFacetData();
  13624. }
  13625. return this._facetPartitioning;
  13626. };
  13627. /**
  13628. * Returns the i-th facet position in the world system.
  13629. * This method allocates a new Vector3 per call.
  13630. */
  13631. AbstractMesh.prototype.getFacetPosition = function (i) {
  13632. var pos = BABYLON.Vector3.Zero();
  13633. this.getFacetPositionToRef(i, pos);
  13634. return pos;
  13635. };
  13636. /**
  13637. * Sets the reference Vector3 with the i-th facet position in the world system.
  13638. * Returns the AbstractMesh.
  13639. */
  13640. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13641. var localPos = (this.getFacetLocalPositions())[i];
  13642. var world = this.getWorldMatrix();
  13643. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13644. return this;
  13645. };
  13646. /**
  13647. * Returns the i-th facet normal in the world system.
  13648. * This method allocates a new Vector3 per call.
  13649. */
  13650. AbstractMesh.prototype.getFacetNormal = function (i) {
  13651. var norm = BABYLON.Vector3.Zero();
  13652. this.getFacetNormalToRef(i, norm);
  13653. return norm;
  13654. };
  13655. /**
  13656. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13657. * Returns the AbstractMesh.
  13658. */
  13659. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13660. var localNorm = (this.getFacetLocalNormals())[i];
  13661. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13662. return this;
  13663. };
  13664. /**
  13665. * 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).
  13666. */
  13667. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13668. var bInfo = this.getBoundingInfo();
  13669. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13670. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13671. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13672. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13673. return null;
  13674. }
  13675. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13676. };
  13677. /**
  13678. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13679. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13680. * 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.
  13681. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13682. * 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.
  13683. */
  13684. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13685. if (checkFace === void 0) { checkFace = false; }
  13686. if (facing === void 0) { facing = true; }
  13687. var world = this.getWorldMatrix();
  13688. var invMat = BABYLON.Tmp.Matrix[5];
  13689. world.invertToRef(invMat);
  13690. var invVect = BABYLON.Tmp.Vector3[8];
  13691. var closest = null;
  13692. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13693. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13694. if (projected) {
  13695. // tranform the local computed projected vector to world coordinates
  13696. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13697. }
  13698. return closest;
  13699. };
  13700. /**
  13701. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13702. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13703. * 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.
  13704. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13705. * 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.
  13706. */
  13707. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13708. if (checkFace === void 0) { checkFace = false; }
  13709. if (facing === void 0) { facing = true; }
  13710. var closest = null;
  13711. var tmpx = 0.0;
  13712. var tmpy = 0.0;
  13713. var tmpz = 0.0;
  13714. var d = 0.0; // tmp dot facet normal * facet position
  13715. var t0 = 0.0;
  13716. var projx = 0.0;
  13717. var projy = 0.0;
  13718. var projz = 0.0;
  13719. // Get all the facets in the same partitioning block than (x, y, z)
  13720. var facetPositions = this.getFacetLocalPositions();
  13721. var facetNormals = this.getFacetLocalNormals();
  13722. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13723. if (!facetsInBlock) {
  13724. return null;
  13725. }
  13726. // Get the closest facet to (x, y, z)
  13727. var shortest = Number.MAX_VALUE; // init distance vars
  13728. var tmpDistance = shortest;
  13729. var fib; // current facet in the block
  13730. var norm; // current facet normal
  13731. var p0; // current facet barycenter position
  13732. // loop on all the facets in the current partitioning block
  13733. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13734. fib = facetsInBlock[idx];
  13735. norm = facetNormals[fib];
  13736. p0 = facetPositions[fib];
  13737. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13738. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13739. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13740. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13741. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13742. projx = x + norm.x * t0;
  13743. projy = y + norm.y * t0;
  13744. projz = z + norm.z * t0;
  13745. tmpx = projx - x;
  13746. tmpy = projy - y;
  13747. tmpz = projz - z;
  13748. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13749. if (tmpDistance < shortest) {
  13750. shortest = tmpDistance;
  13751. closest = fib;
  13752. if (projected) {
  13753. projected.x = projx;
  13754. projected.y = projy;
  13755. projected.z = projz;
  13756. }
  13757. }
  13758. }
  13759. }
  13760. return closest;
  13761. };
  13762. /**
  13763. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13764. */
  13765. AbstractMesh.prototype.getFacetDataParameters = function () {
  13766. return this._facetParameters;
  13767. };
  13768. /**
  13769. * Disables the feature FacetData and frees the related memory.
  13770. * Returns the AbstractMesh.
  13771. */
  13772. AbstractMesh.prototype.disableFacetData = function () {
  13773. if (this._facetDataEnabled) {
  13774. this._facetDataEnabled = false;
  13775. this._facetPositions = null;
  13776. this._facetNormals = null;
  13777. this._facetPartitioning = null;
  13778. this._facetParameters = null;
  13779. }
  13780. return this;
  13781. };
  13782. return AbstractMesh;
  13783. }(BABYLON.Node));
  13784. // Statics
  13785. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13786. AbstractMesh._BILLBOARDMODE_X = 1;
  13787. AbstractMesh._BILLBOARDMODE_Y = 2;
  13788. AbstractMesh._BILLBOARDMODE_Z = 4;
  13789. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13790. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13791. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13792. BABYLON.AbstractMesh = AbstractMesh;
  13793. })(BABYLON || (BABYLON = {}));
  13794. //# sourceMappingURL=babylon.abstractMesh.js.map
  13795. var BABYLON;
  13796. (function (BABYLON) {
  13797. var Light = (function (_super) {
  13798. __extends(Light, _super);
  13799. /**
  13800. * Creates a Light object in the scene.
  13801. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13802. */
  13803. function Light(name, scene) {
  13804. var _this = _super.call(this, name, scene) || this;
  13805. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13806. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13807. _this.intensity = 1.0;
  13808. _this.range = Number.MAX_VALUE;
  13809. _this.includeOnlyWithLayerMask = 0;
  13810. _this.includedOnlyMeshes = new Array();
  13811. _this.excludedMeshes = new Array();
  13812. _this.excludeWithLayerMask = 0;
  13813. _this.lightmapMode = 0;
  13814. // PBR Properties.
  13815. _this.radius = 0.00001;
  13816. _this._excludedMeshesIds = new Array();
  13817. _this._includedOnlyMeshesIds = new Array();
  13818. _this.getScene().addLight(_this);
  13819. return _this;
  13820. }
  13821. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13822. /**
  13823. * If every light affecting the material is in this lightmapMode,
  13824. * material.lightmapTexture adds or multiplies
  13825. * (depends on material.useLightmapAsShadowmap)
  13826. * after every other light calculations.
  13827. */
  13828. get: function () {
  13829. return Light._LIGHTMAP_DEFAULT;
  13830. },
  13831. enumerable: true,
  13832. configurable: true
  13833. });
  13834. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13835. /**
  13836. * material.lightmapTexture as only diffuse lighting from this light
  13837. * adds pnly specular lighting from this light
  13838. * adds dynamic shadows
  13839. */
  13840. get: function () {
  13841. return Light._LIGHTMAP_SPECULAR;
  13842. },
  13843. enumerable: true,
  13844. configurable: true
  13845. });
  13846. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13847. /**
  13848. * material.lightmapTexture as only lighting
  13849. * no light calculation from this light
  13850. * only adds dynamic shadows from this light
  13851. */
  13852. get: function () {
  13853. return Light._LIGHTMAP_SHADOWSONLY;
  13854. },
  13855. enumerable: true,
  13856. configurable: true
  13857. });
  13858. /**
  13859. * Returns the string "Light".
  13860. */
  13861. Light.prototype.getClassName = function () {
  13862. return "Light";
  13863. };
  13864. /**
  13865. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13866. */
  13867. Light.prototype.toString = function (fullDetails) {
  13868. var ret = "Name: " + this.name;
  13869. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13870. if (this.animations) {
  13871. for (var i = 0; i < this.animations.length; i++) {
  13872. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13873. }
  13874. }
  13875. if (fullDetails) {
  13876. }
  13877. return ret;
  13878. };
  13879. /**
  13880. * Returns the Light associated shadow generator.
  13881. */
  13882. Light.prototype.getShadowGenerator = function () {
  13883. return this._shadowGenerator;
  13884. };
  13885. /**
  13886. * Returns a Vector3, the absolute light position in the World.
  13887. */
  13888. Light.prototype.getAbsolutePosition = function () {
  13889. return BABYLON.Vector3.Zero();
  13890. };
  13891. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  13892. };
  13893. Light.prototype._getWorldMatrix = function () {
  13894. return BABYLON.Matrix.Identity();
  13895. };
  13896. /**
  13897. * Boolean : True if the light will affect the passed mesh.
  13898. */
  13899. Light.prototype.canAffectMesh = function (mesh) {
  13900. if (!mesh) {
  13901. return true;
  13902. }
  13903. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13904. return false;
  13905. }
  13906. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13907. return false;
  13908. }
  13909. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13910. return false;
  13911. }
  13912. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13913. return false;
  13914. }
  13915. return true;
  13916. };
  13917. /**
  13918. * Returns the light World matrix.
  13919. */
  13920. Light.prototype.getWorldMatrix = function () {
  13921. this._currentRenderId = this.getScene().getRenderId();
  13922. var worldMatrix = this._getWorldMatrix();
  13923. if (this.parent && this.parent.getWorldMatrix) {
  13924. if (!this._parentedWorldMatrix) {
  13925. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13926. }
  13927. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13928. this._markSyncedWithParent();
  13929. return this._parentedWorldMatrix;
  13930. }
  13931. return worldMatrix;
  13932. };
  13933. /**
  13934. * Disposes the light.
  13935. */
  13936. Light.prototype.dispose = function () {
  13937. if (this._shadowGenerator) {
  13938. this._shadowGenerator.dispose();
  13939. this._shadowGenerator = null;
  13940. }
  13941. // Animations
  13942. this.getScene().stopAnimation(this);
  13943. // Remove from scene
  13944. this.getScene().removeLight(this);
  13945. _super.prototype.dispose.call(this);
  13946. };
  13947. /**
  13948. * Returns the light type ID (integer).
  13949. */
  13950. Light.prototype.getTypeID = function () {
  13951. return 0;
  13952. };
  13953. /**
  13954. * Returns a new Light object, named "name", from the current one.
  13955. */
  13956. Light.prototype.clone = function (name) {
  13957. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13958. };
  13959. /**
  13960. * Serializes the current light into a Serialization object.
  13961. * Returns the serialized object.
  13962. */
  13963. Light.prototype.serialize = function () {
  13964. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13965. // Type
  13966. serializationObject.type = this.getTypeID();
  13967. // Parent
  13968. if (this.parent) {
  13969. serializationObject.parentId = this.parent.id;
  13970. }
  13971. // Inclusion / exclusions
  13972. if (this.excludedMeshes.length > 0) {
  13973. serializationObject.excludedMeshesIds = [];
  13974. this.excludedMeshes.forEach(function (mesh) {
  13975. serializationObject.excludedMeshesIds.push(mesh.id);
  13976. });
  13977. }
  13978. if (this.includedOnlyMeshes.length > 0) {
  13979. serializationObject.includedOnlyMeshesIds = [];
  13980. this.includedOnlyMeshes.forEach(function (mesh) {
  13981. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13982. });
  13983. }
  13984. // Animations
  13985. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13986. serializationObject.ranges = this.serializeAnimationRanges();
  13987. return serializationObject;
  13988. };
  13989. /**
  13990. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13991. * This new light is named "name" and added to the passed scene.
  13992. */
  13993. Light.GetConstructorFromName = function (type, name, scene) {
  13994. switch (type) {
  13995. case 0:
  13996. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13997. case 1:
  13998. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13999. case 2:
  14000. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14001. case 3:
  14002. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14003. }
  14004. };
  14005. /**
  14006. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14007. */
  14008. Light.Parse = function (parsedLight, scene) {
  14009. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14010. // Inclusion / exclusions
  14011. if (parsedLight.excludedMeshesIds) {
  14012. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14013. }
  14014. if (parsedLight.includedOnlyMeshesIds) {
  14015. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14016. }
  14017. // Parent
  14018. if (parsedLight.parentId) {
  14019. light._waitingParentId = parsedLight.parentId;
  14020. }
  14021. // Animations
  14022. if (parsedLight.animations) {
  14023. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14024. var parsedAnimation = parsedLight.animations[animationIndex];
  14025. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14026. }
  14027. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14028. }
  14029. if (parsedLight.autoAnimate) {
  14030. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14031. }
  14032. return light;
  14033. };
  14034. return Light;
  14035. }(BABYLON.Node));
  14036. //lightmapMode Consts
  14037. Light._LIGHTMAP_DEFAULT = 0;
  14038. Light._LIGHTMAP_SPECULAR = 1;
  14039. Light._LIGHTMAP_SHADOWSONLY = 2;
  14040. __decorate([
  14041. BABYLON.serializeAsColor3()
  14042. ], Light.prototype, "diffuse", void 0);
  14043. __decorate([
  14044. BABYLON.serializeAsColor3()
  14045. ], Light.prototype, "specular", void 0);
  14046. __decorate([
  14047. BABYLON.serialize()
  14048. ], Light.prototype, "intensity", void 0);
  14049. __decorate([
  14050. BABYLON.serialize()
  14051. ], Light.prototype, "range", void 0);
  14052. __decorate([
  14053. BABYLON.serialize()
  14054. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  14055. __decorate([
  14056. BABYLON.serialize()
  14057. ], Light.prototype, "excludeWithLayerMask", void 0);
  14058. __decorate([
  14059. BABYLON.serialize()
  14060. ], Light.prototype, "lightmapMode", void 0);
  14061. __decorate([
  14062. BABYLON.serialize()
  14063. ], Light.prototype, "radius", void 0);
  14064. BABYLON.Light = Light;
  14065. })(BABYLON || (BABYLON = {}));
  14066. //# sourceMappingURL=babylon.light.js.map
  14067. var BABYLON;
  14068. (function (BABYLON) {
  14069. var PointLight = (function (_super) {
  14070. __extends(PointLight, _super);
  14071. /**
  14072. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  14073. * A PointLight emits the light in every direction.
  14074. * It can cast shadows.
  14075. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  14076. * ```javascript
  14077. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  14078. * ```
  14079. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14080. */
  14081. function PointLight(name, position, scene) {
  14082. var _this = _super.call(this, name, scene) || this;
  14083. _this.position = position;
  14084. return _this;
  14085. }
  14086. /**
  14087. * Returns the string "PointLight"
  14088. */
  14089. PointLight.prototype.getClassName = function () {
  14090. return "PointLight";
  14091. };
  14092. /**
  14093. * Returns a Vector3, the PointLight absolute position in the World.
  14094. */
  14095. PointLight.prototype.getAbsolutePosition = function () {
  14096. return this.transformedPosition ? this.transformedPosition : this.position;
  14097. };
  14098. /**
  14099. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  14100. */
  14101. PointLight.prototype.computeTransformedPosition = function () {
  14102. if (this.parent && this.parent.getWorldMatrix) {
  14103. if (!this.transformedPosition) {
  14104. this.transformedPosition = BABYLON.Vector3.Zero();
  14105. }
  14106. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14107. return true;
  14108. }
  14109. return false;
  14110. };
  14111. /**
  14112. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  14113. * Returns the PointLight.
  14114. */
  14115. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  14116. if (this.parent && this.parent.getWorldMatrix) {
  14117. this.computeTransformedPosition();
  14118. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0);
  14119. return this;
  14120. }
  14121. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  14122. return this;
  14123. };
  14124. /**
  14125. * Boolean : returns true by default.
  14126. */
  14127. PointLight.prototype.needCube = function () {
  14128. return true;
  14129. };
  14130. /**
  14131. * Boolean : returns false by default.
  14132. */
  14133. PointLight.prototype.needRefreshPerFrame = function () {
  14134. return false;
  14135. };
  14136. /**
  14137. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  14138. */
  14139. PointLight.prototype.getShadowDirection = function (faceIndex) {
  14140. switch (faceIndex) {
  14141. case 0:
  14142. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  14143. case 1:
  14144. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  14145. case 2:
  14146. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  14147. case 3:
  14148. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  14149. case 4:
  14150. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  14151. case 5:
  14152. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  14153. }
  14154. return BABYLON.Vector3.Zero();
  14155. };
  14156. /**
  14157. * Return the depth scale used for the shadow map.
  14158. */
  14159. PointLight.prototype.getDepthScale = function () {
  14160. return 30.0;
  14161. };
  14162. /**
  14163. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  14164. * - fov = PI / 2
  14165. * - aspect ratio : 1.0
  14166. * - z-near and far equal to the active camera minZ and maxZ.
  14167. * Returns the PointLight.
  14168. */
  14169. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14170. if (this.customProjectionMatrixBuilder) {
  14171. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14172. }
  14173. else {
  14174. var activeCamera = this.getScene().activeCamera;
  14175. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14176. }
  14177. return this;
  14178. };
  14179. PointLight.prototype._getWorldMatrix = function () {
  14180. if (!this._worldMatrix) {
  14181. this._worldMatrix = BABYLON.Matrix.Identity();
  14182. }
  14183. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14184. return this._worldMatrix;
  14185. };
  14186. /**
  14187. * Returns the integer 0.
  14188. */
  14189. PointLight.prototype.getTypeID = function () {
  14190. return 0;
  14191. };
  14192. return PointLight;
  14193. }(BABYLON.Light));
  14194. __decorate([
  14195. BABYLON.serializeAsVector3()
  14196. ], PointLight.prototype, "position", void 0);
  14197. __decorate([
  14198. BABYLON.serialize()
  14199. ], PointLight.prototype, "shadowMinZ", void 0);
  14200. __decorate([
  14201. BABYLON.serialize()
  14202. ], PointLight.prototype, "shadowMaxZ", void 0);
  14203. BABYLON.PointLight = PointLight;
  14204. })(BABYLON || (BABYLON = {}));
  14205. //# sourceMappingURL=babylon.pointLight.js.map
  14206. var BABYLON;
  14207. (function (BABYLON) {
  14208. var SpotLight = (function (_super) {
  14209. __extends(SpotLight, _super);
  14210. /**
  14211. * Creates a SpotLight object in the scene with the passed parameters :
  14212. * - `position` (Vector3) is the initial SpotLight position,
  14213. * - `direction` (Vector3) is the initial SpotLight direction,
  14214. * - `angle` (float, in radians) is the spot light cone angle,
  14215. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  14216. * A spot light is a simply light oriented cone.
  14217. * It can cast shadows.
  14218. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14219. */
  14220. function SpotLight(name, position, direction, angle, exponent, scene) {
  14221. var _this = _super.call(this, name, scene) || this;
  14222. _this.position = position;
  14223. _this.direction = direction;
  14224. _this.angle = angle;
  14225. _this.exponent = exponent;
  14226. return _this;
  14227. }
  14228. /**
  14229. * Returns the string "SpotLight".
  14230. */
  14231. SpotLight.prototype.getClassName = function () {
  14232. return "SpotLight";
  14233. };
  14234. /**
  14235. * Returns the SpotLight absolute position in the World (Vector3).
  14236. */
  14237. SpotLight.prototype.getAbsolutePosition = function () {
  14238. return this.transformedPosition ? this.transformedPosition : this.position;
  14239. };
  14240. /**
  14241. * Return the depth scale used for the shadow map.
  14242. */
  14243. SpotLight.prototype.getDepthScale = function () {
  14244. return 30.0;
  14245. };
  14246. /**
  14247. * 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.
  14248. * Returns the SpotLight.
  14249. */
  14250. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14251. if (this.customProjectionMatrixBuilder) {
  14252. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14253. }
  14254. else {
  14255. var activeCamera = this.getScene().activeCamera;
  14256. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  14257. }
  14258. return this;
  14259. };
  14260. /**
  14261. * Boolean : false by default.
  14262. */
  14263. SpotLight.prototype.needCube = function () {
  14264. return false;
  14265. };
  14266. /**
  14267. * Boolean : false by default.
  14268. */
  14269. SpotLight.prototype.needRefreshPerFrame = function () {
  14270. return false;
  14271. };
  14272. /**
  14273. * Returns the SpotLight direction (Vector3) for any passed face index.
  14274. */
  14275. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  14276. return this.direction;
  14277. };
  14278. /**
  14279. * Updates the SpotLight direction towards the passed target (Vector3).
  14280. * Returns the updated direction.
  14281. */
  14282. SpotLight.prototype.setDirectionToTarget = function (target) {
  14283. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14284. return this.direction;
  14285. };
  14286. /**
  14287. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  14288. */
  14289. SpotLight.prototype.computeTransformedPosition = function () {
  14290. if (this.parent && this.parent.getWorldMatrix) {
  14291. if (!this.transformedPosition) {
  14292. this.transformedPosition = BABYLON.Vector3.Zero();
  14293. }
  14294. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14295. return true;
  14296. }
  14297. return false;
  14298. };
  14299. /**
  14300. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  14301. * Return the SpotLight.
  14302. */
  14303. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  14304. var normalizeDirection;
  14305. if (this.parent && this.parent.getWorldMatrix) {
  14306. if (!this._transformedDirection) {
  14307. this._transformedDirection = BABYLON.Vector3.Zero();
  14308. }
  14309. this.computeTransformedPosition();
  14310. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14311. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  14312. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  14313. }
  14314. else {
  14315. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  14316. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14317. }
  14318. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  14319. return this;
  14320. };
  14321. SpotLight.prototype._getWorldMatrix = function () {
  14322. if (!this._worldMatrix) {
  14323. this._worldMatrix = BABYLON.Matrix.Identity();
  14324. }
  14325. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14326. return this._worldMatrix;
  14327. };
  14328. /**
  14329. * Returns the integer 2.
  14330. */
  14331. SpotLight.prototype.getTypeID = function () {
  14332. return 2;
  14333. };
  14334. /**
  14335. * Returns the SpotLight rotation (Vector3).
  14336. */
  14337. SpotLight.prototype.getRotation = function () {
  14338. this.direction.normalize();
  14339. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  14340. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  14341. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  14342. };
  14343. return SpotLight;
  14344. }(BABYLON.Light));
  14345. __decorate([
  14346. BABYLON.serializeAsVector3()
  14347. ], SpotLight.prototype, "position", void 0);
  14348. __decorate([
  14349. BABYLON.serializeAsVector3()
  14350. ], SpotLight.prototype, "direction", void 0);
  14351. __decorate([
  14352. BABYLON.serialize()
  14353. ], SpotLight.prototype, "angle", void 0);
  14354. __decorate([
  14355. BABYLON.serialize()
  14356. ], SpotLight.prototype, "exponent", void 0);
  14357. __decorate([
  14358. BABYLON.serialize()
  14359. ], SpotLight.prototype, "shadowMinZ", void 0);
  14360. __decorate([
  14361. BABYLON.serialize()
  14362. ], SpotLight.prototype, "shadowMaxZ", void 0);
  14363. BABYLON.SpotLight = SpotLight;
  14364. })(BABYLON || (BABYLON = {}));
  14365. //# sourceMappingURL=babylon.spotLight.js.map
  14366. var BABYLON;
  14367. (function (BABYLON) {
  14368. var HemisphericLight = (function (_super) {
  14369. __extends(HemisphericLight, _super);
  14370. /**
  14371. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  14372. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  14373. * The HemisphericLight can't cast shadows.
  14374. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14375. */
  14376. function HemisphericLight(name, direction, scene) {
  14377. var _this = _super.call(this, name, scene) || this;
  14378. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  14379. _this.direction = direction;
  14380. return _this;
  14381. }
  14382. /**
  14383. * Returns the string "HemisphericLight".
  14384. */
  14385. HemisphericLight.prototype.getClassName = function () {
  14386. return "HemisphericLight";
  14387. };
  14388. /**
  14389. * Sets the HemisphericLight direction towards the passed target (Vector3).
  14390. * Returns the updated direction.
  14391. */
  14392. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  14393. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  14394. return this.direction;
  14395. };
  14396. HemisphericLight.prototype.getShadowGenerator = function () {
  14397. return null;
  14398. };
  14399. /**
  14400. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  14401. * Returns the HemisphericLight.
  14402. */
  14403. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  14404. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  14405. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0);
  14406. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  14407. return this;
  14408. };
  14409. HemisphericLight.prototype._getWorldMatrix = function () {
  14410. if (!this._worldMatrix) {
  14411. this._worldMatrix = BABYLON.Matrix.Identity();
  14412. }
  14413. return this._worldMatrix;
  14414. };
  14415. /**
  14416. * Returns the integer 3.
  14417. */
  14418. HemisphericLight.prototype.getTypeID = function () {
  14419. return 3;
  14420. };
  14421. return HemisphericLight;
  14422. }(BABYLON.Light));
  14423. __decorate([
  14424. BABYLON.serializeAsColor3()
  14425. ], HemisphericLight.prototype, "groundColor", void 0);
  14426. __decorate([
  14427. BABYLON.serializeAsVector3()
  14428. ], HemisphericLight.prototype, "direction", void 0);
  14429. BABYLON.HemisphericLight = HemisphericLight;
  14430. })(BABYLON || (BABYLON = {}));
  14431. //# sourceMappingURL=babylon.hemisphericLight.js.map
  14432. /// <reference path="babylon.light.ts" />
  14433. var BABYLON;
  14434. (function (BABYLON) {
  14435. var DirectionalLight = (function (_super) {
  14436. __extends(DirectionalLight, _super);
  14437. /**
  14438. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  14439. * The directional light is emitted from everywhere in the given direction.
  14440. * It can cast shawdows.
  14441. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14442. */
  14443. function DirectionalLight(name, direction, scene) {
  14444. var _this = _super.call(this, name, scene) || this;
  14445. _this.shadowOrthoScale = 0.5;
  14446. _this.autoUpdateExtends = true;
  14447. // Cache
  14448. _this._orthoLeft = Number.MAX_VALUE;
  14449. _this._orthoRight = Number.MIN_VALUE;
  14450. _this._orthoTop = Number.MIN_VALUE;
  14451. _this._orthoBottom = Number.MAX_VALUE;
  14452. _this.position = direction.scale(-1.0);
  14453. _this.direction = direction;
  14454. return _this;
  14455. }
  14456. /**
  14457. * Returns the string "DirectionalLight".
  14458. */
  14459. DirectionalLight.prototype.getClassName = function () {
  14460. return "DirectionalLight";
  14461. };
  14462. /**
  14463. * Returns the DirectionalLight absolute position in the World.
  14464. */
  14465. DirectionalLight.prototype.getAbsolutePosition = function () {
  14466. return this.transformedPosition ? this.transformedPosition : this.position;
  14467. };
  14468. /**
  14469. * Sets the DirectionalLight direction toward the passed target (Vector3).
  14470. * Returns the updated DirectionalLight direction (Vector3).
  14471. */
  14472. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  14473. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  14474. return this.direction;
  14475. };
  14476. /**
  14477. * Return the depth scale used for the shadow map.
  14478. */
  14479. DirectionalLight.prototype.getDepthScale = function () {
  14480. return 30.0;
  14481. };
  14482. /**
  14483. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  14484. * Returns the DirectionalLight.
  14485. */
  14486. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  14487. if (this.customProjectionMatrixBuilder) {
  14488. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  14489. }
  14490. else {
  14491. var activeCamera = this.getScene().activeCamera;
  14492. // Check extends
  14493. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  14494. var tempVector3 = BABYLON.Vector3.Zero();
  14495. this._orthoLeft = Number.MAX_VALUE;
  14496. this._orthoRight = Number.MIN_VALUE;
  14497. this._orthoTop = Number.MIN_VALUE;
  14498. this._orthoBottom = Number.MAX_VALUE;
  14499. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  14500. var mesh = renderList[meshIndex];
  14501. if (!mesh) {
  14502. continue;
  14503. }
  14504. var boundingInfo = mesh.getBoundingInfo();
  14505. if (!boundingInfo) {
  14506. continue;
  14507. }
  14508. var boundingBox = boundingInfo.boundingBox;
  14509. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  14510. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  14511. if (tempVector3.x < this._orthoLeft)
  14512. this._orthoLeft = tempVector3.x;
  14513. if (tempVector3.y < this._orthoBottom)
  14514. this._orthoBottom = tempVector3.y;
  14515. if (tempVector3.x > this._orthoRight)
  14516. this._orthoRight = tempVector3.x;
  14517. if (tempVector3.y > this._orthoTop)
  14518. this._orthoTop = tempVector3.y;
  14519. }
  14520. }
  14521. }
  14522. var xOffset = this._orthoRight - this._orthoLeft;
  14523. var yOffset = this._orthoTop - this._orthoBottom;
  14524. 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);
  14525. }
  14526. return this;
  14527. };
  14528. /**
  14529. * Boolean : true by default.
  14530. */
  14531. DirectionalLight.prototype.needRefreshPerFrame = function () {
  14532. return true;
  14533. };
  14534. /**
  14535. * Boolean : false by default.
  14536. */
  14537. DirectionalLight.prototype.needCube = function () {
  14538. return false;
  14539. };
  14540. /**
  14541. * Returns the light direction (Vector3) for any passed face index.
  14542. */
  14543. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  14544. return this.direction;
  14545. };
  14546. /**
  14547. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  14548. */
  14549. DirectionalLight.prototype.computeTransformedPosition = function () {
  14550. if (this.parent && this.parent.getWorldMatrix) {
  14551. if (!this.transformedPosition) {
  14552. this.transformedPosition = BABYLON.Vector3.Zero();
  14553. }
  14554. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  14555. return true;
  14556. }
  14557. return false;
  14558. };
  14559. /**
  14560. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  14561. * Returns the DirectionalLight.
  14562. */
  14563. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  14564. if (this.parent && this.parent.getWorldMatrix) {
  14565. if (!this._transformedDirection) {
  14566. this._transformedDirection = BABYLON.Vector3.Zero();
  14567. }
  14568. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  14569. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  14570. return this;
  14571. }
  14572. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  14573. return this;
  14574. };
  14575. DirectionalLight.prototype._getWorldMatrix = function () {
  14576. if (!this._worldMatrix) {
  14577. this._worldMatrix = BABYLON.Matrix.Identity();
  14578. }
  14579. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  14580. return this._worldMatrix;
  14581. };
  14582. /**
  14583. * Returns the integer 1.
  14584. */
  14585. DirectionalLight.prototype.getTypeID = function () {
  14586. return 1;
  14587. };
  14588. return DirectionalLight;
  14589. }(BABYLON.Light));
  14590. __decorate([
  14591. BABYLON.serializeAsVector3()
  14592. ], DirectionalLight.prototype, "position", void 0);
  14593. __decorate([
  14594. BABYLON.serializeAsVector3()
  14595. ], DirectionalLight.prototype, "direction", void 0);
  14596. __decorate([
  14597. BABYLON.serialize()
  14598. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  14599. __decorate([
  14600. BABYLON.serialize()
  14601. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  14602. __decorate([
  14603. BABYLON.serialize()
  14604. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  14605. __decorate([
  14606. BABYLON.serialize()
  14607. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  14608. BABYLON.DirectionalLight = DirectionalLight;
  14609. })(BABYLON || (BABYLON = {}));
  14610. //# sourceMappingURL=babylon.directionalLight.js.map
  14611. var BABYLON;
  14612. (function (BABYLON) {
  14613. var ShadowGenerator = (function () {
  14614. /**
  14615. * Creates a ShadowGenerator object.
  14616. * A ShadowGenerator is the required tool to use the shadows.
  14617. * Each light casting shadows needs to use its own ShadowGenerator.
  14618. * Required parameters :
  14619. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  14620. * - `light` : the light object generating the shadows.
  14621. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  14622. */
  14623. function ShadowGenerator(mapSize, light) {
  14624. var _this = this;
  14625. // Members
  14626. this._filter = ShadowGenerator.FILTER_NONE;
  14627. this.blurScale = 2;
  14628. this._blurBoxOffset = 0;
  14629. this._bias = 0.00005;
  14630. this._lightDirection = BABYLON.Vector3.Zero();
  14631. this.forceBackFacesOnly = false;
  14632. this._darkness = 0;
  14633. this._transparencyShadow = false;
  14634. this._viewMatrix = BABYLON.Matrix.Zero();
  14635. this._projectionMatrix = BABYLON.Matrix.Zero();
  14636. this._transformMatrix = BABYLON.Matrix.Zero();
  14637. this._worldViewProjection = BABYLON.Matrix.Zero();
  14638. this._currentFaceIndex = 0;
  14639. this._currentFaceIndexCache = 0;
  14640. this._useFullFloat = true;
  14641. this._light = light;
  14642. this._scene = light.getScene();
  14643. this._mapSize = mapSize;
  14644. light._shadowGenerator = this;
  14645. // Texture type fallback from float to int if not supported.
  14646. var textureType;
  14647. var caps = this._scene.getEngine().getCaps();
  14648. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  14649. this._useFullFloat = true;
  14650. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14651. }
  14652. else {
  14653. this._useFullFloat = false;
  14654. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14655. }
  14656. // Render target
  14657. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  14658. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14659. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14660. this._shadowMap.anisotropicFilteringLevel = 1;
  14661. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14662. this._shadowMap.renderParticles = false;
  14663. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  14664. _this._currentFaceIndex = faceIndex;
  14665. });
  14666. this._shadowMap.onAfterUnbindObservable.add(function () {
  14667. if (!_this.useBlurExponentialShadowMap) {
  14668. return;
  14669. }
  14670. if (!_this._shadowMap2) {
  14671. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  14672. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14673. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14674. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14675. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  14676. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  14677. effect.setTexture("textureSampler", _this._shadowMap);
  14678. });
  14679. _this.blurBoxOffset = 1;
  14680. }
  14681. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  14682. });
  14683. // Custom render function
  14684. var renderSubMesh = function (subMesh) {
  14685. var mesh = subMesh.getRenderingMesh();
  14686. var scene = _this._scene;
  14687. var engine = scene.getEngine();
  14688. // Culling
  14689. engine.setState(subMesh.getMaterial().backFaceCulling);
  14690. // Managing instances
  14691. var batch = mesh._getInstancesRenderList(subMesh._id);
  14692. if (batch.mustReturn) {
  14693. return;
  14694. }
  14695. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14696. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  14697. engine.enableEffect(_this._effect);
  14698. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  14699. var material = subMesh.getMaterial();
  14700. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  14701. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  14702. _this._effect.setVector3("lightPosition", _this.getLight().position);
  14703. if (_this.getLight().needCube()) {
  14704. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  14705. }
  14706. // Alpha test
  14707. if (material && material.needAlphaTesting()) {
  14708. var alphaTexture = material.getAlphaTestTexture();
  14709. _this._effect.setTexture("diffuseSampler", alphaTexture);
  14710. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  14711. }
  14712. // Bones
  14713. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14714. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  14715. }
  14716. if (_this.forceBackFacesOnly) {
  14717. engine.setState(true, 0, false, true);
  14718. }
  14719. // Draw
  14720. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  14721. if (_this.forceBackFacesOnly) {
  14722. engine.setState(true, 0, false, false);
  14723. }
  14724. }
  14725. else {
  14726. // Need to reset refresh rate of the shadowMap
  14727. _this._shadowMap.resetRefreshCounter();
  14728. }
  14729. };
  14730. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  14731. var index;
  14732. for (index = 0; index < opaqueSubMeshes.length; index++) {
  14733. renderSubMesh(opaqueSubMeshes.data[index]);
  14734. }
  14735. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  14736. renderSubMesh(alphaTestSubMeshes.data[index]);
  14737. }
  14738. if (_this._transparencyShadow) {
  14739. for (index = 0; index < transparentSubMeshes.length; index++) {
  14740. renderSubMesh(transparentSubMeshes.data[index]);
  14741. }
  14742. }
  14743. };
  14744. this._shadowMap.onClearObservable.add(function (engine) {
  14745. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  14746. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  14747. }
  14748. else {
  14749. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  14750. }
  14751. });
  14752. }
  14753. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  14754. // Static
  14755. get: function () {
  14756. return ShadowGenerator._FILTER_NONE;
  14757. },
  14758. enumerable: true,
  14759. configurable: true
  14760. });
  14761. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  14762. get: function () {
  14763. return ShadowGenerator._FILTER_POISSONSAMPLING;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  14769. get: function () {
  14770. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  14771. },
  14772. enumerable: true,
  14773. configurable: true
  14774. });
  14775. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  14776. get: function () {
  14777. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  14783. get: function () {
  14784. return this._bias;
  14785. },
  14786. set: function (bias) {
  14787. this._bias = bias;
  14788. },
  14789. enumerable: true,
  14790. configurable: true
  14791. });
  14792. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  14793. get: function () {
  14794. return this._blurBoxOffset;
  14795. },
  14796. set: function (value) {
  14797. var _this = this;
  14798. if (this._blurBoxOffset === value) {
  14799. return;
  14800. }
  14801. this._blurBoxOffset = value;
  14802. if (this._boxBlurPostprocess) {
  14803. this._boxBlurPostprocess.dispose();
  14804. }
  14805. var textureType;
  14806. var caps = this._scene.getEngine().getCaps();
  14807. if (this._useFullFloat) {
  14808. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  14809. }
  14810. else {
  14811. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  14812. }
  14813. 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);
  14814. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  14815. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  14816. });
  14817. },
  14818. enumerable: true,
  14819. configurable: true
  14820. });
  14821. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  14822. get: function () {
  14823. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  14824. },
  14825. set: function (value) {
  14826. this._depthScale = value;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  14832. get: function () {
  14833. return this._filter;
  14834. },
  14835. set: function (value) {
  14836. if (this._filter === value) {
  14837. return;
  14838. }
  14839. this._filter = value;
  14840. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  14841. this._shadowMap.anisotropicFilteringLevel = 16;
  14842. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  14843. }
  14844. else {
  14845. this._shadowMap.anisotropicFilteringLevel = 1;
  14846. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  14847. }
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  14853. get: function () {
  14854. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  14855. return this.useExponentialShadowMap;
  14856. },
  14857. set: function (value) {
  14858. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  14859. this.useExponentialShadowMap = value;
  14860. },
  14861. enumerable: true,
  14862. configurable: true
  14863. });
  14864. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  14865. get: function () {
  14866. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  14867. },
  14868. set: function (value) {
  14869. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  14870. },
  14871. enumerable: true,
  14872. configurable: true
  14873. });
  14874. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  14875. get: function () {
  14876. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  14877. },
  14878. set: function (value) {
  14879. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  14880. },
  14881. enumerable: true,
  14882. configurable: true
  14883. });
  14884. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  14885. get: function () {
  14886. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  14887. return this.useBlurExponentialShadowMap;
  14888. },
  14889. set: function (value) {
  14890. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  14891. this.useBlurExponentialShadowMap = value;
  14892. },
  14893. enumerable: true,
  14894. configurable: true
  14895. });
  14896. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  14897. get: function () {
  14898. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  14899. },
  14900. set: function (value) {
  14901. if (this._light.needCube() && value) {
  14902. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  14903. }
  14904. else {
  14905. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  14906. }
  14907. },
  14908. enumerable: true,
  14909. configurable: true
  14910. });
  14911. /**
  14912. * Boolean : true when the ShadowGenerator is finally computed.
  14913. */
  14914. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  14915. var defines = [];
  14916. if (this._useFullFloat) {
  14917. defines.push("#define FULLFLOAT");
  14918. }
  14919. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  14920. defines.push("#define ESM");
  14921. }
  14922. if (this.getLight().needCube()) {
  14923. defines.push("#define CUBEMAP");
  14924. }
  14925. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14926. var mesh = subMesh.getMesh();
  14927. var material = subMesh.getMaterial();
  14928. // Alpha test
  14929. if (material && material.needAlphaTesting()) {
  14930. defines.push("#define ALPHATEST");
  14931. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14932. attribs.push(BABYLON.VertexBuffer.UVKind);
  14933. defines.push("#define UV1");
  14934. }
  14935. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14936. var alphaTexture = material.getAlphaTestTexture();
  14937. if (alphaTexture.coordinatesIndex === 1) {
  14938. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14939. defines.push("#define UV2");
  14940. }
  14941. }
  14942. }
  14943. // Bones
  14944. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  14945. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14946. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14947. if (mesh.numBoneInfluencers > 4) {
  14948. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  14949. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  14950. }
  14951. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  14952. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14953. }
  14954. else {
  14955. defines.push("#define NUM_BONE_INFLUENCERS 0");
  14956. }
  14957. // Instances
  14958. if (useInstances) {
  14959. defines.push("#define INSTANCES");
  14960. attribs.push("world0");
  14961. attribs.push("world1");
  14962. attribs.push("world2");
  14963. attribs.push("world3");
  14964. }
  14965. // Get correct effect
  14966. var join = defines.join("\n");
  14967. if (this._cachedDefines !== join) {
  14968. this._cachedDefines = join;
  14969. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  14970. }
  14971. return this._effect.isReady();
  14972. };
  14973. /**
  14974. * Returns a RenderTargetTexture object : the shadow map texture.
  14975. */
  14976. ShadowGenerator.prototype.getShadowMap = function () {
  14977. return this._shadowMap;
  14978. };
  14979. /**
  14980. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  14981. */
  14982. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  14983. if (this._shadowMap2) {
  14984. return this._shadowMap2;
  14985. }
  14986. return this._shadowMap;
  14987. };
  14988. /**
  14989. * Returns the associated light object.
  14990. */
  14991. ShadowGenerator.prototype.getLight = function () {
  14992. return this._light;
  14993. };
  14994. // Methods
  14995. /**
  14996. * Returns a Matrix object : the updated transformation matrix.
  14997. */
  14998. ShadowGenerator.prototype.getTransformMatrix = function () {
  14999. var scene = this._scene;
  15000. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  15001. return this._transformMatrix;
  15002. }
  15003. this._currentRenderID = scene.getRenderId();
  15004. this._currentFaceIndexCache = this._currentFaceIndex;
  15005. var lightPosition = this._light.position;
  15006. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  15007. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  15008. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  15009. }
  15010. if (this._light.computeTransformedPosition()) {
  15011. lightPosition = this._light.transformedPosition;
  15012. }
  15013. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  15014. this._cachedPosition = lightPosition.clone();
  15015. this._cachedDirection = this._lightDirection.clone();
  15016. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  15017. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  15018. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15019. }
  15020. return this._transformMatrix;
  15021. };
  15022. /**
  15023. * Returns the darkness value (float).
  15024. */
  15025. ShadowGenerator.prototype.getDarkness = function () {
  15026. return this._darkness;
  15027. };
  15028. /**
  15029. * Sets the ShadowGenerator darkness value (float <= 1.0).
  15030. * Returns the ShadowGenerator.
  15031. */
  15032. ShadowGenerator.prototype.setDarkness = function (darkness) {
  15033. if (darkness >= 1.0)
  15034. this._darkness = 1.0;
  15035. else if (darkness <= 0.0)
  15036. this._darkness = 0.0;
  15037. else
  15038. this._darkness = darkness;
  15039. return this;
  15040. };
  15041. /**
  15042. * Sets the ability to have transparent shadow (boolean).
  15043. * Returns the ShadowGenerator.
  15044. */
  15045. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  15046. this._transparencyShadow = hasShadow;
  15047. return this;
  15048. };
  15049. ShadowGenerator.prototype._packHalf = function (depth) {
  15050. var scale = depth * 255.0;
  15051. var fract = scale - Math.floor(scale);
  15052. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  15053. };
  15054. /**
  15055. * Disposes the ShadowGenerator.
  15056. * Returns nothing.
  15057. */
  15058. ShadowGenerator.prototype.dispose = function () {
  15059. this._shadowMap.dispose();
  15060. if (this._shadowMap2) {
  15061. this._shadowMap2.dispose();
  15062. }
  15063. if (this._downSamplePostprocess) {
  15064. this._downSamplePostprocess.dispose();
  15065. }
  15066. if (this._boxBlurPostprocess) {
  15067. this._boxBlurPostprocess.dispose();
  15068. }
  15069. this._light._shadowGenerator = null;
  15070. };
  15071. /**
  15072. * Serializes the ShadowGenerator and returns a serializationObject.
  15073. */
  15074. ShadowGenerator.prototype.serialize = function () {
  15075. var serializationObject = {};
  15076. serializationObject.lightId = this._light.id;
  15077. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  15078. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  15079. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  15080. serializationObject.usePoissonSampling = this.usePoissonSampling;
  15081. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  15082. serializationObject.darkness = this.getDarkness();
  15083. serializationObject.renderList = [];
  15084. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  15085. var mesh = this.getShadowMap().renderList[meshIndex];
  15086. serializationObject.renderList.push(mesh.id);
  15087. }
  15088. return serializationObject;
  15089. };
  15090. /**
  15091. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  15092. */
  15093. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  15094. //casting to point light, as light is missing the position attr and typescript complains.
  15095. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  15096. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  15097. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  15098. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  15099. meshes.forEach(function (mesh) {
  15100. shadowGenerator.getShadowMap().renderList.push(mesh);
  15101. });
  15102. }
  15103. if (parsedShadowGenerator.usePoissonSampling) {
  15104. shadowGenerator.usePoissonSampling = true;
  15105. }
  15106. else if (parsedShadowGenerator.useExponentialShadowMap) {
  15107. shadowGenerator.useExponentialShadowMap = true;
  15108. }
  15109. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  15110. shadowGenerator.useBlurExponentialShadowMap = true;
  15111. }
  15112. else if (parsedShadowGenerator.useVarianceShadowMap) {
  15113. shadowGenerator.useExponentialShadowMap = true;
  15114. }
  15115. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  15116. shadowGenerator.useBlurExponentialShadowMap = true;
  15117. }
  15118. if (parsedShadowGenerator.blurScale) {
  15119. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  15120. }
  15121. if (parsedShadowGenerator.blurBoxOffset) {
  15122. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  15123. }
  15124. if (parsedShadowGenerator.bias !== undefined) {
  15125. shadowGenerator.bias = parsedShadowGenerator.bias;
  15126. }
  15127. if (parsedShadowGenerator.darkness) {
  15128. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  15129. }
  15130. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  15131. return shadowGenerator;
  15132. };
  15133. return ShadowGenerator;
  15134. }());
  15135. ShadowGenerator._FILTER_NONE = 0;
  15136. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  15137. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  15138. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  15139. BABYLON.ShadowGenerator = ShadowGenerator;
  15140. })(BABYLON || (BABYLON = {}));
  15141. //# sourceMappingURL=babylon.shadowGenerator.js.map
  15142. var BABYLON;
  15143. (function (BABYLON) {
  15144. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  15145. if (boxMin.x > sphereCenter.x + sphereRadius)
  15146. return false;
  15147. if (sphereCenter.x - sphereRadius > boxMax.x)
  15148. return false;
  15149. if (boxMin.y > sphereCenter.y + sphereRadius)
  15150. return false;
  15151. if (sphereCenter.y - sphereRadius > boxMax.y)
  15152. return false;
  15153. if (boxMin.z > sphereCenter.z + sphereRadius)
  15154. return false;
  15155. if (sphereCenter.z - sphereRadius > boxMax.z)
  15156. return false;
  15157. return true;
  15158. };
  15159. var getLowestRoot = (function () {
  15160. var result = { root: 0, found: false };
  15161. return function (a, b, c, maxR) {
  15162. result.root = 0;
  15163. result.found = false;
  15164. var determinant = b * b - 4.0 * a * c;
  15165. if (determinant < 0)
  15166. return result;
  15167. var sqrtD = Math.sqrt(determinant);
  15168. var r1 = (-b - sqrtD) / (2.0 * a);
  15169. var r2 = (-b + sqrtD) / (2.0 * a);
  15170. if (r1 > r2) {
  15171. var temp = r2;
  15172. r2 = r1;
  15173. r1 = temp;
  15174. }
  15175. if (r1 > 0 && r1 < maxR) {
  15176. result.root = r1;
  15177. result.found = true;
  15178. return result;
  15179. }
  15180. if (r2 > 0 && r2 < maxR) {
  15181. result.root = r2;
  15182. result.found = true;
  15183. return result;
  15184. }
  15185. return result;
  15186. };
  15187. })();
  15188. var Collider = (function () {
  15189. function Collider() {
  15190. this.radius = new BABYLON.Vector3(1, 1, 1);
  15191. this.retry = 0;
  15192. this.basePointWorld = BABYLON.Vector3.Zero();
  15193. this.velocityWorld = BABYLON.Vector3.Zero();
  15194. this.normalizedVelocity = BABYLON.Vector3.Zero();
  15195. this._collisionPoint = BABYLON.Vector3.Zero();
  15196. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  15197. this._tempVector = BABYLON.Vector3.Zero();
  15198. this._tempVector2 = BABYLON.Vector3.Zero();
  15199. this._tempVector3 = BABYLON.Vector3.Zero();
  15200. this._tempVector4 = BABYLON.Vector3.Zero();
  15201. this._edge = BABYLON.Vector3.Zero();
  15202. this._baseToVertex = BABYLON.Vector3.Zero();
  15203. this._destinationPoint = BABYLON.Vector3.Zero();
  15204. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  15205. this._displacementVector = BABYLON.Vector3.Zero();
  15206. this._collisionMask = -1;
  15207. }
  15208. Object.defineProperty(Collider.prototype, "collisionMask", {
  15209. get: function () {
  15210. return this._collisionMask;
  15211. },
  15212. set: function (mask) {
  15213. this._collisionMask = !isNaN(mask) ? mask : -1;
  15214. },
  15215. enumerable: true,
  15216. configurable: true
  15217. });
  15218. // Methods
  15219. Collider.prototype._initialize = function (source, dir, e) {
  15220. this.velocity = dir;
  15221. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  15222. this.basePoint = source;
  15223. source.multiplyToRef(this.radius, this.basePointWorld);
  15224. dir.multiplyToRef(this.radius, this.velocityWorld);
  15225. this.velocityWorldLength = this.velocityWorld.length();
  15226. this.epsilon = e;
  15227. this.collisionFound = false;
  15228. };
  15229. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  15230. pa.subtractToRef(point, this._tempVector);
  15231. pb.subtractToRef(point, this._tempVector2);
  15232. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  15233. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15234. if (d < 0)
  15235. return false;
  15236. pc.subtractToRef(point, this._tempVector3);
  15237. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  15238. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15239. if (d < 0)
  15240. return false;
  15241. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  15242. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  15243. return d >= 0;
  15244. };
  15245. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  15246. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  15247. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  15248. if (distance > this.velocityWorldLength + max + sphereRadius) {
  15249. return false;
  15250. }
  15251. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  15252. return false;
  15253. return true;
  15254. };
  15255. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  15256. var t0;
  15257. var embeddedInPlane = false;
  15258. //defensive programming, actually not needed.
  15259. if (!trianglePlaneArray) {
  15260. trianglePlaneArray = [];
  15261. }
  15262. if (!trianglePlaneArray[faceIndex]) {
  15263. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  15264. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  15265. }
  15266. var trianglePlane = trianglePlaneArray[faceIndex];
  15267. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  15268. return;
  15269. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  15270. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  15271. if (normalDotVelocity == 0) {
  15272. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  15273. return;
  15274. embeddedInPlane = true;
  15275. t0 = 0;
  15276. }
  15277. else {
  15278. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15279. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  15280. if (t0 > t1) {
  15281. var temp = t1;
  15282. t1 = t0;
  15283. t0 = temp;
  15284. }
  15285. if (t0 > 1.0 || t1 < 0.0)
  15286. return;
  15287. if (t0 < 0)
  15288. t0 = 0;
  15289. if (t0 > 1.0)
  15290. t0 = 1.0;
  15291. }
  15292. this._collisionPoint.copyFromFloats(0, 0, 0);
  15293. var found = false;
  15294. var t = 1.0;
  15295. if (!embeddedInPlane) {
  15296. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  15297. this.velocity.scaleToRef(t0, this._tempVector);
  15298. this._planeIntersectionPoint.addInPlace(this._tempVector);
  15299. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  15300. found = true;
  15301. t = t0;
  15302. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  15303. }
  15304. }
  15305. if (!found) {
  15306. var velocitySquaredLength = this.velocity.lengthSquared();
  15307. var a = velocitySquaredLength;
  15308. this.basePoint.subtractToRef(p1, this._tempVector);
  15309. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15310. var c = this._tempVector.lengthSquared() - 1.0;
  15311. var lowestRoot = getLowestRoot(a, b, c, t);
  15312. if (lowestRoot.found) {
  15313. t = lowestRoot.root;
  15314. found = true;
  15315. this._collisionPoint.copyFrom(p1);
  15316. }
  15317. this.basePoint.subtractToRef(p2, this._tempVector);
  15318. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15319. c = this._tempVector.lengthSquared() - 1.0;
  15320. lowestRoot = getLowestRoot(a, b, c, t);
  15321. if (lowestRoot.found) {
  15322. t = lowestRoot.root;
  15323. found = true;
  15324. this._collisionPoint.copyFrom(p2);
  15325. }
  15326. this.basePoint.subtractToRef(p3, this._tempVector);
  15327. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  15328. c = this._tempVector.lengthSquared() - 1.0;
  15329. lowestRoot = getLowestRoot(a, b, c, t);
  15330. if (lowestRoot.found) {
  15331. t = lowestRoot.root;
  15332. found = true;
  15333. this._collisionPoint.copyFrom(p3);
  15334. }
  15335. p2.subtractToRef(p1, this._edge);
  15336. p1.subtractToRef(this.basePoint, this._baseToVertex);
  15337. var edgeSquaredLength = this._edge.lengthSquared();
  15338. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15339. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15340. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15341. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15342. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15343. lowestRoot = getLowestRoot(a, b, c, t);
  15344. if (lowestRoot.found) {
  15345. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15346. if (f >= 0.0 && f <= 1.0) {
  15347. t = lowestRoot.root;
  15348. found = true;
  15349. this._edge.scaleInPlace(f);
  15350. p1.addToRef(this._edge, this._collisionPoint);
  15351. }
  15352. }
  15353. p3.subtractToRef(p2, this._edge);
  15354. p2.subtractToRef(this.basePoint, this._baseToVertex);
  15355. edgeSquaredLength = this._edge.lengthSquared();
  15356. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15357. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15358. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15359. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15360. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15361. lowestRoot = getLowestRoot(a, b, c, t);
  15362. if (lowestRoot.found) {
  15363. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15364. if (f >= 0.0 && f <= 1.0) {
  15365. t = lowestRoot.root;
  15366. found = true;
  15367. this._edge.scaleInPlace(f);
  15368. p2.addToRef(this._edge, this._collisionPoint);
  15369. }
  15370. }
  15371. p1.subtractToRef(p3, this._edge);
  15372. p3.subtractToRef(this.basePoint, this._baseToVertex);
  15373. edgeSquaredLength = this._edge.lengthSquared();
  15374. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  15375. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  15376. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  15377. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  15378. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  15379. lowestRoot = getLowestRoot(a, b, c, t);
  15380. if (lowestRoot.found) {
  15381. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  15382. if (f >= 0.0 && f <= 1.0) {
  15383. t = lowestRoot.root;
  15384. found = true;
  15385. this._edge.scaleInPlace(f);
  15386. p3.addToRef(this._edge, this._collisionPoint);
  15387. }
  15388. }
  15389. }
  15390. if (found) {
  15391. var distToCollision = t * this.velocity.length();
  15392. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  15393. if (!this.intersectionPoint) {
  15394. this.intersectionPoint = this._collisionPoint.clone();
  15395. }
  15396. else {
  15397. this.intersectionPoint.copyFrom(this._collisionPoint);
  15398. }
  15399. this.nearestDistance = distToCollision;
  15400. this.collisionFound = true;
  15401. }
  15402. }
  15403. };
  15404. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  15405. for (var i = indexStart; i < indexEnd; i += 3) {
  15406. var p1 = pts[indices[i] - decal];
  15407. var p2 = pts[indices[i + 1] - decal];
  15408. var p3 = pts[indices[i + 2] - decal];
  15409. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  15410. }
  15411. };
  15412. Collider.prototype._getResponse = function (pos, vel) {
  15413. pos.addToRef(vel, this._destinationPoint);
  15414. vel.scaleInPlace((this.nearestDistance / vel.length()));
  15415. this.basePoint.addToRef(vel, pos);
  15416. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  15417. this._slidePlaneNormal.normalize();
  15418. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  15419. pos.addInPlace(this._displacementVector);
  15420. this.intersectionPoint.addInPlace(this._displacementVector);
  15421. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  15422. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  15423. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  15424. };
  15425. return Collider;
  15426. }());
  15427. BABYLON.Collider = Collider;
  15428. })(BABYLON || (BABYLON = {}));
  15429. //# sourceMappingURL=babylon.collider.js.map
  15430. var BABYLON;
  15431. (function (BABYLON) {
  15432. //WebWorker code will be inserted to this variable.
  15433. BABYLON.CollisionWorker = "";
  15434. var WorkerTaskType;
  15435. (function (WorkerTaskType) {
  15436. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  15437. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  15438. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  15439. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  15440. var WorkerReplyType;
  15441. (function (WorkerReplyType) {
  15442. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  15443. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  15444. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  15445. var CollisionCoordinatorWorker = (function () {
  15446. function CollisionCoordinatorWorker() {
  15447. var _this = this;
  15448. this._scaledPosition = BABYLON.Vector3.Zero();
  15449. this._scaledVelocity = BABYLON.Vector3.Zero();
  15450. this.onMeshUpdated = function (mesh) {
  15451. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  15452. };
  15453. this.onGeometryUpdated = function (geometry) {
  15454. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  15455. };
  15456. this._afterRender = function () {
  15457. if (!_this._init)
  15458. return;
  15459. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  15460. return;
  15461. }
  15462. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  15463. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  15464. if (_this._runningUpdated > 4) {
  15465. return;
  15466. }
  15467. ++_this._runningUpdated;
  15468. var payload = {
  15469. updatedMeshes: _this._addUpdateMeshesList,
  15470. updatedGeometries: _this._addUpdateGeometriesList,
  15471. removedGeometries: _this._toRemoveGeometryArray,
  15472. removedMeshes: _this._toRemoveMeshesArray
  15473. };
  15474. var message = {
  15475. payload: payload,
  15476. taskType: WorkerTaskType.UPDATE
  15477. };
  15478. var serializable = [];
  15479. for (var id in payload.updatedGeometries) {
  15480. if (payload.updatedGeometries.hasOwnProperty(id)) {
  15481. //prepare transferables
  15482. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  15483. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  15484. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  15485. }
  15486. }
  15487. _this._worker.postMessage(message, serializable);
  15488. _this._addUpdateMeshesList = {};
  15489. _this._addUpdateGeometriesList = {};
  15490. _this._toRemoveGeometryArray = [];
  15491. _this._toRemoveMeshesArray = [];
  15492. };
  15493. this._onMessageFromWorker = function (e) {
  15494. var returnData = e.data;
  15495. if (returnData.error != WorkerReplyType.SUCCESS) {
  15496. //TODO what errors can be returned from the worker?
  15497. BABYLON.Tools.Warn("error returned from worker!");
  15498. return;
  15499. }
  15500. switch (returnData.taskType) {
  15501. case WorkerTaskType.INIT:
  15502. _this._init = true;
  15503. //Update the worked with ALL of the scene's current state
  15504. _this._scene.meshes.forEach(function (mesh) {
  15505. _this.onMeshAdded(mesh);
  15506. });
  15507. _this._scene.getGeometries().forEach(function (geometry) {
  15508. _this.onGeometryAdded(geometry);
  15509. });
  15510. break;
  15511. case WorkerTaskType.UPDATE:
  15512. _this._runningUpdated--;
  15513. break;
  15514. case WorkerTaskType.COLLIDE:
  15515. _this._runningCollisionTask = false;
  15516. var returnPayload = returnData.payload;
  15517. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  15518. return;
  15519. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  15520. //cleanup
  15521. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  15522. break;
  15523. }
  15524. };
  15525. this._collisionsCallbackArray = [];
  15526. this._init = false;
  15527. this._runningUpdated = 0;
  15528. this._runningCollisionTask = false;
  15529. this._addUpdateMeshesList = {};
  15530. this._addUpdateGeometriesList = {};
  15531. this._toRemoveGeometryArray = [];
  15532. this._toRemoveMeshesArray = [];
  15533. }
  15534. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15535. if (!this._init)
  15536. return;
  15537. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  15538. return;
  15539. position.divideToRef(collider.radius, this._scaledPosition);
  15540. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15541. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  15542. var payload = {
  15543. collider: {
  15544. position: this._scaledPosition.asArray(),
  15545. velocity: this._scaledVelocity.asArray(),
  15546. radius: collider.radius.asArray()
  15547. },
  15548. collisionId: collisionIndex,
  15549. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  15550. maximumRetry: maximumRetry
  15551. };
  15552. var message = {
  15553. payload: payload,
  15554. taskType: WorkerTaskType.COLLIDE
  15555. };
  15556. this._worker.postMessage(message);
  15557. };
  15558. CollisionCoordinatorWorker.prototype.init = function (scene) {
  15559. this._scene = scene;
  15560. this._scene.registerAfterRender(this._afterRender);
  15561. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  15562. this._worker = new Worker(workerUrl);
  15563. this._worker.onmessage = this._onMessageFromWorker;
  15564. var message = {
  15565. payload: {},
  15566. taskType: WorkerTaskType.INIT
  15567. };
  15568. this._worker.postMessage(message);
  15569. };
  15570. CollisionCoordinatorWorker.prototype.destroy = function () {
  15571. this._scene.unregisterAfterRender(this._afterRender);
  15572. this._worker.terminate();
  15573. };
  15574. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  15575. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  15576. this.onMeshUpdated(mesh);
  15577. };
  15578. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  15579. this._toRemoveMeshesArray.push(mesh.uniqueId);
  15580. };
  15581. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  15582. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  15583. geometry.onGeometryUpdated = this.onGeometryUpdated;
  15584. this.onGeometryUpdated(geometry);
  15585. };
  15586. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  15587. this._toRemoveGeometryArray.push(geometry.id);
  15588. };
  15589. return CollisionCoordinatorWorker;
  15590. }());
  15591. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  15592. var submeshes = [];
  15593. if (mesh.subMeshes) {
  15594. submeshes = mesh.subMeshes.map(function (sm, idx) {
  15595. return {
  15596. position: idx,
  15597. verticesStart: sm.verticesStart,
  15598. verticesCount: sm.verticesCount,
  15599. indexStart: sm.indexStart,
  15600. indexCount: sm.indexCount,
  15601. hasMaterial: !!sm.getMaterial(),
  15602. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15603. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  15604. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15605. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  15606. };
  15607. });
  15608. }
  15609. var geometryId = null;
  15610. if (mesh instanceof BABYLON.Mesh) {
  15611. geometryId = mesh.geometry ? mesh.geometry.id : null;
  15612. }
  15613. else if (mesh instanceof BABYLON.InstancedMesh) {
  15614. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  15615. }
  15616. return {
  15617. uniqueId: mesh.uniqueId,
  15618. id: mesh.id,
  15619. name: mesh.name,
  15620. geometryId: geometryId,
  15621. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  15622. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  15623. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  15624. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  15625. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  15626. subMeshes: submeshes,
  15627. checkCollisions: mesh.checkCollisions
  15628. };
  15629. };
  15630. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  15631. return {
  15632. id: geometry.id,
  15633. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  15634. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  15635. indices: new Uint32Array(geometry.getIndices() || []),
  15636. };
  15637. };
  15638. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  15639. var CollisionCoordinatorLegacy = (function () {
  15640. function CollisionCoordinatorLegacy() {
  15641. this._scaledPosition = BABYLON.Vector3.Zero();
  15642. this._scaledVelocity = BABYLON.Vector3.Zero();
  15643. this._finalPosition = BABYLON.Vector3.Zero();
  15644. }
  15645. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  15646. position.divideToRef(collider.radius, this._scaledPosition);
  15647. velocity.divideToRef(collider.radius, this._scaledVelocity);
  15648. collider.collidedMesh = null;
  15649. collider.retry = 0;
  15650. collider.initialVelocity = this._scaledVelocity;
  15651. collider.initialPosition = this._scaledPosition;
  15652. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  15653. this._finalPosition.multiplyInPlace(collider.radius);
  15654. //run the callback
  15655. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  15656. };
  15657. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  15658. this._scene = scene;
  15659. };
  15660. CollisionCoordinatorLegacy.prototype.destroy = function () {
  15661. //Legacy need no destruction method.
  15662. };
  15663. //No update in legacy mode
  15664. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  15665. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  15666. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  15667. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  15668. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  15669. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  15670. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  15671. if (excludedMesh === void 0) { excludedMesh = null; }
  15672. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  15673. if (collider.retry >= maximumRetry) {
  15674. finalPosition.copyFrom(position);
  15675. return;
  15676. }
  15677. // Check if this is a mesh else camera or -1
  15678. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  15679. collider._initialize(position, velocity, closeDistance);
  15680. // Check all meshes
  15681. for (var index = 0; index < this._scene.meshes.length; index++) {
  15682. var mesh = this._scene.meshes[index];
  15683. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  15684. mesh._checkCollision(collider);
  15685. }
  15686. }
  15687. if (!collider.collisionFound) {
  15688. position.addToRef(velocity, finalPosition);
  15689. return;
  15690. }
  15691. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  15692. collider._getResponse(position, velocity);
  15693. }
  15694. if (velocity.length() <= closeDistance) {
  15695. finalPosition.copyFrom(position);
  15696. return;
  15697. }
  15698. collider.retry++;
  15699. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  15700. };
  15701. return CollisionCoordinatorLegacy;
  15702. }());
  15703. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  15704. })(BABYLON || (BABYLON = {}));
  15705. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  15706. var BABYLON;
  15707. (function (BABYLON) {
  15708. var Camera = (function (_super) {
  15709. __extends(Camera, _super);
  15710. function Camera(name, position, scene) {
  15711. var _this = _super.call(this, name, scene) || this;
  15712. _this.upVector = BABYLON.Vector3.Up();
  15713. _this.orthoLeft = null;
  15714. _this.orthoRight = null;
  15715. _this.orthoBottom = null;
  15716. _this.orthoTop = null;
  15717. _this.fov = 0.8;
  15718. _this.minZ = 1.0;
  15719. _this.maxZ = 10000.0;
  15720. _this.inertia = 0.9;
  15721. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15722. _this.isIntermediate = false;
  15723. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15724. _this.layerMask = 0x0FFFFFFF;
  15725. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15726. // Camera rig members
  15727. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15728. _this._rigCameras = new Array();
  15729. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15730. // Cache
  15731. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15732. _this._projectionMatrix = new BABYLON.Matrix();
  15733. _this._doNotComputeProjectionMatrix = false;
  15734. _this._postProcesses = new Array();
  15735. _this._transformMatrix = BABYLON.Matrix.Zero();
  15736. _this._activeMeshes = new BABYLON.SmartArray(256);
  15737. _this._globalPosition = BABYLON.Vector3.Zero();
  15738. _this._refreshFrustumPlanes = true;
  15739. _this.getScene().addCamera(_this);
  15740. if (!_this.getScene().activeCamera) {
  15741. _this.getScene().activeCamera = _this;
  15742. }
  15743. _this.position = position;
  15744. return _this;
  15745. }
  15746. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15747. get: function () {
  15748. return Camera._PERSPECTIVE_CAMERA;
  15749. },
  15750. enumerable: true,
  15751. configurable: true
  15752. });
  15753. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15754. get: function () {
  15755. return Camera._ORTHOGRAPHIC_CAMERA;
  15756. },
  15757. enumerable: true,
  15758. configurable: true
  15759. });
  15760. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15761. get: function () {
  15762. return Camera._FOVMODE_VERTICAL_FIXED;
  15763. },
  15764. enumerable: true,
  15765. configurable: true
  15766. });
  15767. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15768. get: function () {
  15769. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15770. },
  15771. enumerable: true,
  15772. configurable: true
  15773. });
  15774. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15775. get: function () {
  15776. return Camera._RIG_MODE_NONE;
  15777. },
  15778. enumerable: true,
  15779. configurable: true
  15780. });
  15781. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15782. get: function () {
  15783. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15784. },
  15785. enumerable: true,
  15786. configurable: true
  15787. });
  15788. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15789. get: function () {
  15790. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15791. },
  15792. enumerable: true,
  15793. configurable: true
  15794. });
  15795. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15796. get: function () {
  15797. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15798. },
  15799. enumerable: true,
  15800. configurable: true
  15801. });
  15802. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15803. get: function () {
  15804. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15805. },
  15806. enumerable: true,
  15807. configurable: true
  15808. });
  15809. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15810. get: function () {
  15811. return Camera._RIG_MODE_VR;
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15817. get: function () {
  15818. return Camera._RIG_MODE_WEBVR;
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. Camera.prototype.getClassName = function () {
  15824. return "Camera";
  15825. };
  15826. /**
  15827. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15828. */
  15829. Camera.prototype.toString = function (fullDetails) {
  15830. var ret = "Name: " + this.name;
  15831. ret += ", type: " + this.getClassName();
  15832. if (this.animations) {
  15833. for (var i = 0; i < this.animations.length; i++) {
  15834. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15835. }
  15836. }
  15837. if (fullDetails) {
  15838. }
  15839. return ret;
  15840. };
  15841. Object.defineProperty(Camera.prototype, "globalPosition", {
  15842. get: function () {
  15843. return this._globalPosition;
  15844. },
  15845. enumerable: true,
  15846. configurable: true
  15847. });
  15848. Camera.prototype.getActiveMeshes = function () {
  15849. return this._activeMeshes;
  15850. };
  15851. Camera.prototype.isActiveMesh = function (mesh) {
  15852. return (this._activeMeshes.indexOf(mesh) !== -1);
  15853. };
  15854. //Cache
  15855. Camera.prototype._initCache = function () {
  15856. _super.prototype._initCache.call(this);
  15857. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15858. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15859. this._cache.mode = undefined;
  15860. this._cache.minZ = undefined;
  15861. this._cache.maxZ = undefined;
  15862. this._cache.fov = undefined;
  15863. this._cache.fovMode = undefined;
  15864. this._cache.aspectRatio = undefined;
  15865. this._cache.orthoLeft = undefined;
  15866. this._cache.orthoRight = undefined;
  15867. this._cache.orthoBottom = undefined;
  15868. this._cache.orthoTop = undefined;
  15869. this._cache.renderWidth = undefined;
  15870. this._cache.renderHeight = undefined;
  15871. };
  15872. Camera.prototype._updateCache = function (ignoreParentClass) {
  15873. if (!ignoreParentClass) {
  15874. _super.prototype._updateCache.call(this);
  15875. }
  15876. var engine = this.getEngine();
  15877. this._cache.position.copyFrom(this.position);
  15878. this._cache.upVector.copyFrom(this.upVector);
  15879. this._cache.mode = this.mode;
  15880. this._cache.minZ = this.minZ;
  15881. this._cache.maxZ = this.maxZ;
  15882. this._cache.fov = this.fov;
  15883. this._cache.fovMode = this.fovMode;
  15884. this._cache.aspectRatio = engine.getAspectRatio(this);
  15885. this._cache.orthoLeft = this.orthoLeft;
  15886. this._cache.orthoRight = this.orthoRight;
  15887. this._cache.orthoBottom = this.orthoBottom;
  15888. this._cache.orthoTop = this.orthoTop;
  15889. this._cache.renderWidth = engine.getRenderWidth();
  15890. this._cache.renderHeight = engine.getRenderHeight();
  15891. };
  15892. Camera.prototype._updateFromScene = function () {
  15893. this.updateCache();
  15894. this.update();
  15895. };
  15896. // Synchronized
  15897. Camera.prototype._isSynchronized = function () {
  15898. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  15899. };
  15900. Camera.prototype._isSynchronizedViewMatrix = function () {
  15901. if (!_super.prototype._isSynchronized.call(this))
  15902. return false;
  15903. return this._cache.position.equals(this.position)
  15904. && this._cache.upVector.equals(this.upVector)
  15905. && this.isSynchronizedWithParent();
  15906. };
  15907. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  15908. var check = this._cache.mode === this.mode
  15909. && this._cache.minZ === this.minZ
  15910. && this._cache.maxZ === this.maxZ;
  15911. if (!check) {
  15912. return false;
  15913. }
  15914. var engine = this.getEngine();
  15915. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15916. check = this._cache.fov === this.fov
  15917. && this._cache.fovMode === this.fovMode
  15918. && this._cache.aspectRatio === engine.getAspectRatio(this);
  15919. }
  15920. else {
  15921. check = this._cache.orthoLeft === this.orthoLeft
  15922. && this._cache.orthoRight === this.orthoRight
  15923. && this._cache.orthoBottom === this.orthoBottom
  15924. && this._cache.orthoTop === this.orthoTop
  15925. && this._cache.renderWidth === engine.getRenderWidth()
  15926. && this._cache.renderHeight === engine.getRenderHeight();
  15927. }
  15928. return check;
  15929. };
  15930. // Controls
  15931. Camera.prototype.attachControl = function (element, noPreventDefault) {
  15932. };
  15933. Camera.prototype.detachControl = function (element) {
  15934. };
  15935. Camera.prototype.update = function () {
  15936. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15937. this._updateRigCameras();
  15938. }
  15939. this._checkInputs();
  15940. };
  15941. Camera.prototype._checkInputs = function () {
  15942. };
  15943. Object.defineProperty(Camera.prototype, "rigCameras", {
  15944. get: function () {
  15945. return this._rigCameras;
  15946. },
  15947. enumerable: true,
  15948. configurable: true
  15949. });
  15950. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  15951. get: function () {
  15952. return this._rigPostProcess;
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Camera.prototype._cascadePostProcessesToRigCams = function () {
  15958. // invalidate framebuffer
  15959. if (this._postProcesses.length > 0) {
  15960. this._postProcesses[0].markTextureDirty();
  15961. }
  15962. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  15963. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  15964. var cam = this._rigCameras[i];
  15965. var rigPostProcess = cam._rigPostProcess;
  15966. // for VR rig, there does not have to be a post process
  15967. if (rigPostProcess) {
  15968. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  15969. if (isPass) {
  15970. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  15971. cam.isIntermediate = this._postProcesses.length === 0;
  15972. }
  15973. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  15974. rigPostProcess.markTextureDirty();
  15975. }
  15976. else {
  15977. cam._postProcesses = this._postProcesses.slice(0);
  15978. }
  15979. }
  15980. };
  15981. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15982. if (insertAt === void 0) { insertAt = null; }
  15983. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15984. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15985. return 0;
  15986. }
  15987. if (insertAt == null || insertAt < 0) {
  15988. this._postProcesses.push(postProcess);
  15989. }
  15990. else {
  15991. this._postProcesses.splice(insertAt, 0, postProcess);
  15992. }
  15993. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15994. return this._postProcesses.indexOf(postProcess);
  15995. };
  15996. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15997. if (atIndices === void 0) { atIndices = null; }
  15998. var result = [];
  15999. var i;
  16000. var index;
  16001. if (!atIndices) {
  16002. var idx = this._postProcesses.indexOf(postProcess);
  16003. if (idx !== -1) {
  16004. this._postProcesses.splice(idx, 1);
  16005. }
  16006. }
  16007. else {
  16008. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  16009. // iterate descending, so can just splice as we go
  16010. for (i = atIndices.length - 1; i >= 0; i--) {
  16011. if (this._postProcesses[atIndices[i]] !== postProcess) {
  16012. result.push(i);
  16013. continue;
  16014. }
  16015. index = atIndices[i];
  16016. this._postProcesses.splice(index, 1);
  16017. }
  16018. }
  16019. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16020. return result;
  16021. };
  16022. Camera.prototype.getWorldMatrix = function () {
  16023. if (!this._worldMatrix) {
  16024. this._worldMatrix = BABYLON.Matrix.Identity();
  16025. }
  16026. var viewMatrix = this.getViewMatrix();
  16027. viewMatrix.invertToRef(this._worldMatrix);
  16028. return this._worldMatrix;
  16029. };
  16030. Camera.prototype._getViewMatrix = function () {
  16031. return BABYLON.Matrix.Identity();
  16032. };
  16033. Camera.prototype.getViewMatrix = function (force) {
  16034. this._computedViewMatrix = this._computeViewMatrix(force);
  16035. if (!force && this._isSynchronizedViewMatrix()) {
  16036. return this._computedViewMatrix;
  16037. }
  16038. this._refreshFrustumPlanes = true;
  16039. if (!this.parent || !this.parent.getWorldMatrix) {
  16040. this._globalPosition.copyFrom(this.position);
  16041. }
  16042. else {
  16043. if (!this._worldMatrix) {
  16044. this._worldMatrix = BABYLON.Matrix.Identity();
  16045. }
  16046. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16047. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16048. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16049. this._computedViewMatrix.invert();
  16050. this._markSyncedWithParent();
  16051. }
  16052. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16053. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16054. }
  16055. this._currentRenderId = this.getScene().getRenderId();
  16056. return this._computedViewMatrix;
  16057. };
  16058. Camera.prototype._computeViewMatrix = function (force) {
  16059. if (!force && this._isSynchronizedViewMatrix()) {
  16060. return this._computedViewMatrix;
  16061. }
  16062. this._computedViewMatrix = this._getViewMatrix();
  16063. this._currentRenderId = this.getScene().getRenderId();
  16064. return this._computedViewMatrix;
  16065. };
  16066. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16067. this._doNotComputeProjectionMatrix = true;
  16068. if (projection !== undefined) {
  16069. this._projectionMatrix = projection;
  16070. }
  16071. };
  16072. ;
  16073. Camera.prototype.unfreezeProjectionMatrix = function () {
  16074. this._doNotComputeProjectionMatrix = false;
  16075. };
  16076. ;
  16077. Camera.prototype.getProjectionMatrix = function (force) {
  16078. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16079. return this._projectionMatrix;
  16080. }
  16081. this._refreshFrustumPlanes = true;
  16082. var engine = this.getEngine();
  16083. var scene = this.getScene();
  16084. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16085. if (this.minZ <= 0) {
  16086. this.minZ = 0.1;
  16087. }
  16088. if (scene.useRightHandedSystem) {
  16089. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16090. }
  16091. else {
  16092. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16093. }
  16094. return this._projectionMatrix;
  16095. }
  16096. var halfWidth = engine.getRenderWidth() / 2.0;
  16097. var halfHeight = engine.getRenderHeight() / 2.0;
  16098. if (scene.useRightHandedSystem) {
  16099. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16100. }
  16101. else {
  16102. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16103. }
  16104. return this._projectionMatrix;
  16105. };
  16106. Camera.prototype.getTranformationMatrix = function () {
  16107. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16108. return this._transformMatrix;
  16109. };
  16110. Camera.prototype.updateFrustumPlanes = function () {
  16111. if (!this._refreshFrustumPlanes) {
  16112. return;
  16113. }
  16114. this.getTranformationMatrix();
  16115. if (!this._frustumPlanes) {
  16116. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16117. }
  16118. else {
  16119. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16120. }
  16121. this._refreshFrustumPlanes = false;
  16122. };
  16123. Camera.prototype.isInFrustum = function (target) {
  16124. this.updateFrustumPlanes();
  16125. return target.isInFrustum(this._frustumPlanes);
  16126. };
  16127. Camera.prototype.isCompletelyInFrustum = function (target) {
  16128. this.updateFrustumPlanes();
  16129. return target.isCompletelyInFrustum(this._frustumPlanes);
  16130. };
  16131. Camera.prototype.dispose = function () {
  16132. // Animations
  16133. this.getScene().stopAnimation(this);
  16134. // Remove from scene
  16135. this.getScene().removeCamera(this);
  16136. while (this._rigCameras.length > 0) {
  16137. this._rigCameras.pop().dispose();
  16138. }
  16139. // Postprocesses
  16140. var i = this._postProcesses.length;
  16141. while (--i >= 0) {
  16142. this._postProcesses[i].dispose(this);
  16143. }
  16144. _super.prototype.dispose.call(this);
  16145. };
  16146. // ---- Camera rigs section ----
  16147. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16148. while (this._rigCameras.length > 0) {
  16149. this._rigCameras.pop().dispose();
  16150. }
  16151. this.cameraRigMode = mode;
  16152. this._cameraRigParams = {};
  16153. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16154. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16155. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16156. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16157. // create the rig cameras, unless none
  16158. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16159. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  16160. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  16161. }
  16162. switch (this.cameraRigMode) {
  16163. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16164. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16165. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16166. break;
  16167. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16168. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16169. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16170. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16171. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16172. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16173. break;
  16174. case Camera.RIG_MODE_VR:
  16175. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16176. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16177. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16178. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16179. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16180. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16181. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16182. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16183. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16184. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16185. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16186. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16187. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16188. if (metrics.compensateDistortion) {
  16189. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16190. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16191. }
  16192. break;
  16193. case Camera.RIG_MODE_WEBVR:
  16194. if (rigParams.vrDisplay) {
  16195. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16196. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16197. //Left eye
  16198. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16199. this._rigCameras[0].setCameraRigParameter("left", true);
  16200. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16201. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16202. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16203. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16204. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16205. this._rigCameras[0].parent = this;
  16206. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16207. //Right eye
  16208. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16209. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16210. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16211. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16212. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16213. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16214. this._rigCameras[1].parent = this;
  16215. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16216. }
  16217. break;
  16218. }
  16219. this._cascadePostProcessesToRigCams();
  16220. this.
  16221. update();
  16222. };
  16223. Camera.prototype._getVRProjectionMatrix = function () {
  16224. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16225. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16226. return this._projectionMatrix;
  16227. };
  16228. Camera.prototype._updateCameraRotationMatrix = function () {
  16229. //Here for WebVR
  16230. };
  16231. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16232. //Here for WebVR
  16233. };
  16234. /**
  16235. * This function MUST be overwritten by the different WebVR cameras available.
  16236. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16237. */
  16238. Camera.prototype._getWebVRProjectionMatrix = function () {
  16239. return BABYLON.Matrix.Identity();
  16240. };
  16241. /**
  16242. * This function MUST be overwritten by the different WebVR cameras available.
  16243. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16244. */
  16245. Camera.prototype._getWebVRViewMatrix = function () {
  16246. return BABYLON.Matrix.Identity();
  16247. };
  16248. Camera.prototype.setCameraRigParameter = function (name, value) {
  16249. if (!this._cameraRigParams) {
  16250. this._cameraRigParams = {};
  16251. }
  16252. this._cameraRigParams[name] = value;
  16253. //provisionnally:
  16254. if (name === "interaxialDistance") {
  16255. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16256. }
  16257. };
  16258. /**
  16259. * needs to be overridden by children so sub has required properties to be copied
  16260. */
  16261. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16262. return null;
  16263. };
  16264. /**
  16265. * May need to be overridden by children
  16266. */
  16267. Camera.prototype._updateRigCameras = function () {
  16268. for (var i = 0; i < this._rigCameras.length; i++) {
  16269. this._rigCameras[i].minZ = this.minZ;
  16270. this._rigCameras[i].maxZ = this.maxZ;
  16271. this._rigCameras[i].fov = this.fov;
  16272. }
  16273. // only update viewport when ANAGLYPH
  16274. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16275. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16276. }
  16277. };
  16278. Camera.prototype._setupInputs = function () {
  16279. };
  16280. Camera.prototype.serialize = function () {
  16281. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16282. // Type
  16283. serializationObject.type = this.getClassName();
  16284. // Parent
  16285. if (this.parent) {
  16286. serializationObject.parentId = this.parent.id;
  16287. }
  16288. if (this.inputs) {
  16289. this.inputs.serialize(serializationObject);
  16290. }
  16291. // Animations
  16292. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16293. serializationObject.ranges = this.serializeAnimationRanges();
  16294. return serializationObject;
  16295. };
  16296. Camera.prototype.clone = function (name) {
  16297. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16298. };
  16299. Camera.prototype.getDirection = function (localAxis) {
  16300. var result = BABYLON.Vector3.Zero();
  16301. this.getDirectionToRef(localAxis, result);
  16302. return result;
  16303. };
  16304. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16305. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16306. };
  16307. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16308. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16309. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16310. switch (type) {
  16311. case "ArcRotateCamera":
  16312. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16313. case "DeviceOrientationCamera":
  16314. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16315. case "FollowCamera":
  16316. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16317. case "ArcFollowCamera":
  16318. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16319. case "GamepadCamera":
  16320. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16321. case "TouchCamera":
  16322. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16323. case "VirtualJoysticksCamera":
  16324. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16325. case "WebVRFreeCamera":
  16326. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16327. case "WebVRGamepadCamera":
  16328. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16329. case "VRDeviceOrientationFreeCamera":
  16330. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16331. case "VRDeviceOrientationGamepadCamera":
  16332. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16333. case "AnaglyphArcRotateCamera":
  16334. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16335. case "AnaglyphFreeCamera":
  16336. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16337. case "AnaglyphGamepadCamera":
  16338. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16339. case "AnaglyphUniversalCamera":
  16340. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16341. case "StereoscopicArcRotateCamera":
  16342. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16343. case "StereoscopicFreeCamera":
  16344. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16345. case "StereoscopicGamepadCamera":
  16346. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16347. case "StereoscopicUniversalCamera":
  16348. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16349. case "FreeCamera":
  16350. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16351. default:
  16352. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16353. }
  16354. };
  16355. Camera.Parse = function (parsedCamera, scene) {
  16356. var type = parsedCamera.type;
  16357. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16358. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16359. // Parent
  16360. if (parsedCamera.parentId) {
  16361. camera._waitingParentId = parsedCamera.parentId;
  16362. }
  16363. //If camera has an input manager, let it parse inputs settings
  16364. if (camera.inputs) {
  16365. camera.inputs.parse(parsedCamera);
  16366. camera._setupInputs();
  16367. }
  16368. // Target
  16369. if (parsedCamera.target) {
  16370. if (camera.setTarget) {
  16371. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16372. }
  16373. }
  16374. // Apply 3d rig, when found
  16375. if (parsedCamera.cameraRigMode) {
  16376. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16377. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16378. }
  16379. // Animations
  16380. if (parsedCamera.animations) {
  16381. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16382. var parsedAnimation = parsedCamera.animations[animationIndex];
  16383. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16384. }
  16385. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16386. }
  16387. if (parsedCamera.autoAnimate) {
  16388. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16389. }
  16390. return camera;
  16391. };
  16392. return Camera;
  16393. }(BABYLON.Node));
  16394. // Statics
  16395. Camera._PERSPECTIVE_CAMERA = 0;
  16396. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16397. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16398. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16399. Camera._RIG_MODE_NONE = 0;
  16400. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16401. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16402. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16403. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16404. Camera._RIG_MODE_VR = 20;
  16405. Camera._RIG_MODE_WEBVR = 21;
  16406. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16407. __decorate([
  16408. BABYLON.serializeAsVector3()
  16409. ], Camera.prototype, "position", void 0);
  16410. __decorate([
  16411. BABYLON.serializeAsVector3()
  16412. ], Camera.prototype, "upVector", void 0);
  16413. __decorate([
  16414. BABYLON.serialize()
  16415. ], Camera.prototype, "orthoLeft", void 0);
  16416. __decorate([
  16417. BABYLON.serialize()
  16418. ], Camera.prototype, "orthoRight", void 0);
  16419. __decorate([
  16420. BABYLON.serialize()
  16421. ], Camera.prototype, "orthoBottom", void 0);
  16422. __decorate([
  16423. BABYLON.serialize()
  16424. ], Camera.prototype, "orthoTop", void 0);
  16425. __decorate([
  16426. BABYLON.serialize()
  16427. ], Camera.prototype, "fov", void 0);
  16428. __decorate([
  16429. BABYLON.serialize()
  16430. ], Camera.prototype, "minZ", void 0);
  16431. __decorate([
  16432. BABYLON.serialize()
  16433. ], Camera.prototype, "maxZ", void 0);
  16434. __decorate([
  16435. BABYLON.serialize()
  16436. ], Camera.prototype, "inertia", void 0);
  16437. __decorate([
  16438. BABYLON.serialize()
  16439. ], Camera.prototype, "mode", void 0);
  16440. __decorate([
  16441. BABYLON.serialize()
  16442. ], Camera.prototype, "layerMask", void 0);
  16443. __decorate([
  16444. BABYLON.serialize()
  16445. ], Camera.prototype, "fovMode", void 0);
  16446. __decorate([
  16447. BABYLON.serialize()
  16448. ], Camera.prototype, "cameraRigMode", void 0);
  16449. __decorate([
  16450. BABYLON.serialize()
  16451. ], Camera.prototype, "interaxialDistance", void 0);
  16452. __decorate([
  16453. BABYLON.serialize()
  16454. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16455. BABYLON.Camera = Camera;
  16456. })(BABYLON || (BABYLON = {}));
  16457. //# sourceMappingURL=babylon.camera.js.map
  16458. var BABYLON;
  16459. (function (BABYLON) {
  16460. BABYLON.CameraInputTypes = {};
  16461. var CameraInputsManager = (function () {
  16462. function CameraInputsManager(camera) {
  16463. this.attached = {};
  16464. this.camera = camera;
  16465. this.checkInputs = function () { };
  16466. }
  16467. CameraInputsManager.prototype.add = function (input) {
  16468. var type = input.getSimpleName();
  16469. if (this.attached[type]) {
  16470. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  16471. return;
  16472. }
  16473. this.attached[type] = input;
  16474. input.camera = this.camera;
  16475. //for checkInputs, we are dynamically creating a function
  16476. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  16477. if (input.checkInputs) {
  16478. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16479. }
  16480. if (this.attachedElement) {
  16481. input.attachControl(this.attachedElement);
  16482. }
  16483. };
  16484. CameraInputsManager.prototype.remove = function (inputToRemove) {
  16485. for (var cam in this.attached) {
  16486. var input = this.attached[cam];
  16487. if (input === inputToRemove) {
  16488. input.detachControl(this.attachedElement);
  16489. delete this.attached[cam];
  16490. this.rebuildInputCheck();
  16491. }
  16492. }
  16493. };
  16494. CameraInputsManager.prototype.removeByType = function (inputType) {
  16495. for (var cam in this.attached) {
  16496. var input = this.attached[cam];
  16497. if (input.getTypeName() === inputType) {
  16498. input.detachControl(this.attachedElement);
  16499. delete this.attached[cam];
  16500. this.rebuildInputCheck();
  16501. }
  16502. }
  16503. };
  16504. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  16505. var current = this.checkInputs;
  16506. return function () {
  16507. current();
  16508. fn();
  16509. };
  16510. };
  16511. CameraInputsManager.prototype.attachInput = function (input) {
  16512. input.attachControl(this.attachedElement, this.noPreventDefault);
  16513. };
  16514. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  16515. if (this.attachedElement) {
  16516. return;
  16517. }
  16518. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  16519. this.attachedElement = element;
  16520. this.noPreventDefault = noPreventDefault;
  16521. for (var cam in this.attached) {
  16522. var input = this.attached[cam];
  16523. this.attached[cam].attachControl(element, noPreventDefault);
  16524. }
  16525. };
  16526. CameraInputsManager.prototype.detachElement = function (element) {
  16527. if (this.attachedElement !== element) {
  16528. return;
  16529. }
  16530. for (var cam in this.attached) {
  16531. var input = this.attached[cam];
  16532. this.attached[cam].detachControl(element);
  16533. }
  16534. this.attachedElement = null;
  16535. };
  16536. CameraInputsManager.prototype.rebuildInputCheck = function () {
  16537. this.checkInputs = function () { };
  16538. for (var cam in this.attached) {
  16539. var input = this.attached[cam];
  16540. if (input.checkInputs) {
  16541. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  16542. }
  16543. }
  16544. };
  16545. CameraInputsManager.prototype.clear = function () {
  16546. if (this.attachedElement) {
  16547. this.detachElement(this.attachedElement);
  16548. }
  16549. this.attached = {};
  16550. this.attachedElement = null;
  16551. this.checkInputs = function () { };
  16552. };
  16553. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  16554. var inputs = {};
  16555. for (var cam in this.attached) {
  16556. var input = this.attached[cam];
  16557. var res = BABYLON.SerializationHelper.Serialize(input);
  16558. inputs[input.getTypeName()] = res;
  16559. }
  16560. serializedCamera.inputsmgr = inputs;
  16561. };
  16562. CameraInputsManager.prototype.parse = function (parsedCamera) {
  16563. var parsedInputs = parsedCamera.inputsmgr;
  16564. if (parsedInputs) {
  16565. this.clear();
  16566. for (var n in parsedInputs) {
  16567. var construct = BABYLON.CameraInputTypes[n];
  16568. if (construct) {
  16569. var parsedinput = parsedInputs[n];
  16570. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  16571. this.add(input);
  16572. }
  16573. }
  16574. }
  16575. else {
  16576. //2016-03-08 this part is for managing backward compatibility
  16577. for (var n in this.attached) {
  16578. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  16579. if (construct) {
  16580. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  16581. this.remove(this.attached[n]);
  16582. this.add(input);
  16583. }
  16584. }
  16585. }
  16586. };
  16587. return CameraInputsManager;
  16588. }());
  16589. BABYLON.CameraInputsManager = CameraInputsManager;
  16590. })(BABYLON || (BABYLON = {}));
  16591. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  16592. var BABYLON;
  16593. (function (BABYLON) {
  16594. var FreeCameraMouseInput = (function () {
  16595. function FreeCameraMouseInput(touchEnabled) {
  16596. if (touchEnabled === void 0) { touchEnabled = true; }
  16597. this.touchEnabled = touchEnabled;
  16598. this.buttons = [0, 1, 2];
  16599. this.angularSensibility = 2000.0;
  16600. }
  16601. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  16602. var _this = this;
  16603. var engine = this.camera.getEngine();
  16604. if (!this._pointerInput) {
  16605. this._pointerInput = function (p, s) {
  16606. var evt = p.event;
  16607. if (!_this.touchEnabled && evt.pointerType === "touch") {
  16608. return;
  16609. }
  16610. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  16611. return;
  16612. }
  16613. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16614. try {
  16615. evt.srcElement.setPointerCapture(evt.pointerId);
  16616. }
  16617. catch (e) {
  16618. //Nothing to do with the error. Execution will continue.
  16619. }
  16620. _this.previousPosition = {
  16621. x: evt.clientX,
  16622. y: evt.clientY
  16623. };
  16624. if (!noPreventDefault) {
  16625. evt.preventDefault();
  16626. element.focus();
  16627. }
  16628. }
  16629. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16630. try {
  16631. evt.srcElement.releasePointerCapture(evt.pointerId);
  16632. }
  16633. catch (e) {
  16634. //Nothing to do with the error.
  16635. }
  16636. _this.previousPosition = null;
  16637. if (!noPreventDefault) {
  16638. evt.preventDefault();
  16639. }
  16640. }
  16641. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16642. if (!_this.previousPosition || engine.isPointerLock) {
  16643. return;
  16644. }
  16645. var offsetX = evt.clientX - _this.previousPosition.x;
  16646. var offsetY = evt.clientY - _this.previousPosition.y;
  16647. if (_this.camera.getScene().useRightHandedSystem) {
  16648. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16649. }
  16650. else {
  16651. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16652. }
  16653. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16654. _this.previousPosition = {
  16655. x: evt.clientX,
  16656. y: evt.clientY
  16657. };
  16658. if (!noPreventDefault) {
  16659. evt.preventDefault();
  16660. }
  16661. }
  16662. };
  16663. }
  16664. this._onMouseMove = function (evt) {
  16665. if (!engine.isPointerLock) {
  16666. return;
  16667. }
  16668. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  16669. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  16670. if (_this.camera.getScene().useRightHandedSystem) {
  16671. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  16672. }
  16673. else {
  16674. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  16675. }
  16676. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  16677. _this.previousPosition = null;
  16678. if (!noPreventDefault) {
  16679. evt.preventDefault();
  16680. }
  16681. };
  16682. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16683. element.addEventListener("mousemove", this._onMouseMove, false);
  16684. };
  16685. FreeCameraMouseInput.prototype.detachControl = function (element) {
  16686. if (this._observer && element) {
  16687. this.camera.getScene().onPointerObservable.remove(this._observer);
  16688. element.removeEventListener("mousemove", this._onMouseMove);
  16689. this._observer = null;
  16690. this._onMouseMove = null;
  16691. this.previousPosition = null;
  16692. }
  16693. };
  16694. FreeCameraMouseInput.prototype.getTypeName = function () {
  16695. return "FreeCameraMouseInput";
  16696. };
  16697. FreeCameraMouseInput.prototype.getSimpleName = function () {
  16698. return "mouse";
  16699. };
  16700. return FreeCameraMouseInput;
  16701. }());
  16702. __decorate([
  16703. BABYLON.serialize()
  16704. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  16705. __decorate([
  16706. BABYLON.serialize()
  16707. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  16708. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  16709. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  16710. })(BABYLON || (BABYLON = {}));
  16711. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  16712. var BABYLON;
  16713. (function (BABYLON) {
  16714. var FreeCameraKeyboardMoveInput = (function () {
  16715. function FreeCameraKeyboardMoveInput() {
  16716. this._keys = [];
  16717. this.keysUp = [38];
  16718. this.keysDown = [40];
  16719. this.keysLeft = [37];
  16720. this.keysRight = [39];
  16721. }
  16722. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  16723. var _this = this;
  16724. if (!this._onKeyDown) {
  16725. element.tabIndex = 1;
  16726. this._onKeyDown = function (evt) {
  16727. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16728. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16729. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16730. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16731. var index = _this._keys.indexOf(evt.keyCode);
  16732. if (index === -1) {
  16733. _this._keys.push(evt.keyCode);
  16734. }
  16735. if (!noPreventDefault) {
  16736. evt.preventDefault();
  16737. }
  16738. }
  16739. };
  16740. this._onKeyUp = function (evt) {
  16741. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  16742. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  16743. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  16744. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  16745. var index = _this._keys.indexOf(evt.keyCode);
  16746. if (index >= 0) {
  16747. _this._keys.splice(index, 1);
  16748. }
  16749. if (!noPreventDefault) {
  16750. evt.preventDefault();
  16751. }
  16752. }
  16753. };
  16754. element.addEventListener("keydown", this._onKeyDown, false);
  16755. element.addEventListener("keyup", this._onKeyUp, false);
  16756. BABYLON.Tools.RegisterTopRootEvents([
  16757. { name: "blur", handler: this._onLostFocus }
  16758. ]);
  16759. }
  16760. };
  16761. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  16762. if (this._onKeyDown) {
  16763. element.removeEventListener("keydown", this._onKeyDown);
  16764. element.removeEventListener("keyup", this._onKeyUp);
  16765. BABYLON.Tools.UnregisterTopRootEvents([
  16766. { name: "blur", handler: this._onLostFocus }
  16767. ]);
  16768. this._keys = [];
  16769. this._onKeyDown = null;
  16770. this._onKeyUp = null;
  16771. }
  16772. };
  16773. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  16774. if (this._onKeyDown) {
  16775. var camera = this.camera;
  16776. // Keyboard
  16777. for (var index = 0; index < this._keys.length; index++) {
  16778. var keyCode = this._keys[index];
  16779. var speed = camera._computeLocalCameraSpeed();
  16780. if (this.keysLeft.indexOf(keyCode) !== -1) {
  16781. camera._localDirection.copyFromFloats(-speed, 0, 0);
  16782. }
  16783. else if (this.keysUp.indexOf(keyCode) !== -1) {
  16784. camera._localDirection.copyFromFloats(0, 0, speed);
  16785. }
  16786. else if (this.keysRight.indexOf(keyCode) !== -1) {
  16787. camera._localDirection.copyFromFloats(speed, 0, 0);
  16788. }
  16789. else if (this.keysDown.indexOf(keyCode) !== -1) {
  16790. camera._localDirection.copyFromFloats(0, 0, -speed);
  16791. }
  16792. if (camera.getScene().useRightHandedSystem) {
  16793. camera._localDirection.z *= -1;
  16794. }
  16795. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  16796. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  16797. camera.cameraDirection.addInPlace(camera._transformedDirection);
  16798. }
  16799. }
  16800. };
  16801. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  16802. return "FreeCameraKeyboardMoveInput";
  16803. };
  16804. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  16805. this._keys = [];
  16806. };
  16807. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  16808. return "keyboard";
  16809. };
  16810. return FreeCameraKeyboardMoveInput;
  16811. }());
  16812. __decorate([
  16813. BABYLON.serialize()
  16814. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  16815. __decorate([
  16816. BABYLON.serialize()
  16817. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  16818. __decorate([
  16819. BABYLON.serialize()
  16820. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  16821. __decorate([
  16822. BABYLON.serialize()
  16823. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  16824. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  16825. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  16826. })(BABYLON || (BABYLON = {}));
  16827. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  16828. var BABYLON;
  16829. (function (BABYLON) {
  16830. var FreeCameraTouchInput = (function () {
  16831. function FreeCameraTouchInput() {
  16832. this._offsetX = null;
  16833. this._offsetY = null;
  16834. this._pointerCount = 0;
  16835. this._pointerPressed = [];
  16836. this.touchAngularSensibility = 200000.0;
  16837. this.touchMoveSensibility = 250.0;
  16838. }
  16839. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  16840. var _this = this;
  16841. var previousPosition;
  16842. if (this._pointerInput === undefined) {
  16843. this._onLostFocus = function (evt) {
  16844. _this._offsetX = null;
  16845. _this._offsetY = null;
  16846. };
  16847. this._pointerInput = function (p, s) {
  16848. var evt = p.event;
  16849. if (evt.pointerType === "mouse") {
  16850. return;
  16851. }
  16852. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16853. if (!noPreventDefault) {
  16854. evt.preventDefault();
  16855. }
  16856. _this._pointerPressed.push(evt.pointerId);
  16857. if (_this._pointerPressed.length !== 1) {
  16858. return;
  16859. }
  16860. previousPosition = {
  16861. x: evt.clientX,
  16862. y: evt.clientY
  16863. };
  16864. }
  16865. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  16866. if (!noPreventDefault) {
  16867. evt.preventDefault();
  16868. }
  16869. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16870. if (index === -1) {
  16871. return;
  16872. }
  16873. _this._pointerPressed.splice(index, 1);
  16874. if (index != 0) {
  16875. return;
  16876. }
  16877. previousPosition = null;
  16878. _this._offsetX = null;
  16879. _this._offsetY = null;
  16880. }
  16881. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16882. if (!noPreventDefault) {
  16883. evt.preventDefault();
  16884. }
  16885. if (!previousPosition) {
  16886. return;
  16887. }
  16888. var index = _this._pointerPressed.indexOf(evt.pointerId);
  16889. if (index != 0) {
  16890. return;
  16891. }
  16892. _this._offsetX = evt.clientX - previousPosition.x;
  16893. _this._offsetY = -(evt.clientY - previousPosition.y);
  16894. }
  16895. };
  16896. }
  16897. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  16898. element.addEventListener("blur", this._onLostFocus);
  16899. };
  16900. FreeCameraTouchInput.prototype.detachControl = function (element) {
  16901. if (this._pointerInput && element) {
  16902. this.camera.getScene().onPointerObservable.remove(this._observer);
  16903. this._observer = null;
  16904. element.removeEventListener("blur", this._onLostFocus);
  16905. this._onLostFocus = null;
  16906. this._pointerPressed = [];
  16907. this._offsetX = null;
  16908. this._offsetY = null;
  16909. this._pointerCount = 0;
  16910. }
  16911. };
  16912. FreeCameraTouchInput.prototype.checkInputs = function () {
  16913. if (this._offsetX) {
  16914. var camera = this.camera;
  16915. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  16916. if (this._pointerPressed.length > 1) {
  16917. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  16918. }
  16919. else {
  16920. var speed = camera._computeLocalCameraSpeed();
  16921. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  16922. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  16923. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  16924. }
  16925. }
  16926. };
  16927. FreeCameraTouchInput.prototype.getTypeName = function () {
  16928. return "FreeCameraTouchInput";
  16929. };
  16930. FreeCameraTouchInput.prototype.getSimpleName = function () {
  16931. return "touch";
  16932. };
  16933. return FreeCameraTouchInput;
  16934. }());
  16935. __decorate([
  16936. BABYLON.serialize()
  16937. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  16938. __decorate([
  16939. BABYLON.serialize()
  16940. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  16941. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  16942. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  16943. })(BABYLON || (BABYLON = {}));
  16944. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  16945. var BABYLON;
  16946. (function (BABYLON) {
  16947. var FreeCameraDeviceOrientationInput = (function () {
  16948. function FreeCameraDeviceOrientationInput() {
  16949. var _this = this;
  16950. this._screenOrientationAngle = 0;
  16951. this._screenQuaternion = new BABYLON.Quaternion();
  16952. this._alpha = 0;
  16953. this._beta = 0;
  16954. this._gamma = 0;
  16955. this._orientationChanged = function () {
  16956. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  16957. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  16958. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  16959. };
  16960. this._deviceOrientation = function (evt) {
  16961. _this._alpha = evt.alpha;
  16962. _this._beta = evt.beta;
  16963. _this._gamma = evt.gamma;
  16964. };
  16965. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  16966. this._orientationChanged();
  16967. }
  16968. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  16969. get: function () {
  16970. return this._camera;
  16971. },
  16972. set: function (camera) {
  16973. this._camera = camera;
  16974. if (!this._camera.rotationQuaternion)
  16975. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  16976. },
  16977. enumerable: true,
  16978. configurable: true
  16979. });
  16980. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  16981. window.addEventListener("orientationchange", this._orientationChanged);
  16982. window.addEventListener("deviceorientation", this._deviceOrientation);
  16983. //In certain cases, the attach control is called AFTER orientation was changed,
  16984. //So this is needed.
  16985. this._orientationChanged();
  16986. };
  16987. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  16988. window.removeEventListener("orientationchange", this._orientationChanged);
  16989. window.removeEventListener("deviceorientation", this._deviceOrientation);
  16990. };
  16991. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  16992. //if no device orientation provided, don't update the rotation.
  16993. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  16994. if (!this._alpha)
  16995. return;
  16996. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  16997. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  16998. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  16999. //Mirror on XY Plane
  17000. this._camera.rotationQuaternion.z *= -1;
  17001. this._camera.rotationQuaternion.w *= -1;
  17002. };
  17003. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  17004. return "FreeCameraDeviceOrientationInput";
  17005. };
  17006. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  17007. return "deviceOrientation";
  17008. };
  17009. return FreeCameraDeviceOrientationInput;
  17010. }());
  17011. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  17012. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  17013. })(BABYLON || (BABYLON = {}));
  17014. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  17015. var BABYLON;
  17016. (function (BABYLON) {
  17017. var FreeCameraGamepadInput = (function () {
  17018. function FreeCameraGamepadInput() {
  17019. this.gamepadAngularSensibility = 200;
  17020. this.gamepadMoveSensibility = 40;
  17021. // private members
  17022. this._cameraTransform = BABYLON.Matrix.Identity();
  17023. this._deltaTransform = BABYLON.Vector3.Zero();
  17024. this._vector3 = BABYLON.Vector3.Zero();
  17025. this._vector2 = BABYLON.Vector2.Zero();
  17026. }
  17027. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17028. var _this = this;
  17029. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17030. };
  17031. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  17032. if (this._gamepads) {
  17033. this._gamepads.dispose();
  17034. }
  17035. this.gamepad = null;
  17036. };
  17037. FreeCameraGamepadInput.prototype.checkInputs = function () {
  17038. if (this.gamepad && this.gamepad.leftStick) {
  17039. var camera = this.camera;
  17040. var LSValues = this.gamepad.leftStick;
  17041. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  17042. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17043. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  17044. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  17045. var RSValues = this.gamepad.rightStick;
  17046. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  17047. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  17048. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  17049. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  17050. if (!camera.rotationQuaternion) {
  17051. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  17052. }
  17053. else {
  17054. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  17055. }
  17056. var speed = camera._computeLocalCameraSpeed() * 50.0;
  17057. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  17058. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  17059. camera.cameraDirection.addInPlace(this._deltaTransform);
  17060. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  17061. camera.cameraRotation.addInPlace(this._vector2);
  17062. }
  17063. };
  17064. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17065. // Only the first gamepad found can control the camera
  17066. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17067. // prioritize XBOX gamepads.
  17068. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17069. this.gamepad = gamepad;
  17070. }
  17071. }
  17072. };
  17073. FreeCameraGamepadInput.prototype.getTypeName = function () {
  17074. return "FreeCameraGamepadInput";
  17075. };
  17076. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  17077. return "gamepad";
  17078. };
  17079. return FreeCameraGamepadInput;
  17080. }());
  17081. __decorate([
  17082. BABYLON.serialize()
  17083. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  17084. __decorate([
  17085. BABYLON.serialize()
  17086. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17087. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  17088. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  17089. })(BABYLON || (BABYLON = {}));
  17090. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  17091. var BABYLON;
  17092. (function (BABYLON) {
  17093. var ArcRotateCameraKeyboardMoveInput = (function () {
  17094. function ArcRotateCameraKeyboardMoveInput() {
  17095. this._keys = [];
  17096. this.keysUp = [38];
  17097. this.keysDown = [40];
  17098. this.keysLeft = [37];
  17099. this.keysRight = [39];
  17100. }
  17101. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  17102. var _this = this;
  17103. element.tabIndex = 1;
  17104. this._onKeyDown = function (evt) {
  17105. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17106. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17107. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17108. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17109. var index = _this._keys.indexOf(evt.keyCode);
  17110. if (index === -1) {
  17111. _this._keys.push(evt.keyCode);
  17112. }
  17113. if (evt.preventDefault) {
  17114. if (!noPreventDefault) {
  17115. evt.preventDefault();
  17116. }
  17117. }
  17118. }
  17119. };
  17120. this._onKeyUp = function (evt) {
  17121. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  17122. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  17123. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  17124. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  17125. var index = _this._keys.indexOf(evt.keyCode);
  17126. if (index >= 0) {
  17127. _this._keys.splice(index, 1);
  17128. }
  17129. if (evt.preventDefault) {
  17130. if (!noPreventDefault) {
  17131. evt.preventDefault();
  17132. }
  17133. }
  17134. }
  17135. };
  17136. this._onLostFocus = function () {
  17137. _this._keys = [];
  17138. };
  17139. element.addEventListener("keydown", this._onKeyDown, false);
  17140. element.addEventListener("keyup", this._onKeyUp, false);
  17141. BABYLON.Tools.RegisterTopRootEvents([
  17142. { name: "blur", handler: this._onLostFocus }
  17143. ]);
  17144. };
  17145. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  17146. if (element) {
  17147. element.removeEventListener("keydown", this._onKeyDown);
  17148. element.removeEventListener("keyup", this._onKeyUp);
  17149. }
  17150. BABYLON.Tools.UnregisterTopRootEvents([
  17151. { name: "blur", handler: this._onLostFocus }
  17152. ]);
  17153. this._keys = [];
  17154. this._onKeyDown = null;
  17155. this._onKeyUp = null;
  17156. this._onLostFocus = null;
  17157. };
  17158. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  17159. if (this._onKeyDown) {
  17160. var camera = this.camera;
  17161. for (var index = 0; index < this._keys.length; index++) {
  17162. var keyCode = this._keys[index];
  17163. if (this.keysLeft.indexOf(keyCode) !== -1) {
  17164. camera.inertialAlphaOffset -= 0.01;
  17165. }
  17166. else if (this.keysUp.indexOf(keyCode) !== -1) {
  17167. camera.inertialBetaOffset -= 0.01;
  17168. }
  17169. else if (this.keysRight.indexOf(keyCode) !== -1) {
  17170. camera.inertialAlphaOffset += 0.01;
  17171. }
  17172. else if (this.keysDown.indexOf(keyCode) !== -1) {
  17173. camera.inertialBetaOffset += 0.01;
  17174. }
  17175. }
  17176. }
  17177. };
  17178. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  17179. return "ArcRotateCameraKeyboardMoveInput";
  17180. };
  17181. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  17182. return "keyboard";
  17183. };
  17184. return ArcRotateCameraKeyboardMoveInput;
  17185. }());
  17186. __decorate([
  17187. BABYLON.serialize()
  17188. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  17189. __decorate([
  17190. BABYLON.serialize()
  17191. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  17192. __decorate([
  17193. BABYLON.serialize()
  17194. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  17195. __decorate([
  17196. BABYLON.serialize()
  17197. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  17198. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  17199. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  17200. })(BABYLON || (BABYLON = {}));
  17201. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  17202. var BABYLON;
  17203. (function (BABYLON) {
  17204. var ArcRotateCameraMouseWheelInput = (function () {
  17205. function ArcRotateCameraMouseWheelInput() {
  17206. this.wheelPrecision = 3.0;
  17207. }
  17208. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  17209. var _this = this;
  17210. this._wheel = function (p, s) {
  17211. //sanity check - this should be a PointerWheel event.
  17212. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  17213. return;
  17214. var event = p.event;
  17215. var delta = 0;
  17216. if (event.wheelDelta) {
  17217. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  17218. }
  17219. else if (event.detail) {
  17220. delta = -event.detail / _this.wheelPrecision;
  17221. }
  17222. if (delta)
  17223. _this.camera.inertialRadiusOffset += delta;
  17224. if (event.preventDefault) {
  17225. if (!noPreventDefault) {
  17226. event.preventDefault();
  17227. }
  17228. }
  17229. };
  17230. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  17231. };
  17232. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  17233. if (this._observer && element) {
  17234. this.camera.getScene().onPointerObservable.remove(this._observer);
  17235. this._observer = null;
  17236. this._wheel = null;
  17237. }
  17238. };
  17239. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  17240. return "ArcRotateCameraMouseWheelInput";
  17241. };
  17242. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  17243. return "mousewheel";
  17244. };
  17245. return ArcRotateCameraMouseWheelInput;
  17246. }());
  17247. __decorate([
  17248. BABYLON.serialize()
  17249. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  17250. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  17251. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  17252. })(BABYLON || (BABYLON = {}));
  17253. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  17254. var BABYLON;
  17255. (function (BABYLON) {
  17256. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17257. var ArcRotateCameraPointersInput = (function () {
  17258. function ArcRotateCameraPointersInput() {
  17259. this.buttons = [0, 1, 2];
  17260. this.angularSensibilityX = 1000.0;
  17261. this.angularSensibilityY = 1000.0;
  17262. this.pinchPrecision = 6.0;
  17263. this.panningSensibility = 50.0;
  17264. this._isPanClick = false;
  17265. this.pinchInwards = true;
  17266. }
  17267. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  17268. var _this = this;
  17269. var engine = this.camera.getEngine();
  17270. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  17271. var pointA, pointB;
  17272. var previousPinchDistance = 0;
  17273. this._pointerInput = function (p, s) {
  17274. var evt = p.event;
  17275. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  17276. return;
  17277. }
  17278. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  17279. try {
  17280. evt.srcElement.setPointerCapture(evt.pointerId);
  17281. }
  17282. catch (e) {
  17283. //Nothing to do with the error. Execution will continue.
  17284. }
  17285. // Manage panning with pan button click
  17286. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  17287. // manage pointers
  17288. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  17289. if (pointA === undefined) {
  17290. pointA = cacheSoloPointer;
  17291. }
  17292. else if (pointB === undefined) {
  17293. pointB = cacheSoloPointer;
  17294. }
  17295. if (!noPreventDefault) {
  17296. evt.preventDefault();
  17297. element.focus();
  17298. }
  17299. }
  17300. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  17301. try {
  17302. evt.srcElement.releasePointerCapture(evt.pointerId);
  17303. }
  17304. catch (e) {
  17305. //Nothing to do with the error.
  17306. }
  17307. cacheSoloPointer = null;
  17308. previousPinchDistance = 0;
  17309. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  17310. //but emptying completly pointers collection is required to fix a bug on iPhone :
  17311. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  17312. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  17313. pointA = pointB = undefined;
  17314. if (!noPreventDefault) {
  17315. evt.preventDefault();
  17316. }
  17317. }
  17318. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  17319. if (!noPreventDefault) {
  17320. evt.preventDefault();
  17321. }
  17322. // One button down
  17323. if (pointA && pointB === undefined) {
  17324. if (_this.panningSensibility !== 0 &&
  17325. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  17326. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  17327. _this.camera
  17328. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  17329. _this.camera
  17330. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  17331. }
  17332. else {
  17333. var offsetX = evt.clientX - cacheSoloPointer.x;
  17334. var offsetY = evt.clientY - cacheSoloPointer.y;
  17335. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17336. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17337. }
  17338. cacheSoloPointer.x = evt.clientX;
  17339. cacheSoloPointer.y = evt.clientY;
  17340. }
  17341. else if (pointA && pointB) {
  17342. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  17343. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  17344. ed.x = evt.clientX;
  17345. ed.y = evt.clientY;
  17346. var direction = _this.pinchInwards ? 1 : -1;
  17347. var distX = pointA.x - pointB.x;
  17348. var distY = pointA.y - pointB.y;
  17349. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  17350. if (previousPinchDistance === 0) {
  17351. previousPinchDistance = pinchSquaredDistance;
  17352. return;
  17353. }
  17354. if (pinchSquaredDistance !== previousPinchDistance) {
  17355. _this.camera
  17356. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  17357. (_this.pinchPrecision *
  17358. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  17359. direction);
  17360. previousPinchDistance = pinchSquaredDistance;
  17361. }
  17362. }
  17363. }
  17364. };
  17365. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  17366. this._onContextMenu = function (evt) {
  17367. evt.preventDefault();
  17368. };
  17369. if (!this.camera._useCtrlForPanning) {
  17370. element.addEventListener("contextmenu", this._onContextMenu, false);
  17371. }
  17372. this._onLostFocus = function () {
  17373. //this._keys = [];
  17374. pointA = pointB = undefined;
  17375. previousPinchDistance = 0;
  17376. cacheSoloPointer = null;
  17377. };
  17378. this._onMouseMove = function (evt) {
  17379. if (!engine.isPointerLock) {
  17380. return;
  17381. }
  17382. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  17383. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  17384. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  17385. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  17386. if (!noPreventDefault) {
  17387. evt.preventDefault();
  17388. }
  17389. };
  17390. this._onGestureStart = function (e) {
  17391. if (window.MSGesture === undefined) {
  17392. return;
  17393. }
  17394. if (!_this._MSGestureHandler) {
  17395. _this._MSGestureHandler = new MSGesture();
  17396. _this._MSGestureHandler.target = element;
  17397. }
  17398. _this._MSGestureHandler.addPointer(e.pointerId);
  17399. };
  17400. this._onGesture = function (e) {
  17401. _this.camera.radius *= e.scale;
  17402. if (e.preventDefault) {
  17403. if (!noPreventDefault) {
  17404. e.stopPropagation();
  17405. e.preventDefault();
  17406. }
  17407. }
  17408. };
  17409. element.addEventListener("mousemove", this._onMouseMove, false);
  17410. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  17411. element.addEventListener("MSGestureChange", this._onGesture, false);
  17412. element.addEventListener("keydown", this._onKeyDown, false);
  17413. element.addEventListener("keyup", this._onKeyUp, false);
  17414. BABYLON.Tools.RegisterTopRootEvents([
  17415. { name: "blur", handler: this._onLostFocus }
  17416. ]);
  17417. };
  17418. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  17419. if (element && this._observer) {
  17420. this.camera.getScene().onPointerObservable.remove(this._observer);
  17421. this._observer = null;
  17422. element.removeEventListener("contextmenu", this._onContextMenu);
  17423. element.removeEventListener("mousemove", this._onMouseMove);
  17424. element.removeEventListener("MSPointerDown", this._onGestureStart);
  17425. element.removeEventListener("MSGestureChange", this._onGesture);
  17426. element.removeEventListener("keydown", this._onKeyDown);
  17427. element.removeEventListener("keyup", this._onKeyUp);
  17428. this._isPanClick = false;
  17429. this.pinchInwards = true;
  17430. this._onKeyDown = null;
  17431. this._onKeyUp = null;
  17432. this._onMouseMove = null;
  17433. this._onGestureStart = null;
  17434. this._onGesture = null;
  17435. this._MSGestureHandler = null;
  17436. this._onLostFocus = null;
  17437. this._onContextMenu = null;
  17438. }
  17439. BABYLON.Tools.UnregisterTopRootEvents([
  17440. { name: "blur", handler: this._onLostFocus }
  17441. ]);
  17442. };
  17443. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  17444. return "ArcRotateCameraPointersInput";
  17445. };
  17446. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  17447. return "pointers";
  17448. };
  17449. return ArcRotateCameraPointersInput;
  17450. }());
  17451. __decorate([
  17452. BABYLON.serialize()
  17453. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  17454. __decorate([
  17455. BABYLON.serialize()
  17456. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  17457. __decorate([
  17458. BABYLON.serialize()
  17459. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  17460. __decorate([
  17461. BABYLON.serialize()
  17462. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  17463. __decorate([
  17464. BABYLON.serialize()
  17465. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  17466. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  17467. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  17468. })(BABYLON || (BABYLON = {}));
  17469. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  17470. var BABYLON;
  17471. (function (BABYLON) {
  17472. var ArcRotateCameraGamepadInput = (function () {
  17473. function ArcRotateCameraGamepadInput() {
  17474. this.gamepadRotationSensibility = 80;
  17475. this.gamepadMoveSensibility = 40;
  17476. }
  17477. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  17478. var _this = this;
  17479. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  17480. };
  17481. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  17482. if (this._gamepads) {
  17483. this._gamepads.dispose();
  17484. }
  17485. this.gamepad = null;
  17486. };
  17487. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  17488. if (this.gamepad) {
  17489. var camera = this.camera;
  17490. var RSValues = this.gamepad.rightStick;
  17491. if (RSValues.x != 0) {
  17492. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  17493. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  17494. camera.inertialAlphaOffset += normalizedRX;
  17495. }
  17496. }
  17497. if (RSValues.y != 0) {
  17498. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  17499. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  17500. camera.inertialBetaOffset += normalizedRY;
  17501. }
  17502. }
  17503. var LSValues = this.gamepad.leftStick;
  17504. if (LSValues.y != 0) {
  17505. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  17506. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  17507. this.camera.inertialRadiusOffset -= normalizedLY;
  17508. }
  17509. }
  17510. }
  17511. };
  17512. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  17513. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  17514. // prioritize XBOX gamepads.
  17515. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  17516. this.gamepad = gamepad;
  17517. }
  17518. }
  17519. };
  17520. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  17521. return "ArcRotateCameraGamepadInput";
  17522. };
  17523. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  17524. return "gamepad";
  17525. };
  17526. return ArcRotateCameraGamepadInput;
  17527. }());
  17528. __decorate([
  17529. BABYLON.serialize()
  17530. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  17531. __decorate([
  17532. BABYLON.serialize()
  17533. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  17534. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  17535. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  17536. })(BABYLON || (BABYLON = {}));
  17537. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  17538. var BABYLON;
  17539. (function (BABYLON) {
  17540. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  17541. function ArcRotateCameraVRDeviceOrientationInput() {
  17542. this.alphaCorrection = 1;
  17543. this.betaCorrection = 1;
  17544. this.gammaCorrection = 1;
  17545. this._alpha = 0;
  17546. this._beta = 0;
  17547. this._gamma = 0;
  17548. this._dirty = false;
  17549. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  17550. }
  17551. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  17552. this.camera.attachControl(element, noPreventDefault);
  17553. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  17554. };
  17555. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  17556. var camera = this.camera;
  17557. this._alpha = +evt.alpha | 0;
  17558. this._beta = +evt.beta | 0;
  17559. this._gamma = +evt.gamma | 0;
  17560. this._dirty = true;
  17561. };
  17562. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  17563. if (this._dirty) {
  17564. this._dirty = false;
  17565. if (this._gamma < 0) {
  17566. this._gamma = 180 + this._gamma;
  17567. }
  17568. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  17569. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  17570. }
  17571. };
  17572. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  17573. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  17574. };
  17575. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  17576. return "ArcRotateCameraVRDeviceOrientationInput";
  17577. };
  17578. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  17579. return "VRDeviceOrientation";
  17580. };
  17581. return ArcRotateCameraVRDeviceOrientationInput;
  17582. }());
  17583. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  17584. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  17585. })(BABYLON || (BABYLON = {}));
  17586. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  17587. /// <reference path="babylon.camera.ts" />
  17588. var BABYLON;
  17589. (function (BABYLON) {
  17590. var TargetCamera = (function (_super) {
  17591. __extends(TargetCamera, _super);
  17592. function TargetCamera(name, position, scene) {
  17593. var _this = _super.call(this, name, position, scene) || this;
  17594. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17595. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  17596. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  17597. _this.speed = 2.0;
  17598. _this.noRotationConstraint = false;
  17599. _this.lockedTarget = null;
  17600. _this._currentTarget = BABYLON.Vector3.Zero();
  17601. _this._viewMatrix = BABYLON.Matrix.Zero();
  17602. _this._camMatrix = BABYLON.Matrix.Zero();
  17603. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  17604. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  17605. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  17606. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  17607. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  17608. _this._lookAtTemp = BABYLON.Matrix.Zero();
  17609. _this._tempMatrix = BABYLON.Matrix.Zero();
  17610. return _this;
  17611. }
  17612. TargetCamera.prototype.getFrontPosition = function (distance) {
  17613. var direction = this.getTarget().subtract(this.position);
  17614. direction.normalize();
  17615. direction.scaleInPlace(distance);
  17616. return this.globalPosition.add(direction);
  17617. };
  17618. TargetCamera.prototype._getLockedTargetPosition = function () {
  17619. if (!this.lockedTarget) {
  17620. return null;
  17621. }
  17622. if (this.lockedTarget.absolutePosition) {
  17623. this.lockedTarget.computeWorldMatrix();
  17624. }
  17625. return this.lockedTarget.absolutePosition || this.lockedTarget;
  17626. };
  17627. // Cache
  17628. TargetCamera.prototype._initCache = function () {
  17629. _super.prototype._initCache.call(this);
  17630. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17631. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17632. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17633. };
  17634. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  17635. if (!ignoreParentClass) {
  17636. _super.prototype._updateCache.call(this);
  17637. }
  17638. var lockedTargetPosition = this._getLockedTargetPosition();
  17639. if (!lockedTargetPosition) {
  17640. this._cache.lockedTarget = null;
  17641. }
  17642. else {
  17643. if (!this._cache.lockedTarget) {
  17644. this._cache.lockedTarget = lockedTargetPosition.clone();
  17645. }
  17646. else {
  17647. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  17648. }
  17649. }
  17650. this._cache.rotation.copyFrom(this.rotation);
  17651. if (this.rotationQuaternion)
  17652. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17653. };
  17654. // Synchronized
  17655. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  17656. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  17657. return false;
  17658. }
  17659. var lockedTargetPosition = this._getLockedTargetPosition();
  17660. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  17661. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  17662. };
  17663. // Methods
  17664. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  17665. var engine = this.getEngine();
  17666. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  17667. };
  17668. // Target
  17669. TargetCamera.prototype.setTarget = function (target) {
  17670. this.upVector.normalize();
  17671. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  17672. this._camMatrix.invert();
  17673. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  17674. var vDir = target.subtract(this.position);
  17675. if (vDir.x >= 0.0) {
  17676. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  17677. }
  17678. else {
  17679. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  17680. }
  17681. this.rotation.z = 0;
  17682. if (isNaN(this.rotation.x)) {
  17683. this.rotation.x = 0;
  17684. }
  17685. if (isNaN(this.rotation.y)) {
  17686. this.rotation.y = 0;
  17687. }
  17688. if (isNaN(this.rotation.z)) {
  17689. this.rotation.z = 0;
  17690. }
  17691. if (this.rotationQuaternion) {
  17692. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17693. }
  17694. };
  17695. /**
  17696. * Return the current target position of the camera. This value is expressed in local space.
  17697. */
  17698. TargetCamera.prototype.getTarget = function () {
  17699. return this._currentTarget;
  17700. };
  17701. TargetCamera.prototype._decideIfNeedsToMove = function () {
  17702. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  17703. };
  17704. TargetCamera.prototype._updatePosition = function () {
  17705. if (this.parent) {
  17706. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  17707. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  17708. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  17709. return;
  17710. }
  17711. this.position.addInPlace(this.cameraDirection);
  17712. };
  17713. TargetCamera.prototype._checkInputs = function () {
  17714. var needToMove = this._decideIfNeedsToMove();
  17715. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  17716. // Move
  17717. if (needToMove) {
  17718. this._updatePosition();
  17719. }
  17720. // Rotate
  17721. if (needToRotate) {
  17722. this.rotation.x += this.cameraRotation.x;
  17723. this.rotation.y += this.cameraRotation.y;
  17724. //rotate, if quaternion is set and rotation was used
  17725. if (this.rotationQuaternion) {
  17726. var len = this.rotation.lengthSquared();
  17727. if (len) {
  17728. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  17729. }
  17730. }
  17731. if (!this.noRotationConstraint) {
  17732. var limit = (Math.PI / 2) * 0.95;
  17733. if (this.rotation.x > limit)
  17734. this.rotation.x = limit;
  17735. if (this.rotation.x < -limit)
  17736. this.rotation.x = -limit;
  17737. }
  17738. }
  17739. // Inertia
  17740. if (needToMove) {
  17741. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  17742. this.cameraDirection.x = 0;
  17743. }
  17744. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  17745. this.cameraDirection.y = 0;
  17746. }
  17747. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  17748. this.cameraDirection.z = 0;
  17749. }
  17750. this.cameraDirection.scaleInPlace(this.inertia);
  17751. }
  17752. if (needToRotate) {
  17753. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  17754. this.cameraRotation.x = 0;
  17755. }
  17756. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  17757. this.cameraRotation.y = 0;
  17758. }
  17759. this.cameraRotation.scaleInPlace(this.inertia);
  17760. }
  17761. _super.prototype._checkInputs.call(this);
  17762. };
  17763. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  17764. if (this.rotationQuaternion) {
  17765. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  17766. //update the up vector!
  17767. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  17768. }
  17769. else {
  17770. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  17771. }
  17772. };
  17773. TargetCamera.prototype._getViewMatrix = function () {
  17774. if (!this.lockedTarget) {
  17775. // Compute
  17776. this._updateCameraRotationMatrix();
  17777. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  17778. // Computing target and final matrix
  17779. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  17780. }
  17781. else {
  17782. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  17783. }
  17784. if (this.getScene().useRightHandedSystem) {
  17785. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17786. }
  17787. else {
  17788. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  17789. }
  17790. return this._viewMatrix;
  17791. };
  17792. /**
  17793. * @override
  17794. * Override Camera.createRigCamera
  17795. */
  17796. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  17797. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  17798. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  17799. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  17800. if (!this.rotationQuaternion) {
  17801. this.rotationQuaternion = new BABYLON.Quaternion();
  17802. }
  17803. rigCamera._cameraRigParams = {};
  17804. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  17805. }
  17806. return rigCamera;
  17807. }
  17808. return null;
  17809. };
  17810. /**
  17811. * @override
  17812. * Override Camera._updateRigCameras
  17813. */
  17814. TargetCamera.prototype._updateRigCameras = function () {
  17815. var camLeft = this._rigCameras[0];
  17816. var camRight = this._rigCameras[1];
  17817. switch (this.cameraRigMode) {
  17818. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17819. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17820. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17821. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17822. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  17823. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  17824. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  17825. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  17826. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  17827. camLeft.setTarget(this.getTarget());
  17828. camRight.setTarget(this.getTarget());
  17829. break;
  17830. case BABYLON.Camera.RIG_MODE_VR:
  17831. if (camLeft.rotationQuaternion) {
  17832. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17833. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17834. }
  17835. else {
  17836. camLeft.rotation.copyFrom(this.rotation);
  17837. camRight.rotation.copyFrom(this.rotation);
  17838. }
  17839. camLeft.position.copyFrom(this.position);
  17840. camRight.position.copyFrom(this.position);
  17841. break;
  17842. }
  17843. _super.prototype._updateRigCameras.call(this);
  17844. };
  17845. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  17846. if (!this._rigCamTransformMatrix) {
  17847. this._rigCamTransformMatrix = new BABYLON.Matrix();
  17848. }
  17849. var target = this.getTarget();
  17850. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  17851. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  17852. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  17853. };
  17854. TargetCamera.prototype.getClassName = function () {
  17855. return "TargetCamera";
  17856. };
  17857. return TargetCamera;
  17858. }(BABYLON.Camera));
  17859. __decorate([
  17860. BABYLON.serializeAsVector3()
  17861. ], TargetCamera.prototype, "rotation", void 0);
  17862. __decorate([
  17863. BABYLON.serialize()
  17864. ], TargetCamera.prototype, "speed", void 0);
  17865. __decorate([
  17866. BABYLON.serializeAsMeshReference("lockedTargetId")
  17867. ], TargetCamera.prototype, "lockedTarget", void 0);
  17868. BABYLON.TargetCamera = TargetCamera;
  17869. })(BABYLON || (BABYLON = {}));
  17870. //# sourceMappingURL=babylon.targetCamera.js.map
  17871. var BABYLON;
  17872. (function (BABYLON) {
  17873. var FreeCamera = (function (_super) {
  17874. __extends(FreeCamera, _super);
  17875. function FreeCamera(name, position, scene) {
  17876. var _this = _super.call(this, name, position, scene) || this;
  17877. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17878. _this.checkCollisions = false;
  17879. _this.applyGravity = false;
  17880. _this._collider = new BABYLON.Collider();
  17881. _this._needMoveForGravity = false;
  17882. _this._oldPosition = BABYLON.Vector3.Zero();
  17883. _this._diffPosition = BABYLON.Vector3.Zero();
  17884. _this._newPosition = BABYLON.Vector3.Zero();
  17885. // Collisions
  17886. _this._collisionMask = -1;
  17887. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17888. if (collidedMesh === void 0) { collidedMesh = null; }
  17889. //TODO move this to the collision coordinator!
  17890. if (_this.getScene().workerCollisions)
  17891. newPosition.multiplyInPlace(_this._collider.radius);
  17892. var updatePosition = function (newPos) {
  17893. _this._newPosition.copyFrom(newPos);
  17894. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  17895. var oldPosition = _this.position.clone();
  17896. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  17897. _this.position.addInPlace(_this._diffPosition);
  17898. if (_this.onCollide && collidedMesh) {
  17899. _this.onCollide(collidedMesh);
  17900. }
  17901. }
  17902. };
  17903. updatePosition(newPosition);
  17904. };
  17905. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  17906. _this.inputs.addKeyboard().addMouse();
  17907. return _this;
  17908. }
  17909. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  17910. //-- begin properties for backward compatibility for inputs
  17911. get: function () {
  17912. var mouse = this.inputs.attached["mouse"];
  17913. if (mouse)
  17914. return mouse.angularSensibility;
  17915. },
  17916. set: function (value) {
  17917. var mouse = this.inputs.attached["mouse"];
  17918. if (mouse)
  17919. mouse.angularSensibility = value;
  17920. },
  17921. enumerable: true,
  17922. configurable: true
  17923. });
  17924. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  17925. get: function () {
  17926. var keyboard = this.inputs.attached["keyboard"];
  17927. if (keyboard)
  17928. return keyboard.keysUp;
  17929. },
  17930. set: function (value) {
  17931. var keyboard = this.inputs.attached["keyboard"];
  17932. if (keyboard)
  17933. keyboard.keysUp = value;
  17934. },
  17935. enumerable: true,
  17936. configurable: true
  17937. });
  17938. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  17939. get: function () {
  17940. var keyboard = this.inputs.attached["keyboard"];
  17941. if (keyboard)
  17942. return keyboard.keysDown;
  17943. },
  17944. set: function (value) {
  17945. var keyboard = this.inputs.attached["keyboard"];
  17946. if (keyboard)
  17947. keyboard.keysDown = value;
  17948. },
  17949. enumerable: true,
  17950. configurable: true
  17951. });
  17952. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  17953. get: function () {
  17954. var keyboard = this.inputs.attached["keyboard"];
  17955. if (keyboard)
  17956. return keyboard.keysLeft;
  17957. },
  17958. set: function (value) {
  17959. var keyboard = this.inputs.attached["keyboard"];
  17960. if (keyboard)
  17961. keyboard.keysLeft = value;
  17962. },
  17963. enumerable: true,
  17964. configurable: true
  17965. });
  17966. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  17967. get: function () {
  17968. var keyboard = this.inputs.attached["keyboard"];
  17969. if (keyboard)
  17970. return keyboard.keysRight;
  17971. },
  17972. set: function (value) {
  17973. var keyboard = this.inputs.attached["keyboard"];
  17974. if (keyboard)
  17975. keyboard.keysRight = value;
  17976. },
  17977. enumerable: true,
  17978. configurable: true
  17979. });
  17980. // Controls
  17981. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  17982. this.inputs.attachElement(element, noPreventDefault);
  17983. };
  17984. FreeCamera.prototype.detachControl = function (element) {
  17985. this.inputs.detachElement(element);
  17986. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  17987. this.cameraRotation = new BABYLON.Vector2(0, 0);
  17988. };
  17989. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  17990. get: function () {
  17991. return this._collisionMask;
  17992. },
  17993. set: function (mask) {
  17994. this._collisionMask = !isNaN(mask) ? mask : -1;
  17995. },
  17996. enumerable: true,
  17997. configurable: true
  17998. });
  17999. FreeCamera.prototype._collideWithWorld = function (velocity) {
  18000. var globalPosition;
  18001. if (this.parent) {
  18002. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  18003. }
  18004. else {
  18005. globalPosition = this.position;
  18006. }
  18007. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  18008. this._collider.radius = this.ellipsoid;
  18009. this._collider.collisionMask = this._collisionMask;
  18010. //no need for clone, as long as gravity is not on.
  18011. var actualVelocity = velocity;
  18012. //add gravity to the velocity to prevent the dual-collision checking
  18013. if (this.applyGravity) {
  18014. //this prevents mending with cameraDirection, a global variable of the free camera class.
  18015. actualVelocity = velocity.add(this.getScene().gravity);
  18016. }
  18017. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18018. };
  18019. FreeCamera.prototype._checkInputs = function () {
  18020. if (!this._localDirection) {
  18021. this._localDirection = BABYLON.Vector3.Zero();
  18022. this._transformedDirection = BABYLON.Vector3.Zero();
  18023. }
  18024. this.inputs.checkInputs();
  18025. _super.prototype._checkInputs.call(this);
  18026. };
  18027. FreeCamera.prototype._decideIfNeedsToMove = function () {
  18028. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  18029. };
  18030. FreeCamera.prototype._updatePosition = function () {
  18031. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  18032. this._collideWithWorld(this.cameraDirection);
  18033. }
  18034. else {
  18035. _super.prototype._updatePosition.call(this);
  18036. }
  18037. };
  18038. FreeCamera.prototype.dispose = function () {
  18039. this.inputs.clear();
  18040. _super.prototype.dispose.call(this);
  18041. };
  18042. FreeCamera.prototype.getClassName = function () {
  18043. return "FreeCamera";
  18044. };
  18045. return FreeCamera;
  18046. }(BABYLON.TargetCamera));
  18047. __decorate([
  18048. BABYLON.serializeAsVector3()
  18049. ], FreeCamera.prototype, "ellipsoid", void 0);
  18050. __decorate([
  18051. BABYLON.serialize()
  18052. ], FreeCamera.prototype, "checkCollisions", void 0);
  18053. __decorate([
  18054. BABYLON.serialize()
  18055. ], FreeCamera.prototype, "applyGravity", void 0);
  18056. BABYLON.FreeCamera = FreeCamera;
  18057. })(BABYLON || (BABYLON = {}));
  18058. //# sourceMappingURL=babylon.freeCamera.js.map
  18059. var BABYLON;
  18060. (function (BABYLON) {
  18061. var FreeCameraInputsManager = (function (_super) {
  18062. __extends(FreeCameraInputsManager, _super);
  18063. function FreeCameraInputsManager(camera) {
  18064. return _super.call(this, camera) || this;
  18065. }
  18066. FreeCameraInputsManager.prototype.addKeyboard = function () {
  18067. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  18068. return this;
  18069. };
  18070. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  18071. if (touchEnabled === void 0) { touchEnabled = true; }
  18072. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  18073. return this;
  18074. };
  18075. FreeCameraInputsManager.prototype.addGamepad = function () {
  18076. this.add(new BABYLON.FreeCameraGamepadInput());
  18077. return this;
  18078. };
  18079. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  18080. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  18081. return this;
  18082. };
  18083. FreeCameraInputsManager.prototype.addTouch = function () {
  18084. this.add(new BABYLON.FreeCameraTouchInput());
  18085. return this;
  18086. };
  18087. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  18088. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  18089. return this;
  18090. };
  18091. return FreeCameraInputsManager;
  18092. }(BABYLON.CameraInputsManager));
  18093. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  18094. })(BABYLON || (BABYLON = {}));
  18095. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  18096. /// <reference path="babylon.targetCamera.ts" />
  18097. var BABYLON;
  18098. (function (BABYLON) {
  18099. var FollowCamera = (function (_super) {
  18100. __extends(FollowCamera, _super);
  18101. function FollowCamera(name, position, scene, lockedTarget) {
  18102. var _this = _super.call(this, name, position, scene) || this;
  18103. _this.radius = 12;
  18104. _this.rotationOffset = 0;
  18105. _this.heightOffset = 4;
  18106. _this.cameraAcceleration = 0.05;
  18107. _this.maxCameraSpeed = 20;
  18108. _this.lockedTarget = lockedTarget;
  18109. return _this;
  18110. }
  18111. FollowCamera.prototype.getRadians = function (degrees) {
  18112. return degrees * Math.PI / 180;
  18113. };
  18114. FollowCamera.prototype.follow = function (cameraTarget) {
  18115. if (!cameraTarget)
  18116. return;
  18117. var yRotation;
  18118. if (cameraTarget.rotationQuaternion) {
  18119. var rotMatrix = new BABYLON.Matrix();
  18120. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  18121. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  18122. }
  18123. else {
  18124. yRotation = cameraTarget.rotation.y;
  18125. }
  18126. var radians = this.getRadians(this.rotationOffset) + yRotation;
  18127. var targetPosition = cameraTarget.getAbsolutePosition();
  18128. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  18129. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  18130. var dx = targetX - this.position.x;
  18131. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  18132. var dz = (targetZ) - this.position.z;
  18133. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  18134. var vy = dy * this.cameraAcceleration;
  18135. var vz = dz * this.cameraAcceleration * 2;
  18136. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  18137. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18138. }
  18139. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  18140. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18141. }
  18142. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  18143. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  18144. }
  18145. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  18146. this.setTarget(targetPosition);
  18147. };
  18148. FollowCamera.prototype._checkInputs = function () {
  18149. _super.prototype._checkInputs.call(this);
  18150. this.follow(this.lockedTarget);
  18151. };
  18152. FollowCamera.prototype.getClassName = function () {
  18153. return "FollowCamera";
  18154. };
  18155. return FollowCamera;
  18156. }(BABYLON.TargetCamera));
  18157. __decorate([
  18158. BABYLON.serialize()
  18159. ], FollowCamera.prototype, "radius", void 0);
  18160. __decorate([
  18161. BABYLON.serialize()
  18162. ], FollowCamera.prototype, "rotationOffset", void 0);
  18163. __decorate([
  18164. BABYLON.serialize()
  18165. ], FollowCamera.prototype, "heightOffset", void 0);
  18166. __decorate([
  18167. BABYLON.serialize()
  18168. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  18169. __decorate([
  18170. BABYLON.serialize()
  18171. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  18172. __decorate([
  18173. BABYLON.serializeAsMeshReference("lockedTargetId")
  18174. ], FollowCamera.prototype, "lockedTarget", void 0);
  18175. BABYLON.FollowCamera = FollowCamera;
  18176. var ArcFollowCamera = (function (_super) {
  18177. __extends(ArcFollowCamera, _super);
  18178. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  18179. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18180. _this.alpha = alpha;
  18181. _this.beta = beta;
  18182. _this.radius = radius;
  18183. _this.target = target;
  18184. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  18185. _this.follow();
  18186. return _this;
  18187. }
  18188. ArcFollowCamera.prototype.follow = function () {
  18189. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  18190. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  18191. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  18192. var targetPosition = this.target.getAbsolutePosition();
  18193. this.position = targetPosition.add(this._cartesianCoordinates);
  18194. this.setTarget(targetPosition);
  18195. };
  18196. ArcFollowCamera.prototype._checkInputs = function () {
  18197. _super.prototype._checkInputs.call(this);
  18198. this.follow();
  18199. };
  18200. ArcFollowCamera.prototype.getClassName = function () {
  18201. return "ArcFollowCamera";
  18202. };
  18203. return ArcFollowCamera;
  18204. }(BABYLON.TargetCamera));
  18205. BABYLON.ArcFollowCamera = ArcFollowCamera;
  18206. })(BABYLON || (BABYLON = {}));
  18207. //# sourceMappingURL=babylon.followCamera.js.map
  18208. /// <reference path="babylon.freeCamera.ts" />
  18209. var BABYLON;
  18210. (function (BABYLON) {
  18211. // We're mainly based on the logic defined into the FreeCamera code
  18212. var TouchCamera = (function (_super) {
  18213. __extends(TouchCamera, _super);
  18214. //-- end properties for backward compatibility for inputs
  18215. function TouchCamera(name, position, scene) {
  18216. var _this = _super.call(this, name, position, scene) || this;
  18217. _this.inputs.addTouch();
  18218. _this._setupInputs();
  18219. return _this;
  18220. }
  18221. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  18222. //-- Begin properties for backward compatibility for inputs
  18223. get: function () {
  18224. var touch = this.inputs.attached["touch"];
  18225. if (touch)
  18226. return touch.touchAngularSensibility;
  18227. },
  18228. set: function (value) {
  18229. var touch = this.inputs.attached["touch"];
  18230. if (touch)
  18231. touch.touchAngularSensibility = value;
  18232. },
  18233. enumerable: true,
  18234. configurable: true
  18235. });
  18236. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  18237. get: function () {
  18238. var touch = this.inputs.attached["touch"];
  18239. if (touch)
  18240. return touch.touchMoveSensibility;
  18241. },
  18242. set: function (value) {
  18243. var touch = this.inputs.attached["touch"];
  18244. if (touch)
  18245. touch.touchMoveSensibility = value;
  18246. },
  18247. enumerable: true,
  18248. configurable: true
  18249. });
  18250. TouchCamera.prototype.getClassName = function () {
  18251. return "TouchCamera";
  18252. };
  18253. TouchCamera.prototype._setupInputs = function () {
  18254. var mouse = this.inputs.attached["mouse"];
  18255. if (mouse) {
  18256. mouse.touchEnabled = false;
  18257. }
  18258. };
  18259. return TouchCamera;
  18260. }(BABYLON.FreeCamera));
  18261. BABYLON.TouchCamera = TouchCamera;
  18262. })(BABYLON || (BABYLON = {}));
  18263. //# sourceMappingURL=babylon.touchCamera.js.map
  18264. /// <reference path="babylon.targetCamera.ts" />
  18265. /// <reference path="..\Tools\babylon.tools.ts" />
  18266. var BABYLON;
  18267. (function (BABYLON) {
  18268. var ArcRotateCamera = (function (_super) {
  18269. __extends(ArcRotateCamera, _super);
  18270. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  18271. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  18272. _this.inertialAlphaOffset = 0;
  18273. _this.inertialBetaOffset = 0;
  18274. _this.inertialRadiusOffset = 0;
  18275. _this.lowerAlphaLimit = null;
  18276. _this.upperAlphaLimit = null;
  18277. _this.lowerBetaLimit = 0.01;
  18278. _this.upperBetaLimit = Math.PI;
  18279. _this.lowerRadiusLimit = null;
  18280. _this.upperRadiusLimit = null;
  18281. _this.inertialPanningX = 0;
  18282. _this.inertialPanningY = 0;
  18283. //-- end properties for backward compatibility for inputs
  18284. _this.zoomOnFactor = 1;
  18285. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  18286. _this.allowUpsideDown = true;
  18287. _this._viewMatrix = new BABYLON.Matrix();
  18288. // Panning
  18289. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  18290. _this.checkCollisions = false;
  18291. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  18292. _this._collider = new BABYLON.Collider();
  18293. _this._previousPosition = BABYLON.Vector3.Zero();
  18294. _this._collisionVelocity = BABYLON.Vector3.Zero();
  18295. _this._newPosition = BABYLON.Vector3.Zero();
  18296. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  18297. if (collidedMesh === void 0) { collidedMesh = null; }
  18298. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  18299. newPosition.multiplyInPlace(_this._collider.radius);
  18300. }
  18301. if (!collidedMesh) {
  18302. _this._previousPosition.copyFrom(_this.position);
  18303. }
  18304. else {
  18305. _this.setPosition(newPosition);
  18306. if (_this.onCollide) {
  18307. _this.onCollide(collidedMesh);
  18308. }
  18309. }
  18310. // Recompute because of constraints
  18311. var cosa = Math.cos(_this.alpha);
  18312. var sina = Math.sin(_this.alpha);
  18313. var cosb = Math.cos(_this.beta);
  18314. var sinb = Math.sin(_this.beta);
  18315. if (sinb === 0) {
  18316. sinb = 0.0001;
  18317. }
  18318. var target = _this._getTargetPosition();
  18319. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  18320. _this.position.copyFrom(_this._newPosition);
  18321. var up = _this.upVector;
  18322. if (_this.allowUpsideDown && _this.beta < 0) {
  18323. up = up.clone();
  18324. up = up.negate();
  18325. }
  18326. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  18327. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  18328. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  18329. _this._collisionTriggered = false;
  18330. };
  18331. if (!target) {
  18332. _this.target = BABYLON.Vector3.Zero();
  18333. }
  18334. else {
  18335. _this.target = target;
  18336. }
  18337. _this.alpha = alpha;
  18338. _this.beta = beta;
  18339. _this.radius = radius;
  18340. _this.getViewMatrix();
  18341. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  18342. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  18343. return _this;
  18344. }
  18345. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  18346. //-- begin properties for backward compatibility for inputs
  18347. get: function () {
  18348. var pointers = this.inputs.attached["pointers"];
  18349. if (pointers)
  18350. return pointers.angularSensibilityX;
  18351. },
  18352. set: function (value) {
  18353. var pointers = this.inputs.attached["pointers"];
  18354. if (pointers) {
  18355. pointers.angularSensibilityX = value;
  18356. }
  18357. },
  18358. enumerable: true,
  18359. configurable: true
  18360. });
  18361. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  18362. get: function () {
  18363. var pointers = this.inputs.attached["pointers"];
  18364. if (pointers)
  18365. return pointers.angularSensibilityY;
  18366. },
  18367. set: function (value) {
  18368. var pointers = this.inputs.attached["pointers"];
  18369. if (pointers) {
  18370. pointers.angularSensibilityY = value;
  18371. }
  18372. },
  18373. enumerable: true,
  18374. configurable: true
  18375. });
  18376. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  18377. get: function () {
  18378. var pointers = this.inputs.attached["pointers"];
  18379. if (pointers)
  18380. return pointers.pinchPrecision;
  18381. },
  18382. set: function (value) {
  18383. var pointers = this.inputs.attached["pointers"];
  18384. if (pointers) {
  18385. pointers.pinchPrecision = value;
  18386. }
  18387. },
  18388. enumerable: true,
  18389. configurable: true
  18390. });
  18391. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  18392. get: function () {
  18393. var pointers = this.inputs.attached["pointers"];
  18394. if (pointers)
  18395. return pointers.panningSensibility;
  18396. },
  18397. set: function (value) {
  18398. var pointers = this.inputs.attached["pointers"];
  18399. if (pointers) {
  18400. pointers.panningSensibility = value;
  18401. }
  18402. },
  18403. enumerable: true,
  18404. configurable: true
  18405. });
  18406. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  18407. get: function () {
  18408. var keyboard = this.inputs.attached["keyboard"];
  18409. if (keyboard)
  18410. return keyboard.keysUp;
  18411. },
  18412. set: function (value) {
  18413. var keyboard = this.inputs.attached["keyboard"];
  18414. if (keyboard)
  18415. keyboard.keysUp = value;
  18416. },
  18417. enumerable: true,
  18418. configurable: true
  18419. });
  18420. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  18421. get: function () {
  18422. var keyboard = this.inputs.attached["keyboard"];
  18423. if (keyboard)
  18424. return keyboard.keysDown;
  18425. },
  18426. set: function (value) {
  18427. var keyboard = this.inputs.attached["keyboard"];
  18428. if (keyboard)
  18429. keyboard.keysDown = value;
  18430. },
  18431. enumerable: true,
  18432. configurable: true
  18433. });
  18434. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  18435. get: function () {
  18436. var keyboard = this.inputs.attached["keyboard"];
  18437. if (keyboard)
  18438. return keyboard.keysLeft;
  18439. },
  18440. set: function (value) {
  18441. var keyboard = this.inputs.attached["keyboard"];
  18442. if (keyboard)
  18443. keyboard.keysLeft = value;
  18444. },
  18445. enumerable: true,
  18446. configurable: true
  18447. });
  18448. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  18449. get: function () {
  18450. var keyboard = this.inputs.attached["keyboard"];
  18451. if (keyboard)
  18452. return keyboard.keysRight;
  18453. },
  18454. set: function (value) {
  18455. var keyboard = this.inputs.attached["keyboard"];
  18456. if (keyboard)
  18457. keyboard.keysRight = value;
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  18463. get: function () {
  18464. var mousewheel = this.inputs.attached["mousewheel"];
  18465. if (mousewheel)
  18466. return mousewheel.wheelPrecision;
  18467. },
  18468. set: function (value) {
  18469. var mousewheel = this.inputs.attached["mousewheel"];
  18470. if (mousewheel)
  18471. mousewheel.wheelPrecision = value;
  18472. },
  18473. enumerable: true,
  18474. configurable: true
  18475. });
  18476. // Cache
  18477. ArcRotateCamera.prototype._initCache = function () {
  18478. _super.prototype._initCache.call(this);
  18479. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18480. this._cache.alpha = undefined;
  18481. this._cache.beta = undefined;
  18482. this._cache.radius = undefined;
  18483. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  18484. };
  18485. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  18486. if (!ignoreParentClass) {
  18487. _super.prototype._updateCache.call(this);
  18488. }
  18489. this._cache.target.copyFrom(this._getTargetPosition());
  18490. this._cache.alpha = this.alpha;
  18491. this._cache.beta = this.beta;
  18492. this._cache.radius = this.radius;
  18493. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  18494. };
  18495. ArcRotateCamera.prototype._getTargetPosition = function () {
  18496. if (this.target.getAbsolutePosition) {
  18497. var pos = this.target.getAbsolutePosition();
  18498. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  18499. }
  18500. return this.target;
  18501. };
  18502. // Synchronized
  18503. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  18504. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  18505. return false;
  18506. return this._cache.target.equals(this.target)
  18507. && this._cache.alpha === this.alpha
  18508. && this._cache.beta === this.beta
  18509. && this._cache.radius === this.radius
  18510. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  18511. };
  18512. // Methods
  18513. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  18514. var _this = this;
  18515. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  18516. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  18517. this._useCtrlForPanning = useCtrlForPanning;
  18518. this._panningMouseButton = panningMouseButton;
  18519. this.inputs.attachElement(element, noPreventDefault);
  18520. this._reset = function () {
  18521. _this.inertialAlphaOffset = 0;
  18522. _this.inertialBetaOffset = 0;
  18523. _this.inertialRadiusOffset = 0;
  18524. };
  18525. };
  18526. ArcRotateCamera.prototype.detachControl = function (element) {
  18527. this.inputs.detachElement(element);
  18528. if (this._reset) {
  18529. this._reset();
  18530. }
  18531. };
  18532. ArcRotateCamera.prototype._checkInputs = function () {
  18533. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  18534. if (this._collisionTriggered) {
  18535. return;
  18536. }
  18537. this.inputs.checkInputs();
  18538. // Inertia
  18539. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  18540. if (this.getScene().useRightHandedSystem) {
  18541. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18542. }
  18543. else {
  18544. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  18545. }
  18546. this.beta += this.inertialBetaOffset;
  18547. this.radius -= this.inertialRadiusOffset;
  18548. this.inertialAlphaOffset *= this.inertia;
  18549. this.inertialBetaOffset *= this.inertia;
  18550. this.inertialRadiusOffset *= this.inertia;
  18551. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  18552. this.inertialAlphaOffset = 0;
  18553. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  18554. this.inertialBetaOffset = 0;
  18555. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  18556. this.inertialRadiusOffset = 0;
  18557. }
  18558. // Panning inertia
  18559. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  18560. if (!this._localDirection) {
  18561. this._localDirection = BABYLON.Vector3.Zero();
  18562. this._transformedDirection = BABYLON.Vector3.Zero();
  18563. }
  18564. this.inertialPanningX *= this.inertia;
  18565. this.inertialPanningY *= this.inertia;
  18566. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  18567. this.inertialPanningX = 0;
  18568. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  18569. this.inertialPanningY = 0;
  18570. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  18571. this._localDirection.multiplyInPlace(this.panningAxis);
  18572. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  18573. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  18574. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  18575. if (!this.panningAxis.y) {
  18576. this._transformedDirection.y = 0;
  18577. }
  18578. if (!this.target.getAbsolutePosition) {
  18579. this.target.addInPlace(this._transformedDirection);
  18580. }
  18581. }
  18582. // Limits
  18583. this._checkLimits();
  18584. _super.prototype._checkInputs.call(this);
  18585. };
  18586. ArcRotateCamera.prototype._checkLimits = function () {
  18587. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  18588. if (this.allowUpsideDown && this.beta > Math.PI) {
  18589. this.beta = this.beta - (2 * Math.PI);
  18590. }
  18591. }
  18592. else {
  18593. if (this.beta < this.lowerBetaLimit) {
  18594. this.beta = this.lowerBetaLimit;
  18595. }
  18596. }
  18597. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  18598. if (this.allowUpsideDown && this.beta < -Math.PI) {
  18599. this.beta = this.beta + (2 * Math.PI);
  18600. }
  18601. }
  18602. else {
  18603. if (this.beta > this.upperBetaLimit) {
  18604. this.beta = this.upperBetaLimit;
  18605. }
  18606. }
  18607. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  18608. this.alpha = this.lowerAlphaLimit;
  18609. }
  18610. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  18611. this.alpha = this.upperAlphaLimit;
  18612. }
  18613. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  18614. this.radius = this.lowerRadiusLimit;
  18615. }
  18616. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  18617. this.radius = this.upperRadiusLimit;
  18618. }
  18619. };
  18620. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  18621. var radiusv3 = this.position.subtract(this._getTargetPosition());
  18622. this.radius = radiusv3.length();
  18623. // Alpha
  18624. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  18625. if (radiusv3.z < 0) {
  18626. this.alpha = 2 * Math.PI - this.alpha;
  18627. }
  18628. // Beta
  18629. this.beta = Math.acos(radiusv3.y / this.radius);
  18630. this._checkLimits();
  18631. };
  18632. ArcRotateCamera.prototype.setPosition = function (position) {
  18633. if (this.position.equals(position)) {
  18634. return;
  18635. }
  18636. this.position.copyFrom(position);
  18637. this.rebuildAnglesAndRadius();
  18638. };
  18639. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  18640. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  18641. if (allowSamePosition === void 0) { allowSamePosition = false; }
  18642. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  18643. return;
  18644. }
  18645. if (toBoundingCenter && target.getBoundingInfo) {
  18646. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  18647. }
  18648. else {
  18649. this._targetBoundingCenter = null;
  18650. }
  18651. this.target = target;
  18652. this.rebuildAnglesAndRadius();
  18653. };
  18654. ArcRotateCamera.prototype._getViewMatrix = function () {
  18655. // Compute
  18656. var cosa = Math.cos(this.alpha);
  18657. var sina = Math.sin(this.alpha);
  18658. var cosb = Math.cos(this.beta);
  18659. var sinb = Math.sin(this.beta);
  18660. if (sinb === 0) {
  18661. sinb = 0.0001;
  18662. }
  18663. var target = this._getTargetPosition();
  18664. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  18665. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  18666. this._collider.radius = this.collisionRadius;
  18667. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  18668. this._collisionTriggered = true;
  18669. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  18670. }
  18671. else {
  18672. this.position.copyFrom(this._newPosition);
  18673. var up = this.upVector;
  18674. if (this.allowUpsideDown && sinb < 0) {
  18675. up = up.clone();
  18676. up = up.negate();
  18677. }
  18678. if (this.getScene().useRightHandedSystem) {
  18679. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  18680. }
  18681. else {
  18682. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  18683. }
  18684. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  18685. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  18686. }
  18687. this._currentTarget = target;
  18688. return this._viewMatrix;
  18689. };
  18690. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  18691. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18692. meshes = meshes || this.getScene().meshes;
  18693. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  18694. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  18695. this.radius = distance * this.zoomOnFactor;
  18696. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  18697. };
  18698. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  18699. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  18700. var meshesOrMinMaxVector;
  18701. var distance;
  18702. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  18703. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  18704. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  18705. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  18706. }
  18707. else {
  18708. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  18709. distance = meshesOrMinMaxVectorAndDistance.distance;
  18710. }
  18711. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  18712. if (!doNotUpdateMaxZ) {
  18713. this.maxZ = distance * 2;
  18714. }
  18715. };
  18716. /**
  18717. * @override
  18718. * Override Camera.createRigCamera
  18719. */
  18720. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  18721. var alphaShift;
  18722. switch (this.cameraRigMode) {
  18723. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18724. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18725. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18726. case BABYLON.Camera.RIG_MODE_VR:
  18727. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  18728. break;
  18729. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18730. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  18731. break;
  18732. }
  18733. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  18734. rigCam._cameraRigParams = {};
  18735. return rigCam;
  18736. };
  18737. /**
  18738. * @override
  18739. * Override Camera._updateRigCameras
  18740. */
  18741. ArcRotateCamera.prototype._updateRigCameras = function () {
  18742. var camLeft = this._rigCameras[0];
  18743. var camRight = this._rigCameras[1];
  18744. camLeft.beta = camRight.beta = this.beta;
  18745. camLeft.radius = camRight.radius = this.radius;
  18746. switch (this.cameraRigMode) {
  18747. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18748. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18749. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18750. case BABYLON.Camera.RIG_MODE_VR:
  18751. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18752. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18753. break;
  18754. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18755. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  18756. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  18757. break;
  18758. }
  18759. _super.prototype._updateRigCameras.call(this);
  18760. };
  18761. ArcRotateCamera.prototype.dispose = function () {
  18762. this.inputs.clear();
  18763. _super.prototype.dispose.call(this);
  18764. };
  18765. ArcRotateCamera.prototype.getClassName = function () {
  18766. return "ArcRotateCamera";
  18767. };
  18768. return ArcRotateCamera;
  18769. }(BABYLON.TargetCamera));
  18770. __decorate([
  18771. BABYLON.serialize()
  18772. ], ArcRotateCamera.prototype, "alpha", void 0);
  18773. __decorate([
  18774. BABYLON.serialize()
  18775. ], ArcRotateCamera.prototype, "beta", void 0);
  18776. __decorate([
  18777. BABYLON.serialize()
  18778. ], ArcRotateCamera.prototype, "radius", void 0);
  18779. __decorate([
  18780. BABYLON.serializeAsVector3()
  18781. ], ArcRotateCamera.prototype, "target", void 0);
  18782. __decorate([
  18783. BABYLON.serialize()
  18784. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  18785. __decorate([
  18786. BABYLON.serialize()
  18787. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  18788. __decorate([
  18789. BABYLON.serialize()
  18790. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  18791. __decorate([
  18792. BABYLON.serialize()
  18793. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  18794. __decorate([
  18795. BABYLON.serialize()
  18796. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  18797. __decorate([
  18798. BABYLON.serialize()
  18799. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  18800. __decorate([
  18801. BABYLON.serialize()
  18802. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  18803. __decorate([
  18804. BABYLON.serialize()
  18805. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  18806. __decorate([
  18807. BABYLON.serialize()
  18808. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  18809. __decorate([
  18810. BABYLON.serialize()
  18811. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  18812. __decorate([
  18813. BABYLON.serialize()
  18814. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  18815. __decorate([
  18816. BABYLON.serialize()
  18817. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  18818. __decorate([
  18819. BABYLON.serialize()
  18820. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  18821. BABYLON.ArcRotateCamera = ArcRotateCamera;
  18822. })(BABYLON || (BABYLON = {}));
  18823. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  18824. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  18825. var BABYLON;
  18826. (function (BABYLON) {
  18827. var ArcRotateCameraInputsManager = (function (_super) {
  18828. __extends(ArcRotateCameraInputsManager, _super);
  18829. function ArcRotateCameraInputsManager(camera) {
  18830. return _super.call(this, camera) || this;
  18831. }
  18832. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  18833. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  18834. return this;
  18835. };
  18836. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  18837. this.add(new BABYLON.ArcRotateCameraPointersInput());
  18838. return this;
  18839. };
  18840. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  18841. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  18842. return this;
  18843. };
  18844. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  18845. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  18846. return this;
  18847. };
  18848. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  18849. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  18850. return this;
  18851. };
  18852. return ArcRotateCameraInputsManager;
  18853. }(BABYLON.CameraInputsManager));
  18854. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  18855. })(BABYLON || (BABYLON = {}));
  18856. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  18857. var BABYLON;
  18858. (function (BABYLON) {
  18859. var RenderingManager = (function () {
  18860. function RenderingManager(scene) {
  18861. this._renderingGroups = new Array();
  18862. this._autoClearDepthStencil = {};
  18863. this._customOpaqueSortCompareFn = {};
  18864. this._customAlphaTestSortCompareFn = {};
  18865. this._customTransparentSortCompareFn = {};
  18866. this._renderinGroupInfo = null;
  18867. this._scene = scene;
  18868. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18869. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18870. }
  18871. }
  18872. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18873. if (depth === void 0) { depth = true; }
  18874. if (stencil === void 0) { stencil = true; }
  18875. if (this._depthStencilBufferAlreadyCleaned) {
  18876. return;
  18877. }
  18878. this._scene.getEngine().clear(null, false, depth, stencil);
  18879. this._depthStencilBufferAlreadyCleaned = true;
  18880. };
  18881. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18882. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18883. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18884. var info = null;
  18885. if (observable) {
  18886. if (!this._renderinGroupInfo) {
  18887. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18888. }
  18889. info = this._renderinGroupInfo;
  18890. info.scene = this._scene;
  18891. info.camera = this._scene.activeCamera;
  18892. }
  18893. // Dispatch sprites
  18894. if (renderSprites) {
  18895. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18896. var manager = this._scene.spriteManagers[index];
  18897. this.dispatchSprites(manager);
  18898. }
  18899. }
  18900. // Render
  18901. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18902. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18903. var renderingGroup = this._renderingGroups[index];
  18904. if (!renderingGroup && !observable)
  18905. continue;
  18906. this._currentIndex = index;
  18907. var renderingGroupMask = 0;
  18908. // Fire PRECLEAR stage
  18909. if (observable) {
  18910. renderingGroupMask = Math.pow(2, index);
  18911. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18912. info.renderingGroupId = index;
  18913. observable.notifyObservers(info, renderingGroupMask);
  18914. }
  18915. // Clear depth/stencil if needed
  18916. var autoClear = this._autoClearDepthStencil[index];
  18917. if (autoClear && autoClear.autoClear) {
  18918. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18919. }
  18920. if (observable) {
  18921. // Fire PREOPAQUE stage
  18922. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18923. observable.notifyObservers(info, renderingGroupMask);
  18924. // Fire PRETRANSPARENT stage
  18925. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18926. observable.notifyObservers(info, renderingGroupMask);
  18927. }
  18928. if (renderingGroup)
  18929. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18930. // Fire POSTTRANSPARENT stage
  18931. if (observable) {
  18932. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18933. observable.notifyObservers(info, renderingGroupMask);
  18934. }
  18935. }
  18936. };
  18937. RenderingManager.prototype.reset = function () {
  18938. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18939. var renderingGroup = this._renderingGroups[index];
  18940. if (renderingGroup) {
  18941. renderingGroup.prepare();
  18942. }
  18943. }
  18944. };
  18945. RenderingManager.prototype.dispose = function () {
  18946. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18947. var renderingGroup = this._renderingGroups[index];
  18948. if (renderingGroup) {
  18949. renderingGroup.dispose();
  18950. }
  18951. }
  18952. this._renderingGroups.length = 0;
  18953. };
  18954. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18955. if (!this._renderingGroups[renderingGroupId]) {
  18956. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18957. }
  18958. };
  18959. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18960. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18961. this._prepareRenderingGroup(renderingGroupId);
  18962. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18963. };
  18964. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18965. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18966. this._prepareRenderingGroup(renderingGroupId);
  18967. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18968. };
  18969. RenderingManager.prototype.dispatch = function (subMesh) {
  18970. var mesh = subMesh.getMesh();
  18971. var renderingGroupId = mesh.renderingGroupId || 0;
  18972. this._prepareRenderingGroup(renderingGroupId);
  18973. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  18974. };
  18975. /**
  18976. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18977. * This allowed control for front to back rendering or reversly depending of the special needs.
  18978. *
  18979. * @param renderingGroupId The rendering group id corresponding to its index
  18980. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18981. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18982. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18983. */
  18984. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18985. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18986. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18987. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18988. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18989. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18990. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18991. if (this._renderingGroups[renderingGroupId]) {
  18992. var group = this._renderingGroups[renderingGroupId];
  18993. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18994. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18995. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18996. }
  18997. };
  18998. /**
  18999. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19000. *
  19001. * @param renderingGroupId The rendering group id corresponding to its index
  19002. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19003. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19004. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19005. */
  19006. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19007. if (depth === void 0) { depth = true; }
  19008. if (stencil === void 0) { stencil = true; }
  19009. this._autoClearDepthStencil[renderingGroupId] = {
  19010. autoClear: autoClearDepthStencil,
  19011. depth: depth,
  19012. stencil: stencil
  19013. };
  19014. };
  19015. return RenderingManager;
  19016. }());
  19017. /**
  19018. * The max id used for rendering groups (not included)
  19019. */
  19020. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19021. /**
  19022. * The min id used for rendering groups (included)
  19023. */
  19024. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19025. BABYLON.RenderingManager = RenderingManager;
  19026. })(BABYLON || (BABYLON = {}));
  19027. //# sourceMappingURL=babylon.renderingManager.js.map
  19028. var BABYLON;
  19029. (function (BABYLON) {
  19030. var RenderingGroup = (function () {
  19031. /**
  19032. * Creates a new rendering group.
  19033. * @param index The rendering group index
  19034. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19035. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19036. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19037. */
  19038. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19039. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19040. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19041. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19042. this.index = index;
  19043. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19044. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19045. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19046. this._particleSystems = new BABYLON.SmartArray(256);
  19047. this._spriteManagers = new BABYLON.SmartArray(256);
  19048. this._scene = scene;
  19049. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19050. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19051. this.transparentSortCompareFn = transparentSortCompareFn;
  19052. }
  19053. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19054. /**
  19055. * Set the opaque sort comparison function.
  19056. * If null the sub meshes will be render in the order they were created
  19057. */
  19058. set: function (value) {
  19059. this._opaqueSortCompareFn = value;
  19060. if (value) {
  19061. this._renderOpaque = this.renderOpaqueSorted;
  19062. }
  19063. else {
  19064. this._renderOpaque = RenderingGroup.renderUnsorted;
  19065. }
  19066. },
  19067. enumerable: true,
  19068. configurable: true
  19069. });
  19070. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19071. /**
  19072. * Set the alpha test sort comparison function.
  19073. * If null the sub meshes will be render in the order they were created
  19074. */
  19075. set: function (value) {
  19076. this._alphaTestSortCompareFn = value;
  19077. if (value) {
  19078. this._renderAlphaTest = this.renderAlphaTestSorted;
  19079. }
  19080. else {
  19081. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19082. }
  19083. },
  19084. enumerable: true,
  19085. configurable: true
  19086. });
  19087. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19088. /**
  19089. * Set the transparent sort comparison function.
  19090. * If null the sub meshes will be render in the order they were created
  19091. */
  19092. set: function (value) {
  19093. if (value) {
  19094. this._transparentSortCompareFn = value;
  19095. }
  19096. else {
  19097. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19098. }
  19099. this._renderTransparent = this.renderTransparentSorted;
  19100. },
  19101. enumerable: true,
  19102. configurable: true
  19103. });
  19104. /**
  19105. * Render all the sub meshes contained in the group.
  19106. * @param customRenderFunction Used to override the default render behaviour of the group.
  19107. * @returns true if rendered some submeshes.
  19108. */
  19109. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19110. if (customRenderFunction) {
  19111. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  19112. return;
  19113. }
  19114. var engine = this._scene.getEngine();
  19115. // Opaque
  19116. if (this._opaqueSubMeshes.length !== 0) {
  19117. this._renderOpaque(this._opaqueSubMeshes);
  19118. }
  19119. // Alpha test
  19120. if (this._alphaTestSubMeshes.length !== 0) {
  19121. engine.setAlphaTesting(true);
  19122. this._renderAlphaTest(this._alphaTestSubMeshes);
  19123. engine.setAlphaTesting(false);
  19124. }
  19125. // Sprites
  19126. if (renderSprites) {
  19127. this._renderSprites();
  19128. }
  19129. // Particles
  19130. if (renderParticles) {
  19131. this._renderParticles(activeMeshes);
  19132. }
  19133. if (this.onBeforeTransparentRendering) {
  19134. this.onBeforeTransparentRendering();
  19135. }
  19136. // Transparent
  19137. if (this._transparentSubMeshes.length !== 0) {
  19138. this._renderTransparent(this._transparentSubMeshes);
  19139. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19140. }
  19141. };
  19142. /**
  19143. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19144. * @param subMeshes The submeshes to render
  19145. */
  19146. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19147. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19148. };
  19149. /**
  19150. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19151. * @param subMeshes The submeshes to render
  19152. */
  19153. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19154. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  19155. };
  19156. /**
  19157. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19158. * @param subMeshes The submeshes to render
  19159. */
  19160. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19161. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  19162. };
  19163. /**
  19164. * Renders the submeshes in a specified order.
  19165. * @param subMeshes The submeshes to sort before render
  19166. * @param sortCompareFn The comparison function use to sort
  19167. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19168. * @param transparent Specifies to activate blending if true
  19169. */
  19170. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  19171. var subIndex = 0;
  19172. var subMesh;
  19173. for (; subIndex < subMeshes.length; subIndex++) {
  19174. subMesh = subMeshes.data[subIndex];
  19175. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19176. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19177. }
  19178. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19179. sortedArray.sort(sortCompareFn);
  19180. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19181. subMesh = sortedArray[subIndex];
  19182. subMesh.render(transparent);
  19183. }
  19184. };
  19185. /**
  19186. * Renders the submeshes in the order they were dispatched (no sort applied).
  19187. * @param subMeshes The submeshes to render
  19188. */
  19189. RenderingGroup.renderUnsorted = function (subMeshes) {
  19190. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19191. var submesh = subMeshes.data[subIndex];
  19192. submesh.render(false);
  19193. }
  19194. };
  19195. /**
  19196. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19197. * are rendered back to front if in the same alpha index.
  19198. *
  19199. * @param a The first submesh
  19200. * @param b The second submesh
  19201. * @returns The result of the comparison
  19202. */
  19203. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19204. // Alpha index first
  19205. if (a._alphaIndex > b._alphaIndex) {
  19206. return 1;
  19207. }
  19208. if (a._alphaIndex < b._alphaIndex) {
  19209. return -1;
  19210. }
  19211. // Then distance to camera
  19212. return RenderingGroup.backToFrontSortCompare(a, b);
  19213. };
  19214. /**
  19215. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19216. * are rendered back to front.
  19217. *
  19218. * @param a The first submesh
  19219. * @param b The second submesh
  19220. * @returns The result of the comparison
  19221. */
  19222. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19223. // Then distance to camera
  19224. if (a._distanceToCamera < b._distanceToCamera) {
  19225. return 1;
  19226. }
  19227. if (a._distanceToCamera > b._distanceToCamera) {
  19228. return -1;
  19229. }
  19230. return 0;
  19231. };
  19232. /**
  19233. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19234. * are rendered front to back (prevent overdraw).
  19235. *
  19236. * @param a The first submesh
  19237. * @param b The second submesh
  19238. * @returns The result of the comparison
  19239. */
  19240. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19241. // Then distance to camera
  19242. if (a._distanceToCamera < b._distanceToCamera) {
  19243. return -1;
  19244. }
  19245. if (a._distanceToCamera > b._distanceToCamera) {
  19246. return 1;
  19247. }
  19248. return 0;
  19249. };
  19250. /**
  19251. * Resets the different lists of submeshes to prepare a new frame.
  19252. */
  19253. RenderingGroup.prototype.prepare = function () {
  19254. this._opaqueSubMeshes.reset();
  19255. this._transparentSubMeshes.reset();
  19256. this._alphaTestSubMeshes.reset();
  19257. this._particleSystems.reset();
  19258. this._spriteManagers.reset();
  19259. };
  19260. RenderingGroup.prototype.dispose = function () {
  19261. this._opaqueSubMeshes.dispose();
  19262. this._transparentSubMeshes.dispose();
  19263. this._alphaTestSubMeshes.dispose();
  19264. this._particleSystems.dispose();
  19265. this._spriteManagers.dispose();
  19266. };
  19267. /**
  19268. * Inserts the submesh in its correct queue depending on its material.
  19269. * @param subMesh The submesh to dispatch
  19270. */
  19271. RenderingGroup.prototype.dispatch = function (subMesh) {
  19272. var material = subMesh.getMaterial();
  19273. var mesh = subMesh.getMesh();
  19274. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  19275. this._transparentSubMeshes.push(subMesh);
  19276. }
  19277. else if (material.needAlphaTesting()) {
  19278. this._alphaTestSubMeshes.push(subMesh);
  19279. }
  19280. else {
  19281. this._opaqueSubMeshes.push(subMesh); // Opaque
  19282. }
  19283. };
  19284. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19285. this._spriteManagers.push(spriteManager);
  19286. };
  19287. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19288. this._particleSystems.push(particleSystem);
  19289. };
  19290. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19291. if (this._particleSystems.length === 0) {
  19292. return;
  19293. }
  19294. // Particles
  19295. var activeCamera = this._scene.activeCamera;
  19296. this._scene._particlesDuration.beginMonitoring();
  19297. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19298. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19299. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19300. continue;
  19301. }
  19302. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  19303. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19304. }
  19305. }
  19306. this._scene._particlesDuration.endMonitoring(false);
  19307. };
  19308. RenderingGroup.prototype._renderSprites = function () {
  19309. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19310. return;
  19311. }
  19312. // Sprites
  19313. var activeCamera = this._scene.activeCamera;
  19314. this._scene._spritesDuration.beginMonitoring();
  19315. for (var id = 0; id < this._spriteManagers.length; id++) {
  19316. var spriteManager = this._spriteManagers.data[id];
  19317. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19318. spriteManager.render();
  19319. }
  19320. }
  19321. this._scene._spritesDuration.endMonitoring(false);
  19322. };
  19323. return RenderingGroup;
  19324. }());
  19325. BABYLON.RenderingGroup = RenderingGroup;
  19326. })(BABYLON || (BABYLON = {}));
  19327. //# sourceMappingURL=babylon.renderingGroup.js.map
  19328. var BABYLON;
  19329. (function (BABYLON) {
  19330. var ClickInfo = (function () {
  19331. function ClickInfo() {
  19332. this._singleClick = false;
  19333. this._doubleClick = false;
  19334. this._hasSwiped = false;
  19335. this._ignore = false;
  19336. }
  19337. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19338. get: function () {
  19339. return this._singleClick;
  19340. },
  19341. set: function (b) {
  19342. this._singleClick = b;
  19343. },
  19344. enumerable: true,
  19345. configurable: true
  19346. });
  19347. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19348. get: function () {
  19349. return this._doubleClick;
  19350. },
  19351. set: function (b) {
  19352. this._doubleClick = b;
  19353. },
  19354. enumerable: true,
  19355. configurable: true
  19356. });
  19357. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19358. get: function () {
  19359. return this._hasSwiped;
  19360. },
  19361. set: function (b) {
  19362. this._hasSwiped = b;
  19363. },
  19364. enumerable: true,
  19365. configurable: true
  19366. });
  19367. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19368. get: function () {
  19369. return this._ignore;
  19370. },
  19371. set: function (b) {
  19372. this._ignore = b;
  19373. },
  19374. enumerable: true,
  19375. configurable: true
  19376. });
  19377. return ClickInfo;
  19378. }());
  19379. var PointerEventTypes = (function () {
  19380. function PointerEventTypes() {
  19381. }
  19382. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  19383. get: function () {
  19384. return PointerEventTypes._POINTERDOWN;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  19390. get: function () {
  19391. return PointerEventTypes._POINTERUP;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  19397. get: function () {
  19398. return PointerEventTypes._POINTERMOVE;
  19399. },
  19400. enumerable: true,
  19401. configurable: true
  19402. });
  19403. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  19404. get: function () {
  19405. return PointerEventTypes._POINTERWHEEL;
  19406. },
  19407. enumerable: true,
  19408. configurable: true
  19409. });
  19410. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  19411. get: function () {
  19412. return PointerEventTypes._POINTERPICK;
  19413. },
  19414. enumerable: true,
  19415. configurable: true
  19416. });
  19417. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  19418. get: function () {
  19419. return PointerEventTypes._POINTERTAP;
  19420. },
  19421. enumerable: true,
  19422. configurable: true
  19423. });
  19424. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  19425. get: function () {
  19426. return PointerEventTypes._POINTERDOUBLETAP;
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. return PointerEventTypes;
  19432. }());
  19433. PointerEventTypes._POINTERDOWN = 0x01;
  19434. PointerEventTypes._POINTERUP = 0x02;
  19435. PointerEventTypes._POINTERMOVE = 0x04;
  19436. PointerEventTypes._POINTERWHEEL = 0x08;
  19437. PointerEventTypes._POINTERPICK = 0x10;
  19438. PointerEventTypes._POINTERTAP = 0x20;
  19439. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  19440. BABYLON.PointerEventTypes = PointerEventTypes;
  19441. var PointerInfoBase = (function () {
  19442. function PointerInfoBase(type, event) {
  19443. this.type = type;
  19444. this.event = event;
  19445. }
  19446. return PointerInfoBase;
  19447. }());
  19448. BABYLON.PointerInfoBase = PointerInfoBase;
  19449. /**
  19450. * This class is used to store pointer related info for the onPrePointerObservable event.
  19451. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  19452. */
  19453. var PointerInfoPre = (function (_super) {
  19454. __extends(PointerInfoPre, _super);
  19455. function PointerInfoPre(type, event, localX, localY) {
  19456. var _this = _super.call(this, type, event) || this;
  19457. _this.skipOnPointerObservable = false;
  19458. _this.localPosition = new BABYLON.Vector2(localX, localY);
  19459. return _this;
  19460. }
  19461. return PointerInfoPre;
  19462. }(PointerInfoBase));
  19463. BABYLON.PointerInfoPre = PointerInfoPre;
  19464. /**
  19465. * This type contains all the data related to a pointer event in Babylon.js.
  19466. * 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.
  19467. */
  19468. var PointerInfo = (function (_super) {
  19469. __extends(PointerInfo, _super);
  19470. function PointerInfo(type, event, pickInfo) {
  19471. var _this = _super.call(this, type, event) || this;
  19472. _this.pickInfo = pickInfo;
  19473. return _this;
  19474. }
  19475. return PointerInfo;
  19476. }(PointerInfoBase));
  19477. BABYLON.PointerInfo = PointerInfo;
  19478. /**
  19479. * This class is used by the onRenderingGroupObservable
  19480. */
  19481. var RenderingGroupInfo = (function () {
  19482. function RenderingGroupInfo() {
  19483. }
  19484. return RenderingGroupInfo;
  19485. }());
  19486. /**
  19487. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19488. * This stage will be fired no matter what
  19489. */
  19490. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19491. /**
  19492. * Called before opaque object are rendered.
  19493. * This stage will be fired only if there's 3D Opaque content to render
  19494. */
  19495. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19496. /**
  19497. * Called after the opaque objects are rendered and before the transparent ones
  19498. * This stage will be fired only if there's 3D transparent content to render
  19499. */
  19500. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19501. /**
  19502. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19503. * This stage will be fired no matter what
  19504. */
  19505. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19506. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19507. /**
  19508. * Represents a scene to be rendered by the engine.
  19509. * @see http://doc.babylonjs.com/page.php?p=21911
  19510. */
  19511. var Scene = (function () {
  19512. /**
  19513. * @constructor
  19514. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19515. */
  19516. function Scene(engine) {
  19517. // Members
  19518. this.autoClear = true;
  19519. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19520. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19521. this.forceWireframe = false;
  19522. this.forcePointsCloud = false;
  19523. this.forceShowBoundingBoxes = false;
  19524. this.animationsEnabled = true;
  19525. this.constantlyUpdateMeshUnderPointer = false;
  19526. this.useRightHandedSystem = false;
  19527. this.hoverCursor = "pointer";
  19528. // Metadata
  19529. this.metadata = null;
  19530. // Events
  19531. /**
  19532. * An event triggered when the scene is disposed.
  19533. * @type {BABYLON.Observable}
  19534. */
  19535. this.onDisposeObservable = new BABYLON.Observable();
  19536. /**
  19537. * An event triggered before rendering the scene
  19538. * @type {BABYLON.Observable}
  19539. */
  19540. this.onBeforeRenderObservable = new BABYLON.Observable();
  19541. /**
  19542. * An event triggered after rendering the scene
  19543. * @type {BABYLON.Observable}
  19544. */
  19545. this.onAfterRenderObservable = new BABYLON.Observable();
  19546. /**
  19547. * An event triggered when the scene is ready
  19548. * @type {BABYLON.Observable}
  19549. */
  19550. this.onReadyObservable = new BABYLON.Observable();
  19551. /**
  19552. * An event triggered before rendering a camera
  19553. * @type {BABYLON.Observable}
  19554. */
  19555. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19556. /**
  19557. * An event triggered after rendering a camera
  19558. * @type {BABYLON.Observable}
  19559. */
  19560. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19561. /**
  19562. * An event triggered when a camera is created
  19563. * @type {BABYLON.Observable}
  19564. */
  19565. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19566. /**
  19567. * An event triggered when a camera is removed
  19568. * @type {BABYLON.Observable}
  19569. */
  19570. this.onCameraRemovedObservable = new BABYLON.Observable();
  19571. /**
  19572. * An event triggered when a light is created
  19573. * @type {BABYLON.Observable}
  19574. */
  19575. this.onNewLightAddedObservable = new BABYLON.Observable();
  19576. /**
  19577. * An event triggered when a light is removed
  19578. * @type {BABYLON.Observable}
  19579. */
  19580. this.onLightRemovedObservable = new BABYLON.Observable();
  19581. /**
  19582. * An event triggered when a geometry is created
  19583. * @type {BABYLON.Observable}
  19584. */
  19585. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19586. /**
  19587. * An event triggered when a geometry is removed
  19588. * @type {BABYLON.Observable}
  19589. */
  19590. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19591. /**
  19592. * An event triggered when a mesh is created
  19593. * @type {BABYLON.Observable}
  19594. */
  19595. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19596. /**
  19597. * An event triggered when a mesh is removed
  19598. * @type {BABYLON.Observable}
  19599. */
  19600. this.onMeshRemovedObservable = new BABYLON.Observable();
  19601. /**
  19602. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19603. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19604. * 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)
  19605. */
  19606. this.onRenderingGroupObservable = new BABYLON.Observable();
  19607. // Animations
  19608. this.animations = [];
  19609. /**
  19610. * 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).
  19611. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  19612. */
  19613. this.onPrePointerObservable = new BABYLON.Observable();
  19614. /**
  19615. * Observable event triggered each time an input event is received from the rendering canvas
  19616. */
  19617. this.onPointerObservable = new BABYLON.Observable();
  19618. this._meshPickProceed = false;
  19619. this._previousHasSwiped = false;
  19620. this._currentPickResult = null;
  19621. this._previousPickResult = null;
  19622. this._isButtonPressed = false;
  19623. this._doubleClickOccured = false;
  19624. 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
  19625. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19626. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19627. this._startingPointerTime = 0;
  19628. this._previousStartingPointerTime = 0;
  19629. // Fog
  19630. /**
  19631. * is fog enabled on this scene.
  19632. * @type {boolean}
  19633. */
  19634. this.fogEnabled = true;
  19635. this.fogMode = Scene.FOGMODE_NONE;
  19636. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19637. this.fogDensity = 0.1;
  19638. this.fogStart = 0;
  19639. this.fogEnd = 1000.0;
  19640. // Lights
  19641. /**
  19642. * is shadow enabled on this scene.
  19643. * @type {boolean}
  19644. */
  19645. this.shadowsEnabled = true;
  19646. /**
  19647. * is light enabled on this scene.
  19648. * @type {boolean}
  19649. */
  19650. this.lightsEnabled = true;
  19651. /**
  19652. * All of the lights added to this scene.
  19653. * @see BABYLON.Light
  19654. * @type {BABYLON.Light[]}
  19655. */
  19656. this.lights = new Array();
  19657. // Cameras
  19658. /**
  19659. * All of the cameras added to this scene.
  19660. * @see BABYLON.Camera
  19661. * @type {BABYLON.Camera[]}
  19662. */
  19663. this.cameras = new Array();
  19664. this.activeCameras = new Array();
  19665. // Meshes
  19666. /**
  19667. * All of the (abstract) meshes added to this scene.
  19668. * @see BABYLON.AbstractMesh
  19669. * @type {BABYLON.AbstractMesh[]}
  19670. */
  19671. this.meshes = new Array();
  19672. // Geometries
  19673. this._geometries = new Array();
  19674. this.materials = new Array();
  19675. this.multiMaterials = new Array();
  19676. // Textures
  19677. this.texturesEnabled = true;
  19678. this.textures = new Array();
  19679. // Particles
  19680. this.particlesEnabled = true;
  19681. this.particleSystems = new Array();
  19682. // Sprites
  19683. this.spritesEnabled = true;
  19684. this.spriteManagers = new Array();
  19685. // Layers
  19686. this.layers = new Array();
  19687. this.highlightLayers = new Array();
  19688. // Skeletons
  19689. this.skeletonsEnabled = true;
  19690. this.skeletons = new Array();
  19691. // Lens flares
  19692. this.lensFlaresEnabled = true;
  19693. this.lensFlareSystems = new Array();
  19694. // Collisions
  19695. this.collisionsEnabled = true;
  19696. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19697. // Postprocesses
  19698. this.postProcessesEnabled = true;
  19699. // Customs render targets
  19700. this.renderTargetsEnabled = true;
  19701. this.dumpNextRenderTargets = false;
  19702. this.customRenderTargets = new Array();
  19703. // Imported meshes
  19704. this.importedMeshesFiles = new Array();
  19705. // Probes
  19706. this.probesEnabled = true;
  19707. this.reflectionProbes = new Array();
  19708. this._actionManagers = new Array();
  19709. this._meshesForIntersections = new BABYLON.SmartArray(256);
  19710. // Procedural textures
  19711. this.proceduralTexturesEnabled = true;
  19712. this._proceduralTextures = new Array();
  19713. this.soundTracks = new Array();
  19714. this._audioEnabled = true;
  19715. this._headphone = false;
  19716. // Performance counters
  19717. this._totalMeshesCounter = new BABYLON.PerfCounter();
  19718. this._totalLightsCounter = new BABYLON.PerfCounter();
  19719. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  19720. this._totalTexturesCounter = new BABYLON.PerfCounter();
  19721. this._totalVertices = new BABYLON.PerfCounter();
  19722. this._activeIndices = new BABYLON.PerfCounter();
  19723. this._activeParticles = new BABYLON.PerfCounter();
  19724. this._lastFrameDuration = new BABYLON.PerfCounter();
  19725. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  19726. this._renderTargetsDuration = new BABYLON.PerfCounter();
  19727. this._particlesDuration = new BABYLON.PerfCounter();
  19728. this._renderDuration = new BABYLON.PerfCounter();
  19729. this._spritesDuration = new BABYLON.PerfCounter();
  19730. this._activeBones = new BABYLON.PerfCounter();
  19731. this._animationTime = 0;
  19732. this.animationTimeScale = 1;
  19733. this._renderId = 0;
  19734. this._executeWhenReadyTimeoutId = -1;
  19735. this._intermediateRendering = false;
  19736. this._toBeDisposed = new BABYLON.SmartArray(256);
  19737. this._pendingData = []; //ANY
  19738. this._activeMeshes = new BABYLON.SmartArray(256);
  19739. this._processedMaterials = new BABYLON.SmartArray(256);
  19740. this._renderTargets = new BABYLON.SmartArray(256);
  19741. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19742. this._activeSkeletons = new BABYLON.SmartArray(32);
  19743. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  19744. this._activeAnimatables = new Array();
  19745. this._transformMatrix = BABYLON.Matrix.Zero();
  19746. this._edgesRenderers = new BABYLON.SmartArray(16);
  19747. this._uniqueIdCounter = 0;
  19748. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19749. this._engine.scenes.push(this);
  19750. this._externalData = new BABYLON.StringDictionary();
  19751. this._uid = null;
  19752. this._renderingManager = new BABYLON.RenderingManager(this);
  19753. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19754. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19755. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19756. if (BABYLON.OutlineRenderer) {
  19757. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19758. }
  19759. this.attachControl();
  19760. if (BABYLON.SoundTrack) {
  19761. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19762. }
  19763. //simplification queue
  19764. if (BABYLON.SimplificationQueue) {
  19765. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19766. }
  19767. //collision coordinator initialization. For now legacy per default.
  19768. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19769. }
  19770. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19771. get: function () {
  19772. return Scene._FOGMODE_NONE;
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19778. get: function () {
  19779. return Scene._FOGMODE_EXP;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19785. get: function () {
  19786. return Scene._FOGMODE_EXP2;
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19792. get: function () {
  19793. return Scene._FOGMODE_LINEAR;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(Scene.prototype, "onDispose", {
  19799. set: function (callback) {
  19800. if (this._onDisposeObserver) {
  19801. this.onDisposeObservable.remove(this._onDisposeObserver);
  19802. }
  19803. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. Object.defineProperty(Scene.prototype, "beforeRender", {
  19809. set: function (callback) {
  19810. if (this._onBeforeRenderObserver) {
  19811. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19812. }
  19813. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19814. },
  19815. enumerable: true,
  19816. configurable: true
  19817. });
  19818. Object.defineProperty(Scene.prototype, "afterRender", {
  19819. set: function (callback) {
  19820. if (this._onAfterRenderObserver) {
  19821. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19822. }
  19823. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19829. set: function (callback) {
  19830. if (this._onBeforeCameraRenderObserver) {
  19831. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19832. }
  19833. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19834. },
  19835. enumerable: true,
  19836. configurable: true
  19837. });
  19838. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19839. set: function (callback) {
  19840. if (this._onAfterCameraRenderObserver) {
  19841. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19842. }
  19843. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19849. get: function () {
  19850. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19851. },
  19852. enumerable: true,
  19853. configurable: true
  19854. });
  19855. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19856. get: function () {
  19857. if (!this._defaultMaterial) {
  19858. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19859. }
  19860. return this._defaultMaterial;
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19866. get: function () {
  19867. return this._frustumPlanes;
  19868. },
  19869. enumerable: true,
  19870. configurable: true
  19871. });
  19872. Object.defineProperty(Scene.prototype, "debugLayer", {
  19873. // Properties
  19874. get: function () {
  19875. if (!this._debugLayer) {
  19876. this._debugLayer = new BABYLON.DebugLayer(this);
  19877. }
  19878. return this._debugLayer;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19884. get: function () {
  19885. return this._workerCollisions;
  19886. },
  19887. set: function (enabled) {
  19888. enabled = (enabled && !!Worker);
  19889. this._workerCollisions = enabled;
  19890. if (this.collisionCoordinator) {
  19891. this.collisionCoordinator.destroy();
  19892. }
  19893. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19894. this.collisionCoordinator.init(this);
  19895. },
  19896. enumerable: true,
  19897. configurable: true
  19898. });
  19899. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  19900. get: function () {
  19901. return this._selectionOctree;
  19902. },
  19903. enumerable: true,
  19904. configurable: true
  19905. });
  19906. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19907. /**
  19908. * The mesh that is currently under the pointer.
  19909. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19910. */
  19911. get: function () {
  19912. return this._pointerOverMesh;
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. Object.defineProperty(Scene.prototype, "pointerX", {
  19918. /**
  19919. * Current on-screen X position of the pointer
  19920. * @return {number} X position of the pointer
  19921. */
  19922. get: function () {
  19923. return this._pointerX;
  19924. },
  19925. enumerable: true,
  19926. configurable: true
  19927. });
  19928. Object.defineProperty(Scene.prototype, "pointerY", {
  19929. /**
  19930. * Current on-screen Y position of the pointer
  19931. * @return {number} Y position of the pointer
  19932. */
  19933. get: function () {
  19934. return this._pointerY;
  19935. },
  19936. enumerable: true,
  19937. configurable: true
  19938. });
  19939. Scene.prototype.getCachedMaterial = function () {
  19940. return this._cachedMaterial;
  19941. };
  19942. Scene.prototype.getBoundingBoxRenderer = function () {
  19943. return this._boundingBoxRenderer;
  19944. };
  19945. Scene.prototype.getOutlineRenderer = function () {
  19946. return this._outlineRenderer;
  19947. };
  19948. Scene.prototype.getEngine = function () {
  19949. return this._engine;
  19950. };
  19951. Scene.prototype.getTotalVertices = function () {
  19952. return this._totalVertices.current;
  19953. };
  19954. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19955. get: function () {
  19956. return this._totalVertices;
  19957. },
  19958. enumerable: true,
  19959. configurable: true
  19960. });
  19961. Scene.prototype.getActiveIndices = function () {
  19962. return this._activeIndices.current;
  19963. };
  19964. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19965. get: function () {
  19966. return this._activeIndices;
  19967. },
  19968. enumerable: true,
  19969. configurable: true
  19970. });
  19971. Scene.prototype.getActiveParticles = function () {
  19972. return this._activeParticles.current;
  19973. };
  19974. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19975. get: function () {
  19976. return this._activeParticles;
  19977. },
  19978. enumerable: true,
  19979. configurable: true
  19980. });
  19981. Scene.prototype.getActiveBones = function () {
  19982. return this._activeBones.current;
  19983. };
  19984. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19985. get: function () {
  19986. return this._activeBones;
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. // Stats
  19992. Scene.prototype.getLastFrameDuration = function () {
  19993. return this._lastFrameDuration.current;
  19994. };
  19995. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19996. get: function () {
  19997. return this._lastFrameDuration;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20003. return this._evaluateActiveMeshesDuration.current;
  20004. };
  20005. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20006. get: function () {
  20007. return this._evaluateActiveMeshesDuration;
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Scene.prototype.getActiveMeshes = function () {
  20013. return this._activeMeshes;
  20014. };
  20015. Scene.prototype.getRenderTargetsDuration = function () {
  20016. return this._renderTargetsDuration.current;
  20017. };
  20018. Scene.prototype.getRenderDuration = function () {
  20019. return this._renderDuration.current;
  20020. };
  20021. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20022. get: function () {
  20023. return this._renderDuration;
  20024. },
  20025. enumerable: true,
  20026. configurable: true
  20027. });
  20028. Scene.prototype.getParticlesDuration = function () {
  20029. return this._particlesDuration.current;
  20030. };
  20031. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20032. get: function () {
  20033. return this._particlesDuration;
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Scene.prototype.getSpritesDuration = function () {
  20039. return this._spritesDuration.current;
  20040. };
  20041. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20042. get: function () {
  20043. return this._spritesDuration;
  20044. },
  20045. enumerable: true,
  20046. configurable: true
  20047. });
  20048. Scene.prototype.getAnimationRatio = function () {
  20049. return this._animationRatio;
  20050. };
  20051. Scene.prototype.getRenderId = function () {
  20052. return this._renderId;
  20053. };
  20054. Scene.prototype.incrementRenderId = function () {
  20055. this._renderId++;
  20056. };
  20057. Scene.prototype._updatePointerPosition = function (evt) {
  20058. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20059. this._pointerX = evt.clientX - canvasRect.left;
  20060. this._pointerY = evt.clientY - canvasRect.top;
  20061. this._unTranslatedPointerX = this._pointerX;
  20062. this._unTranslatedPointerY = this._pointerY;
  20063. if (this.cameraToUseForPointers) {
  20064. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  20065. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  20066. }
  20067. };
  20068. // Pointers handling
  20069. /**
  20070. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20071. * @param attachUp defines if you want to attach events to pointerup
  20072. * @param attachDown defines if you want to attach events to pointerdown
  20073. * @param attachMove defines if you want to attach events to pointermove
  20074. */
  20075. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20076. var _this = this;
  20077. if (attachUp === void 0) { attachUp = true; }
  20078. if (attachDown === void 0) { attachDown = true; }
  20079. if (attachMove === void 0) { attachMove = true; }
  20080. this._initActionManager = function (act, clickInfo) {
  20081. if (!_this._meshPickProceed) {
  20082. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20083. _this._currentPickResult = pickResult;
  20084. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20085. _this._meshPickProceed = true;
  20086. }
  20087. return act;
  20088. };
  20089. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20090. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20091. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20092. btn !== _this._previousButtonPressed) {
  20093. _this._doubleClickOccured = false;
  20094. clickInfo.singleClick = true;
  20095. clickInfo.ignore = false;
  20096. cb(clickInfo, _this._currentPickResult);
  20097. }
  20098. };
  20099. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20100. var clickInfo = new ClickInfo();
  20101. _this._currentPickResult = null;
  20102. var act;
  20103. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  20104. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  20105. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20106. if (!checkPicking && BABYLON.ActionManager.HasPickTriggers) {
  20107. act = _this._initActionManager(act, clickInfo);
  20108. if (act)
  20109. checkPicking = act.hasPickTriggers;
  20110. }
  20111. if (checkPicking) {
  20112. var btn = evt.button;
  20113. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20114. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20115. if (!clickInfo.hasSwiped) {
  20116. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20117. if (!checkSingleClickImmediately) {
  20118. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  20119. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20120. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20121. act = _this._initActionManager(act, clickInfo);
  20122. if (act)
  20123. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20124. }
  20125. }
  20126. if (checkSingleClickImmediately) {
  20127. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20128. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20129. btn !== _this._previousButtonPressed) {
  20130. clickInfo.singleClick = true;
  20131. cb(clickInfo, _this._currentPickResult);
  20132. }
  20133. }
  20134. else {
  20135. // wait that no double click has been raised during the double click delay
  20136. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20137. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20138. }
  20139. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  20140. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  20141. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20142. act = _this._initActionManager(act, clickInfo);
  20143. if (act)
  20144. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20145. }
  20146. if (checkDoubleClick) {
  20147. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20148. if (btn === _this._previousButtonPressed &&
  20149. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20150. !_this._doubleClickOccured) {
  20151. // pointer has not moved for 2 clicks, it's a double click
  20152. if (!clickInfo.hasSwiped &&
  20153. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20154. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20155. _this._previousStartingPointerTime = 0;
  20156. _this._doubleClickOccured = true;
  20157. clickInfo.doubleClick = true;
  20158. clickInfo.ignore = false;
  20159. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  20160. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20161. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20162. cb(clickInfo, _this._currentPickResult);
  20163. }
  20164. else {
  20165. _this._doubleClickOccured = false;
  20166. _this._previousStartingPointerTime = _this._startingPointerTime;
  20167. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20168. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20169. _this._previousButtonPressed = btn;
  20170. _this._previousHasSwiped = clickInfo.hasSwiped;
  20171. if (Scene.ExclusiveDoubleClickMode) {
  20172. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  20173. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  20174. }
  20175. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20176. cb(clickInfo, _this._previousPickResult);
  20177. }
  20178. else {
  20179. cb(clickInfo, _this._currentPickResult);
  20180. }
  20181. }
  20182. }
  20183. else {
  20184. _this._doubleClickOccured = false;
  20185. _this._previousStartingPointerTime = _this._startingPointerTime;
  20186. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20187. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20188. _this._previousButtonPressed = btn;
  20189. _this._previousHasSwiped = clickInfo.hasSwiped;
  20190. }
  20191. }
  20192. }
  20193. }
  20194. clickInfo.ignore = true;
  20195. cb(clickInfo, _this._currentPickResult);
  20196. };
  20197. var spritePredicate = function (sprite) {
  20198. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20199. };
  20200. this._onPointerMove = function (evt) {
  20201. _this._updatePointerPosition(evt);
  20202. // PreObservable support
  20203. if (_this.onPrePointerObservable.hasObservers()) {
  20204. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20205. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20206. _this.onPrePointerObservable.notifyObservers(pi, type);
  20207. if (pi.skipOnPointerObservable) {
  20208. return;
  20209. }
  20210. }
  20211. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20212. return;
  20213. }
  20214. var canvas = _this._engine.getRenderingCanvas();
  20215. if (!_this.pointerMovePredicate) {
  20216. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20217. }
  20218. // Meshes
  20219. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20220. if (pickResult.hit && pickResult.pickedMesh) {
  20221. _this.setPointerOverSprite(null);
  20222. _this.setPointerOverMesh(pickResult.pickedMesh);
  20223. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20224. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  20225. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  20226. }
  20227. else {
  20228. canvas.style.cursor = _this.hoverCursor;
  20229. }
  20230. }
  20231. else {
  20232. canvas.style.cursor = "";
  20233. }
  20234. }
  20235. else {
  20236. _this.setPointerOverMesh(null);
  20237. // Sprites
  20238. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20239. if (pickResult.hit && pickResult.pickedSprite) {
  20240. _this.setPointerOverSprite(pickResult.pickedSprite);
  20241. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  20242. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  20243. }
  20244. else {
  20245. canvas.style.cursor = _this.hoverCursor;
  20246. }
  20247. }
  20248. else {
  20249. _this.setPointerOverSprite(null);
  20250. // Restore pointer
  20251. canvas.style.cursor = "";
  20252. }
  20253. }
  20254. if (_this.onPointerMove) {
  20255. _this.onPointerMove(evt, pickResult);
  20256. }
  20257. if (_this.onPointerObservable.hasObservers()) {
  20258. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  20259. var pi = new PointerInfo(type, evt, pickResult);
  20260. _this.onPointerObservable.notifyObservers(pi, type);
  20261. }
  20262. };
  20263. this._onPointerDown = function (evt) {
  20264. _this._isButtonPressed = true;
  20265. _this._pickedDownMesh = null;
  20266. _this._meshPickProceed = false;
  20267. _this._updatePointerPosition(evt);
  20268. // PreObservable support
  20269. if (_this.onPrePointerObservable.hasObservers()) {
  20270. var type = PointerEventTypes.POINTERDOWN;
  20271. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20272. _this.onPrePointerObservable.notifyObservers(pi, type);
  20273. if (pi.skipOnPointerObservable) {
  20274. return;
  20275. }
  20276. }
  20277. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20278. return;
  20279. }
  20280. _this._startingPointerPosition.x = _this._pointerX;
  20281. _this._startingPointerPosition.y = _this._pointerY;
  20282. _this._startingPointerTime = new Date().getTime();
  20283. if (!_this.pointerDownPredicate) {
  20284. _this.pointerDownPredicate = function (mesh) {
  20285. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20286. };
  20287. }
  20288. // Meshes
  20289. _this._pickedDownMesh = null;
  20290. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20291. if (pickResult.hit && pickResult.pickedMesh) {
  20292. _this._pickedDownMesh = pickResult.pickedMesh;
  20293. var actionManager = pickResult.pickedMesh.actionManager;
  20294. if (actionManager) {
  20295. if (actionManager.hasPickTriggers) {
  20296. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20297. switch (evt.button) {
  20298. case 0:
  20299. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20300. break;
  20301. case 1:
  20302. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20303. break;
  20304. case 2:
  20305. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20306. break;
  20307. }
  20308. }
  20309. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20310. window.setTimeout((function () {
  20311. var _this = this;
  20312. 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);
  20313. if (pickResult.hit && pickResult.pickedMesh) {
  20314. if (this._isButtonPressed &&
  20315. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  20316. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  20317. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  20318. this._startingPointerTime = 0;
  20319. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20320. }
  20321. }
  20322. }).bind(_this), Scene.LongPressDelay);
  20323. }
  20324. }
  20325. }
  20326. if (_this.onPointerDown) {
  20327. _this.onPointerDown(evt, pickResult);
  20328. }
  20329. if (_this.onPointerObservable.hasObservers()) {
  20330. var type = PointerEventTypes.POINTERDOWN;
  20331. var pi = new PointerInfo(type, evt, pickResult);
  20332. _this.onPointerObservable.notifyObservers(pi, type);
  20333. }
  20334. // Sprites
  20335. _this._pickedDownSprite = null;
  20336. if (_this.spriteManagers.length > 0) {
  20337. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  20338. if (pickResult.hit && pickResult.pickedSprite) {
  20339. if (pickResult.pickedSprite.actionManager) {
  20340. _this._pickedDownSprite = pickResult.pickedSprite;
  20341. switch (evt.button) {
  20342. case 0:
  20343. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20344. break;
  20345. case 1:
  20346. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20347. break;
  20348. case 2:
  20349. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20350. break;
  20351. }
  20352. if (pickResult.pickedSprite.actionManager) {
  20353. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20354. }
  20355. }
  20356. }
  20357. }
  20358. };
  20359. this._onPointerUp = function (evt) {
  20360. _this._isButtonPressed = false;
  20361. _this._pickedUpMesh = null;
  20362. _this._meshPickProceed = false;
  20363. _this._updatePointerPosition(evt);
  20364. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  20365. // PreObservable support
  20366. if (this.onPrePointerObservable.hasObservers()) {
  20367. if (!clickInfo.ignore) {
  20368. if (!clickInfo.hasSwiped) {
  20369. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20370. var type = PointerEventTypes.POINTERTAP;
  20371. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20372. this.onPrePointerObservable.notifyObservers(pi, type);
  20373. if (pi.skipOnPointerObservable) {
  20374. return;
  20375. }
  20376. }
  20377. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20378. var type = PointerEventTypes.POINTERDOUBLETAP;
  20379. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20380. this.onPrePointerObservable.notifyObservers(pi, type);
  20381. if (pi.skipOnPointerObservable) {
  20382. return;
  20383. }
  20384. }
  20385. }
  20386. }
  20387. else {
  20388. var type = PointerEventTypes.POINTERUP;
  20389. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  20390. this.onPrePointerObservable.notifyObservers(pi, type);
  20391. if (pi.skipOnPointerObservable) {
  20392. return;
  20393. }
  20394. }
  20395. }
  20396. if (!this.cameraToUseForPointers && !this.activeCamera) {
  20397. return;
  20398. }
  20399. if (!this.pointerUpPredicate) {
  20400. this.pointerUpPredicate = function (mesh) {
  20401. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  20402. };
  20403. }
  20404. // Meshes
  20405. if (!this._meshPickProceed && (BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  20406. this._initActionManager(null, clickInfo);
  20407. }
  20408. if (!pickResult) {
  20409. pickResult = this._currentPickResult;
  20410. }
  20411. if (pickResult && pickResult.pickedMesh) {
  20412. this._pickedUpMesh = pickResult.pickedMesh;
  20413. if (this._pickedDownMesh === this._pickedUpMesh) {
  20414. if (this.onPointerPick) {
  20415. this.onPointerPick(evt, pickResult);
  20416. }
  20417. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20418. var type = PointerEventTypes.POINTERPICK;
  20419. var pi = new PointerInfo(type, evt, pickResult);
  20420. this.onPointerObservable.notifyObservers(pi, type);
  20421. }
  20422. }
  20423. if (pickResult.pickedMesh.actionManager) {
  20424. if (clickInfo.ignore) {
  20425. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20426. }
  20427. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20428. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20429. }
  20430. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20431. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20432. }
  20433. }
  20434. }
  20435. if (this._pickedDownMesh &&
  20436. this._pickedDownMesh.actionManager &&
  20437. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20438. this._pickedDownMesh !== this._pickedUpMesh) {
  20439. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20440. }
  20441. if (this.onPointerUp) {
  20442. this.onPointerUp(evt, pickResult);
  20443. }
  20444. if (this.onPointerObservable.hasObservers()) {
  20445. if (!clickInfo.ignore) {
  20446. if (!clickInfo.hasSwiped) {
  20447. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  20448. var type = PointerEventTypes.POINTERTAP;
  20449. var pi = new PointerInfo(type, evt, pickResult);
  20450. this.onPointerObservable.notifyObservers(pi, type);
  20451. }
  20452. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  20453. var type = PointerEventTypes.POINTERDOUBLETAP;
  20454. var pi = new PointerInfo(type, evt, pickResult);
  20455. this.onPointerObservable.notifyObservers(pi, type);
  20456. }
  20457. }
  20458. }
  20459. else {
  20460. var type = PointerEventTypes.POINTERUP;
  20461. var pi = new PointerInfo(type, evt, pickResult);
  20462. this.onPointerObservable.notifyObservers(pi, type);
  20463. }
  20464. }
  20465. // Sprites
  20466. if (this.spriteManagers.length > 0) {
  20467. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  20468. if (pickResult.hit && pickResult.pickedSprite) {
  20469. if (pickResult.pickedSprite.actionManager) {
  20470. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20471. if (pickResult.pickedSprite.actionManager) {
  20472. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  20473. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  20474. }
  20475. }
  20476. }
  20477. }
  20478. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  20479. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  20480. }
  20481. }
  20482. this._previousPickResult = this._currentPickResult;
  20483. }).bind(_this));
  20484. };
  20485. this._onKeyDown = function (evt) {
  20486. if (_this.actionManager) {
  20487. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20488. }
  20489. };
  20490. this._onKeyUp = function (evt) {
  20491. if (_this.actionManager) {
  20492. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20493. }
  20494. };
  20495. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20496. var canvas = this._engine.getRenderingCanvas();
  20497. if (attachMove) {
  20498. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20499. // Wheel
  20500. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20501. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20502. }
  20503. if (attachDown) {
  20504. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20505. }
  20506. if (attachUp) {
  20507. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20508. }
  20509. canvas.tabIndex = 1;
  20510. canvas.addEventListener("keydown", this._onKeyDown, false);
  20511. canvas.addEventListener("keyup", this._onKeyUp, false);
  20512. };
  20513. Scene.prototype.detachControl = function () {
  20514. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20515. var canvas = this._engine.getRenderingCanvas();
  20516. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20517. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20518. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20519. // Wheel
  20520. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20521. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20522. canvas.removeEventListener("keydown", this._onKeyDown);
  20523. canvas.removeEventListener("keyup", this._onKeyUp);
  20524. };
  20525. // Ready
  20526. Scene.prototype.isReady = function () {
  20527. if (this._pendingData.length > 0) {
  20528. return false;
  20529. }
  20530. var index;
  20531. for (index = 0; index < this._geometries.length; index++) {
  20532. var geometry = this._geometries[index];
  20533. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20534. return false;
  20535. }
  20536. }
  20537. for (index = 0; index < this.meshes.length; index++) {
  20538. var mesh = this.meshes[index];
  20539. if (!mesh.isEnabled()) {
  20540. continue;
  20541. }
  20542. if (!mesh.isReady()) {
  20543. return false;
  20544. }
  20545. var mat = mesh.material;
  20546. if (mat) {
  20547. if (!mat.isReady(mesh)) {
  20548. return false;
  20549. }
  20550. }
  20551. }
  20552. return true;
  20553. };
  20554. Scene.prototype.resetCachedMaterial = function () {
  20555. this._cachedMaterial = null;
  20556. };
  20557. Scene.prototype.registerBeforeRender = function (func) {
  20558. this.onBeforeRenderObservable.add(func);
  20559. };
  20560. Scene.prototype.unregisterBeforeRender = function (func) {
  20561. this.onBeforeRenderObservable.removeCallback(func);
  20562. };
  20563. Scene.prototype.registerAfterRender = function (func) {
  20564. this.onAfterRenderObservable.add(func);
  20565. };
  20566. Scene.prototype.unregisterAfterRender = function (func) {
  20567. this.onAfterRenderObservable.removeCallback(func);
  20568. };
  20569. Scene.prototype._addPendingData = function (data) {
  20570. this._pendingData.push(data);
  20571. };
  20572. Scene.prototype._removePendingData = function (data) {
  20573. var index = this._pendingData.indexOf(data);
  20574. if (index !== -1) {
  20575. this._pendingData.splice(index, 1);
  20576. }
  20577. };
  20578. Scene.prototype.getWaitingItemsCount = function () {
  20579. return this._pendingData.length;
  20580. };
  20581. /**
  20582. * Registers a function to be executed when the scene is ready.
  20583. * @param {Function} func - the function to be executed.
  20584. */
  20585. Scene.prototype.executeWhenReady = function (func) {
  20586. var _this = this;
  20587. this.onReadyObservable.add(func);
  20588. if (this._executeWhenReadyTimeoutId !== -1) {
  20589. return;
  20590. }
  20591. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20592. _this._checkIsReady();
  20593. }, 150);
  20594. };
  20595. Scene.prototype._checkIsReady = function () {
  20596. var _this = this;
  20597. if (this.isReady()) {
  20598. this.onReadyObservable.notifyObservers(this);
  20599. this.onReadyObservable.clear();
  20600. this._executeWhenReadyTimeoutId = -1;
  20601. return;
  20602. }
  20603. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20604. _this._checkIsReady();
  20605. }, 150);
  20606. };
  20607. // Animations
  20608. /**
  20609. * Will start the animation sequence of a given target
  20610. * @param target - the target
  20611. * @param {number} from - from which frame should animation start
  20612. * @param {number} to - till which frame should animation run.
  20613. * @param {boolean} [loop] - should the animation loop
  20614. * @param {number} [speedRatio] - the speed in which to run the animation
  20615. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20616. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20617. * @return {BABYLON.Animatable} the animatable object created for this animation
  20618. * @see BABYLON.Animatable
  20619. * @see http://doc.babylonjs.com/page.php?p=22081
  20620. */
  20621. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20622. if (speedRatio === void 0) { speedRatio = 1.0; }
  20623. this.stopAnimation(target);
  20624. if (!animatable) {
  20625. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20626. }
  20627. // Local animations
  20628. if (target.animations) {
  20629. animatable.appendAnimations(target, target.animations);
  20630. }
  20631. // Children animations
  20632. if (target.getAnimatables) {
  20633. var animatables = target.getAnimatables();
  20634. for (var index = 0; index < animatables.length; index++) {
  20635. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20636. }
  20637. }
  20638. animatable.reset();
  20639. return animatable;
  20640. };
  20641. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20642. if (speedRatio === undefined) {
  20643. speedRatio = 1.0;
  20644. }
  20645. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20646. return animatable;
  20647. };
  20648. Scene.prototype.getAnimatableByTarget = function (target) {
  20649. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20650. if (this._activeAnimatables[index].target === target) {
  20651. return this._activeAnimatables[index];
  20652. }
  20653. }
  20654. return null;
  20655. };
  20656. Object.defineProperty(Scene.prototype, "Animatables", {
  20657. get: function () {
  20658. return this._activeAnimatables;
  20659. },
  20660. enumerable: true,
  20661. configurable: true
  20662. });
  20663. /**
  20664. * Will stop the animation of the given target
  20665. * @param target - the target
  20666. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20667. * @see beginAnimation
  20668. */
  20669. Scene.prototype.stopAnimation = function (target, animationName) {
  20670. var animatable = this.getAnimatableByTarget(target);
  20671. if (animatable) {
  20672. animatable.stop(animationName);
  20673. }
  20674. };
  20675. Scene.prototype._animate = function () {
  20676. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20677. return;
  20678. }
  20679. // Getting time
  20680. var now = BABYLON.Tools.Now;
  20681. if (!this._animationTimeLast) {
  20682. if (this._pendingData.length > 0) {
  20683. return;
  20684. }
  20685. this._animationTimeLast = now;
  20686. }
  20687. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  20688. this._animationTime += deltaTime;
  20689. this._animationTimeLast = now;
  20690. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20691. this._activeAnimatables[index]._animate(this._animationTime);
  20692. }
  20693. };
  20694. // Matrix
  20695. Scene.prototype.getViewMatrix = function () {
  20696. return this._viewMatrix;
  20697. };
  20698. Scene.prototype.getProjectionMatrix = function () {
  20699. return this._projectionMatrix;
  20700. };
  20701. Scene.prototype.getTransformMatrix = function () {
  20702. return this._transformMatrix;
  20703. };
  20704. Scene.prototype.setTransformMatrix = function (view, projection) {
  20705. this._viewMatrix = view;
  20706. this._projectionMatrix = projection;
  20707. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20708. // Update frustum
  20709. if (!this._frustumPlanes) {
  20710. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20711. }
  20712. else {
  20713. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20714. }
  20715. };
  20716. // Methods
  20717. Scene.prototype.addMesh = function (newMesh) {
  20718. newMesh.uniqueId = this._uniqueIdCounter++;
  20719. var position = this.meshes.push(newMesh);
  20720. //notify the collision coordinator
  20721. this.collisionCoordinator.onMeshAdded(newMesh);
  20722. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20723. };
  20724. Scene.prototype.removeMesh = function (toRemove) {
  20725. var index = this.meshes.indexOf(toRemove);
  20726. if (index !== -1) {
  20727. // Remove from the scene if mesh found
  20728. this.meshes.splice(index, 1);
  20729. }
  20730. //notify the collision coordinator
  20731. this.collisionCoordinator.onMeshRemoved(toRemove);
  20732. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20733. return index;
  20734. };
  20735. Scene.prototype.removeSkeleton = function (toRemove) {
  20736. var index = this.skeletons.indexOf(toRemove);
  20737. if (index !== -1) {
  20738. // Remove from the scene if mesh found
  20739. this.skeletons.splice(index, 1);
  20740. }
  20741. return index;
  20742. };
  20743. Scene.prototype.removeLight = function (toRemove) {
  20744. var index = this.lights.indexOf(toRemove);
  20745. if (index !== -1) {
  20746. // Remove from the scene if mesh found
  20747. this.lights.splice(index, 1);
  20748. }
  20749. this.onLightRemovedObservable.notifyObservers(toRemove);
  20750. return index;
  20751. };
  20752. Scene.prototype.removeCamera = function (toRemove) {
  20753. var index = this.cameras.indexOf(toRemove);
  20754. if (index !== -1) {
  20755. // Remove from the scene if mesh found
  20756. this.cameras.splice(index, 1);
  20757. }
  20758. // Remove from activeCameras
  20759. var index2 = this.activeCameras.indexOf(toRemove);
  20760. if (index2 !== -1) {
  20761. // Remove from the scene if mesh found
  20762. this.activeCameras.splice(index2, 1);
  20763. }
  20764. // Reset the activeCamera
  20765. if (this.activeCamera === toRemove) {
  20766. if (this.cameras.length > 0) {
  20767. this.activeCamera = this.cameras[0];
  20768. }
  20769. else {
  20770. this.activeCamera = null;
  20771. }
  20772. }
  20773. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20774. return index;
  20775. };
  20776. Scene.prototype.addLight = function (newLight) {
  20777. newLight.uniqueId = this._uniqueIdCounter++;
  20778. var position = this.lights.push(newLight);
  20779. this.onNewLightAddedObservable.notifyObservers(newLight);
  20780. };
  20781. Scene.prototype.addCamera = function (newCamera) {
  20782. newCamera.uniqueId = this._uniqueIdCounter++;
  20783. var position = this.cameras.push(newCamera);
  20784. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20785. };
  20786. /**
  20787. * Switch active camera
  20788. * @param {Camera} newCamera - new active camera
  20789. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20790. */
  20791. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20792. if (attachControl === void 0) { attachControl = true; }
  20793. var canvas = this._engine.getRenderingCanvas();
  20794. this.activeCamera.detachControl(canvas);
  20795. this.activeCamera = newCamera;
  20796. if (attachControl) {
  20797. newCamera.attachControl(canvas);
  20798. }
  20799. };
  20800. /**
  20801. * sets the active camera of the scene using its ID
  20802. * @param {string} id - the camera's ID
  20803. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20804. * @see activeCamera
  20805. */
  20806. Scene.prototype.setActiveCameraByID = function (id) {
  20807. var camera = this.getCameraByID(id);
  20808. if (camera) {
  20809. this.activeCamera = camera;
  20810. return camera;
  20811. }
  20812. return null;
  20813. };
  20814. /**
  20815. * sets the active camera of the scene using its name
  20816. * @param {string} name - the camera's name
  20817. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20818. * @see activeCamera
  20819. */
  20820. Scene.prototype.setActiveCameraByName = function (name) {
  20821. var camera = this.getCameraByName(name);
  20822. if (camera) {
  20823. this.activeCamera = camera;
  20824. return camera;
  20825. }
  20826. return null;
  20827. };
  20828. /**
  20829. * get a material using its id
  20830. * @param {string} the material's ID
  20831. * @return {BABYLON.Material|null} the material or null if none found.
  20832. */
  20833. Scene.prototype.getMaterialByID = function (id) {
  20834. for (var index = 0; index < this.materials.length; index++) {
  20835. if (this.materials[index].id === id) {
  20836. return this.materials[index];
  20837. }
  20838. }
  20839. return null;
  20840. };
  20841. /**
  20842. * get a material using its name
  20843. * @param {string} the material's name
  20844. * @return {BABYLON.Material|null} the material or null if none found.
  20845. */
  20846. Scene.prototype.getMaterialByName = function (name) {
  20847. for (var index = 0; index < this.materials.length; index++) {
  20848. if (this.materials[index].name === name) {
  20849. return this.materials[index];
  20850. }
  20851. }
  20852. return null;
  20853. };
  20854. Scene.prototype.getLensFlareSystemByName = function (name) {
  20855. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20856. if (this.lensFlareSystems[index].name === name) {
  20857. return this.lensFlareSystems[index];
  20858. }
  20859. }
  20860. return null;
  20861. };
  20862. Scene.prototype.getLensFlareSystemByID = function (id) {
  20863. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20864. if (this.lensFlareSystems[index].id === id) {
  20865. return this.lensFlareSystems[index];
  20866. }
  20867. }
  20868. return null;
  20869. };
  20870. Scene.prototype.getCameraByID = function (id) {
  20871. for (var index = 0; index < this.cameras.length; index++) {
  20872. if (this.cameras[index].id === id) {
  20873. return this.cameras[index];
  20874. }
  20875. }
  20876. return null;
  20877. };
  20878. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20879. for (var index = 0; index < this.cameras.length; index++) {
  20880. if (this.cameras[index].uniqueId === uniqueId) {
  20881. return this.cameras[index];
  20882. }
  20883. }
  20884. return null;
  20885. };
  20886. /**
  20887. * get a camera using its name
  20888. * @param {string} the camera's name
  20889. * @return {BABYLON.Camera|null} the camera or null if none found.
  20890. */
  20891. Scene.prototype.getCameraByName = function (name) {
  20892. for (var index = 0; index < this.cameras.length; index++) {
  20893. if (this.cameras[index].name === name) {
  20894. return this.cameras[index];
  20895. }
  20896. }
  20897. return null;
  20898. };
  20899. /**
  20900. * get a bone using its id
  20901. * @param {string} the bone's id
  20902. * @return {BABYLON.Bone|null} the bone or null if not found
  20903. */
  20904. Scene.prototype.getBoneByID = function (id) {
  20905. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20906. var skeleton = this.skeletons[skeletonIndex];
  20907. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20908. if (skeleton.bones[boneIndex].id === id) {
  20909. return skeleton.bones[boneIndex];
  20910. }
  20911. }
  20912. }
  20913. return null;
  20914. };
  20915. /**
  20916. * get a bone using its id
  20917. * @param {string} the bone's name
  20918. * @return {BABYLON.Bone|null} the bone or null if not found
  20919. */
  20920. Scene.prototype.getBoneByName = function (name) {
  20921. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20922. var skeleton = this.skeletons[skeletonIndex];
  20923. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20924. if (skeleton.bones[boneIndex].name === name) {
  20925. return skeleton.bones[boneIndex];
  20926. }
  20927. }
  20928. }
  20929. return null;
  20930. };
  20931. /**
  20932. * get a light node using its name
  20933. * @param {string} the light's name
  20934. * @return {BABYLON.Light|null} the light or null if none found.
  20935. */
  20936. Scene.prototype.getLightByName = function (name) {
  20937. for (var index = 0; index < this.lights.length; index++) {
  20938. if (this.lights[index].name === name) {
  20939. return this.lights[index];
  20940. }
  20941. }
  20942. return null;
  20943. };
  20944. /**
  20945. * get a light node using its ID
  20946. * @param {string} the light's id
  20947. * @return {BABYLON.Light|null} the light or null if none found.
  20948. */
  20949. Scene.prototype.getLightByID = function (id) {
  20950. for (var index = 0; index < this.lights.length; index++) {
  20951. if (this.lights[index].id === id) {
  20952. return this.lights[index];
  20953. }
  20954. }
  20955. return null;
  20956. };
  20957. /**
  20958. * get a light node using its scene-generated unique ID
  20959. * @param {number} the light's unique id
  20960. * @return {BABYLON.Light|null} the light or null if none found.
  20961. */
  20962. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20963. for (var index = 0; index < this.lights.length; index++) {
  20964. if (this.lights[index].uniqueId === uniqueId) {
  20965. return this.lights[index];
  20966. }
  20967. }
  20968. return null;
  20969. };
  20970. /**
  20971. * get a particle system by id
  20972. * @param id {number} the particle system id
  20973. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  20974. */
  20975. Scene.prototype.getParticleSystemByID = function (id) {
  20976. for (var index = 0; index < this.particleSystems.length; index++) {
  20977. if (this.particleSystems[index].id === id) {
  20978. return this.particleSystems[index];
  20979. }
  20980. }
  20981. return null;
  20982. };
  20983. /**
  20984. * get a geometry using its ID
  20985. * @param {string} the geometry's id
  20986. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20987. */
  20988. Scene.prototype.getGeometryByID = function (id) {
  20989. for (var index = 0; index < this._geometries.length; index++) {
  20990. if (this._geometries[index].id === id) {
  20991. return this._geometries[index];
  20992. }
  20993. }
  20994. return null;
  20995. };
  20996. /**
  20997. * add a new geometry to this scene.
  20998. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20999. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21000. * @return {boolean} was the geometry added or not
  21001. */
  21002. Scene.prototype.pushGeometry = function (geometry, force) {
  21003. if (!force && this.getGeometryByID(geometry.id)) {
  21004. return false;
  21005. }
  21006. this._geometries.push(geometry);
  21007. //notify the collision coordinator
  21008. this.collisionCoordinator.onGeometryAdded(geometry);
  21009. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21010. return true;
  21011. };
  21012. /**
  21013. * Removes an existing geometry
  21014. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21015. * @return {boolean} was the geometry removed or not
  21016. */
  21017. Scene.prototype.removeGeometry = function (geometry) {
  21018. var index = this._geometries.indexOf(geometry);
  21019. if (index > -1) {
  21020. this._geometries.splice(index, 1);
  21021. //notify the collision coordinator
  21022. this.collisionCoordinator.onGeometryDeleted(geometry);
  21023. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21024. return true;
  21025. }
  21026. return false;
  21027. };
  21028. Scene.prototype.getGeometries = function () {
  21029. return this._geometries;
  21030. };
  21031. /**
  21032. * Get the first added mesh found of a given ID
  21033. * @param {string} id - the id to search for
  21034. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21035. */
  21036. Scene.prototype.getMeshByID = function (id) {
  21037. for (var index = 0; index < this.meshes.length; index++) {
  21038. if (this.meshes[index].id === id) {
  21039. return this.meshes[index];
  21040. }
  21041. }
  21042. return null;
  21043. };
  21044. Scene.prototype.getMeshesByID = function (id) {
  21045. return this.meshes.filter(function (m) {
  21046. return m.id === id;
  21047. });
  21048. };
  21049. /**
  21050. * Get a mesh with its auto-generated unique id
  21051. * @param {number} uniqueId - the unique id to search for
  21052. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21053. */
  21054. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21055. for (var index = 0; index < this.meshes.length; index++) {
  21056. if (this.meshes[index].uniqueId === uniqueId) {
  21057. return this.meshes[index];
  21058. }
  21059. }
  21060. return null;
  21061. };
  21062. /**
  21063. * Get a the last added mesh found of a given ID
  21064. * @param {string} id - the id to search for
  21065. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21066. */
  21067. Scene.prototype.getLastMeshByID = function (id) {
  21068. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21069. if (this.meshes[index].id === id) {
  21070. return this.meshes[index];
  21071. }
  21072. }
  21073. return null;
  21074. };
  21075. /**
  21076. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21077. * @param {string} id - the id to search for
  21078. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21079. */
  21080. Scene.prototype.getLastEntryByID = function (id) {
  21081. var index;
  21082. for (index = this.meshes.length - 1; index >= 0; index--) {
  21083. if (this.meshes[index].id === id) {
  21084. return this.meshes[index];
  21085. }
  21086. }
  21087. for (index = this.cameras.length - 1; index >= 0; index--) {
  21088. if (this.cameras[index].id === id) {
  21089. return this.cameras[index];
  21090. }
  21091. }
  21092. for (index = this.lights.length - 1; index >= 0; index--) {
  21093. if (this.lights[index].id === id) {
  21094. return this.lights[index];
  21095. }
  21096. }
  21097. return null;
  21098. };
  21099. Scene.prototype.getNodeByID = function (id) {
  21100. var mesh = this.getMeshByID(id);
  21101. if (mesh) {
  21102. return mesh;
  21103. }
  21104. var light = this.getLightByID(id);
  21105. if (light) {
  21106. return light;
  21107. }
  21108. var camera = this.getCameraByID(id);
  21109. if (camera) {
  21110. return camera;
  21111. }
  21112. var bone = this.getBoneByID(id);
  21113. return bone;
  21114. };
  21115. Scene.prototype.getNodeByName = function (name) {
  21116. var mesh = this.getMeshByName(name);
  21117. if (mesh) {
  21118. return mesh;
  21119. }
  21120. var light = this.getLightByName(name);
  21121. if (light) {
  21122. return light;
  21123. }
  21124. var camera = this.getCameraByName(name);
  21125. if (camera) {
  21126. return camera;
  21127. }
  21128. var bone = this.getBoneByName(name);
  21129. return bone;
  21130. };
  21131. Scene.prototype.getMeshByName = function (name) {
  21132. for (var index = 0; index < this.meshes.length; index++) {
  21133. if (this.meshes[index].name === name) {
  21134. return this.meshes[index];
  21135. }
  21136. }
  21137. return null;
  21138. };
  21139. Scene.prototype.getSoundByName = function (name) {
  21140. var index;
  21141. if (BABYLON.AudioEngine) {
  21142. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21143. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21144. return this.mainSoundTrack.soundCollection[index];
  21145. }
  21146. }
  21147. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21148. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21149. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21150. return this.soundTracks[sdIndex].soundCollection[index];
  21151. }
  21152. }
  21153. }
  21154. }
  21155. return null;
  21156. };
  21157. Scene.prototype.getLastSkeletonByID = function (id) {
  21158. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21159. if (this.skeletons[index].id === id) {
  21160. return this.skeletons[index];
  21161. }
  21162. }
  21163. return null;
  21164. };
  21165. Scene.prototype.getSkeletonById = function (id) {
  21166. for (var index = 0; index < this.skeletons.length; index++) {
  21167. if (this.skeletons[index].id === id) {
  21168. return this.skeletons[index];
  21169. }
  21170. }
  21171. return null;
  21172. };
  21173. Scene.prototype.getSkeletonByName = function (name) {
  21174. for (var index = 0; index < this.skeletons.length; index++) {
  21175. if (this.skeletons[index].name === name) {
  21176. return this.skeletons[index];
  21177. }
  21178. }
  21179. return null;
  21180. };
  21181. Scene.prototype.isActiveMesh = function (mesh) {
  21182. return (this._activeMeshes.indexOf(mesh) !== -1);
  21183. };
  21184. /**
  21185. * Return a the first highlight layer of the scene with a given name.
  21186. * @param name The name of the highlight layer to look for.
  21187. * @return The highlight layer if found otherwise null.
  21188. */
  21189. Scene.prototype.getHighlightLayerByName = function (name) {
  21190. for (var index = 0; index < this.highlightLayers.length; index++) {
  21191. if (this.highlightLayers[index].name === name) {
  21192. return this.highlightLayers[index];
  21193. }
  21194. }
  21195. return null;
  21196. };
  21197. Object.defineProperty(Scene.prototype, "uid", {
  21198. /**
  21199. * Return a unique id as a string which can serve as an identifier for the scene
  21200. */
  21201. get: function () {
  21202. if (!this._uid) {
  21203. this._uid = BABYLON.Tools.RandomId();
  21204. }
  21205. return this._uid;
  21206. },
  21207. enumerable: true,
  21208. configurable: true
  21209. });
  21210. /**
  21211. * Add an externaly attached data from its key.
  21212. * This method call will fail and return false, if such key already exists.
  21213. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21214. * @param key the unique key that identifies the data
  21215. * @param data the data object to associate to the key for this Engine instance
  21216. * @return true if no such key were already present and the data was added successfully, false otherwise
  21217. */
  21218. Scene.prototype.addExternalData = function (key, data) {
  21219. return this._externalData.add(key, data);
  21220. };
  21221. /**
  21222. * Get an externaly attached data from its key
  21223. * @param key the unique key that identifies the data
  21224. * @return the associated data, if present (can be null), or undefined if not present
  21225. */
  21226. Scene.prototype.getExternalData = function (key) {
  21227. return this._externalData.get(key);
  21228. };
  21229. /**
  21230. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21231. * @param key the unique key that identifies the data
  21232. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21233. * @return the associated data, can be null if the factory returned null.
  21234. */
  21235. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21236. return this._externalData.getOrAddWithFactory(key, factory);
  21237. };
  21238. /**
  21239. * Remove an externaly attached data from the Engine instance
  21240. * @param key the unique key that identifies the data
  21241. * @return true if the data was successfully removed, false if it doesn't exist
  21242. */
  21243. Scene.prototype.removeExternalData = function (key) {
  21244. return this._externalData.remove(key);
  21245. };
  21246. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21247. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21248. var material = subMesh.getMaterial();
  21249. if (mesh.showSubMeshesBoundingBox) {
  21250. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  21251. }
  21252. if (material) {
  21253. // Render targets
  21254. if (material.getRenderTargetTextures) {
  21255. if (this._processedMaterials.indexOf(material) === -1) {
  21256. this._processedMaterials.push(material);
  21257. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21258. }
  21259. }
  21260. // Dispatch
  21261. this._activeIndices.addCount(subMesh.indexCount, false);
  21262. this._renderingManager.dispatch(subMesh);
  21263. }
  21264. }
  21265. };
  21266. Scene.prototype._isInIntermediateRendering = function () {
  21267. return this._intermediateRendering;
  21268. };
  21269. Scene.prototype._evaluateActiveMeshes = function () {
  21270. this.activeCamera._activeMeshes.reset();
  21271. this._activeMeshes.reset();
  21272. this._renderingManager.reset();
  21273. this._processedMaterials.reset();
  21274. this._activeParticleSystems.reset();
  21275. this._activeSkeletons.reset();
  21276. this._softwareSkinnedMeshes.reset();
  21277. this._boundingBoxRenderer.reset();
  21278. this._edgesRenderers.reset();
  21279. // Meshes
  21280. var meshes;
  21281. var len;
  21282. if (this._selectionOctree) {
  21283. var selection = this._selectionOctree.select(this._frustumPlanes);
  21284. meshes = selection.data;
  21285. len = selection.length;
  21286. }
  21287. else {
  21288. len = this.meshes.length;
  21289. meshes = this.meshes;
  21290. }
  21291. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  21292. var mesh = meshes[meshIndex];
  21293. if (mesh.isBlocked) {
  21294. continue;
  21295. }
  21296. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21297. if (!mesh.isReady() || !mesh.isEnabled()) {
  21298. continue;
  21299. }
  21300. mesh.computeWorldMatrix();
  21301. // Intersections
  21302. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21303. this._meshesForIntersections.pushNoDuplicate(mesh);
  21304. }
  21305. // Switch to current LOD
  21306. var meshLOD = mesh.getLOD(this.activeCamera);
  21307. if (!meshLOD) {
  21308. continue;
  21309. }
  21310. mesh._preActivate();
  21311. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21312. this._activeMeshes.push(mesh);
  21313. this.activeCamera._activeMeshes.push(mesh);
  21314. mesh._activate(this._renderId);
  21315. this._activeMesh(mesh, meshLOD);
  21316. }
  21317. }
  21318. // Particle systems
  21319. this._particlesDuration.beginMonitoring();
  21320. var beforeParticlesDate = BABYLON.Tools.Now;
  21321. if (this.particlesEnabled) {
  21322. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  21323. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21324. var particleSystem = this.particleSystems[particleIndex];
  21325. if (!particleSystem.isStarted()) {
  21326. continue;
  21327. }
  21328. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  21329. this._activeParticleSystems.push(particleSystem);
  21330. particleSystem.animate();
  21331. this._renderingManager.dispatchParticles(particleSystem);
  21332. }
  21333. }
  21334. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  21335. }
  21336. this._particlesDuration.endMonitoring(false);
  21337. };
  21338. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21339. if (mesh.skeleton && this.skeletonsEnabled) {
  21340. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21341. mesh.skeleton.prepare();
  21342. }
  21343. if (!mesh.computeBonesUsingShaders) {
  21344. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21345. }
  21346. }
  21347. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21348. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  21349. }
  21350. if (sourceMesh._edgesRenderer) {
  21351. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  21352. }
  21353. if (mesh && mesh.subMeshes) {
  21354. // Submeshes Octrees
  21355. var len;
  21356. var subMeshes;
  21357. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  21358. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21359. len = intersections.length;
  21360. subMeshes = intersections.data;
  21361. }
  21362. else {
  21363. subMeshes = mesh.subMeshes;
  21364. len = subMeshes.length;
  21365. }
  21366. for (var subIndex = 0; subIndex < len; subIndex++) {
  21367. var subMesh = subMeshes[subIndex];
  21368. this._evaluateSubMesh(subMesh, mesh);
  21369. }
  21370. }
  21371. };
  21372. Scene.prototype.updateTransformMatrix = function (force) {
  21373. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21374. };
  21375. Scene.prototype._renderForCamera = function (camera) {
  21376. var engine = this._engine;
  21377. var startTime = BABYLON.Tools.Now;
  21378. this.activeCamera = camera;
  21379. if (!this.activeCamera)
  21380. throw new Error("Active camera not set");
  21381. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21382. // Viewport
  21383. engine.setViewport(this.activeCamera.viewport);
  21384. // Camera
  21385. this.resetCachedMaterial();
  21386. this._renderId++;
  21387. this.updateTransformMatrix();
  21388. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21389. // Meshes
  21390. this._evaluateActiveMeshesDuration.beginMonitoring();
  21391. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  21392. this._evaluateActiveMeshes();
  21393. this._evaluateActiveMeshesDuration.endMonitoring(false);
  21394. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  21395. // Software skinning
  21396. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21397. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21398. mesh.applySkeleton(mesh.skeleton);
  21399. }
  21400. // Render targets
  21401. this._renderTargetsDuration.beginMonitoring();
  21402. var needsRestoreFrameBuffer = false;
  21403. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21404. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21405. this._intermediateRendering = true;
  21406. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21407. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21408. var renderTarget = this._renderTargets.data[renderIndex];
  21409. if (renderTarget._shouldRender()) {
  21410. this._renderId++;
  21411. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21412. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21413. }
  21414. }
  21415. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21416. this._intermediateRendering = false;
  21417. this._renderId++;
  21418. needsRestoreFrameBuffer = true; // Restore back buffer
  21419. }
  21420. // Render HighlightLayer Texture
  21421. var stencilState = this._engine.getStencilBuffer();
  21422. var renderhighlights = false;
  21423. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21424. this._intermediateRendering = true;
  21425. for (var i = 0; i < this.highlightLayers.length; i++) {
  21426. var highlightLayer = this.highlightLayers[i];
  21427. if (highlightLayer.shouldRender() &&
  21428. (!highlightLayer.camera ||
  21429. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  21430. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  21431. renderhighlights = true;
  21432. var renderTarget = highlightLayer._mainTexture;
  21433. if (renderTarget._shouldRender()) {
  21434. this._renderId++;
  21435. renderTarget.render(false, false);
  21436. needsRestoreFrameBuffer = true;
  21437. }
  21438. }
  21439. }
  21440. this._intermediateRendering = false;
  21441. this._renderId++;
  21442. }
  21443. if (needsRestoreFrameBuffer) {
  21444. engine.restoreDefaultFramebuffer();
  21445. }
  21446. this._renderTargetsDuration.endMonitoring(false);
  21447. // Prepare Frame
  21448. this.postProcessManager._prepareFrame();
  21449. this._renderDuration.beginMonitoring();
  21450. // Backgrounds
  21451. var layerIndex;
  21452. var layer;
  21453. if (this.layers.length) {
  21454. engine.setDepthBuffer(false);
  21455. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21456. layer = this.layers[layerIndex];
  21457. if (layer.isBackground) {
  21458. layer.render();
  21459. }
  21460. }
  21461. engine.setDepthBuffer(true);
  21462. }
  21463. // Render
  21464. BABYLON.Tools.StartPerformanceCounter("Main render");
  21465. // Activate HighlightLayer stencil
  21466. if (renderhighlights) {
  21467. this._engine.setStencilBuffer(true);
  21468. }
  21469. this._renderingManager.render(null, null, true, true);
  21470. // Restore HighlightLayer stencil
  21471. if (renderhighlights) {
  21472. this._engine.setStencilBuffer(stencilState);
  21473. }
  21474. BABYLON.Tools.EndPerformanceCounter("Main render");
  21475. // Bounding boxes
  21476. this._boundingBoxRenderer.render();
  21477. // Edges
  21478. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21479. this._edgesRenderers.data[edgesRendererIndex].render();
  21480. }
  21481. // Lens flares
  21482. if (this.lensFlaresEnabled) {
  21483. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21484. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  21485. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  21486. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  21487. lensFlareSystem.render();
  21488. }
  21489. }
  21490. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  21491. }
  21492. // Foregrounds
  21493. if (this.layers.length) {
  21494. engine.setDepthBuffer(false);
  21495. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  21496. layer = this.layers[layerIndex];
  21497. if (!layer.isBackground) {
  21498. layer.render();
  21499. }
  21500. }
  21501. engine.setDepthBuffer(true);
  21502. }
  21503. // Highlight Layer
  21504. if (renderhighlights) {
  21505. engine.setDepthBuffer(false);
  21506. for (var i = 0; i < this.highlightLayers.length; i++) {
  21507. if (this.highlightLayers[i].shouldRender()) {
  21508. this.highlightLayers[i].render();
  21509. }
  21510. }
  21511. engine.setDepthBuffer(true);
  21512. }
  21513. this._renderDuration.endMonitoring(false);
  21514. // Finalize frame
  21515. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21516. // Update camera
  21517. this.activeCamera._updateFromScene();
  21518. // Reset some special arrays
  21519. this._renderTargets.reset();
  21520. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21521. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21522. };
  21523. Scene.prototype._processSubCameras = function (camera) {
  21524. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21525. this._renderForCamera(camera);
  21526. return;
  21527. }
  21528. // rig cameras
  21529. for (var index = 0; index < camera._rigCameras.length; index++) {
  21530. this._renderForCamera(camera._rigCameras[index]);
  21531. }
  21532. this.activeCamera = camera;
  21533. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21534. // Update camera
  21535. this.activeCamera._updateFromScene();
  21536. };
  21537. Scene.prototype._checkIntersections = function () {
  21538. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21539. var sourceMesh = this._meshesForIntersections.data[index];
  21540. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21541. var action = sourceMesh.actionManager.actions[actionIndex];
  21542. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21543. var parameters = action.getTriggerParameter();
  21544. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21545. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21546. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21547. if (areIntersecting && currentIntersectionInProgress === -1) {
  21548. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21549. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21550. sourceMesh._intersectionsInProgress.push(otherMesh);
  21551. }
  21552. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21553. sourceMesh._intersectionsInProgress.push(otherMesh);
  21554. }
  21555. }
  21556. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21557. //They intersected, and now they don't.
  21558. //is this trigger an exit trigger? execute an event.
  21559. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21560. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  21561. }
  21562. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21563. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21564. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21565. }
  21566. }
  21567. }
  21568. }
  21569. }
  21570. };
  21571. Scene.prototype.render = function () {
  21572. if (this.isDisposed) {
  21573. return;
  21574. }
  21575. this._lastFrameDuration.beginMonitoring();
  21576. this._particlesDuration.fetchNewFrame();
  21577. this._spritesDuration.fetchNewFrame();
  21578. this._activeParticles.fetchNewFrame();
  21579. this._renderDuration.fetchNewFrame();
  21580. this._renderTargetsDuration.fetchNewFrame();
  21581. this._evaluateActiveMeshesDuration.fetchNewFrame();
  21582. this._totalVertices.fetchNewFrame();
  21583. this._activeIndices.fetchNewFrame();
  21584. this._activeBones.fetchNewFrame();
  21585. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  21586. this._meshesForIntersections.reset();
  21587. this.resetCachedMaterial();
  21588. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  21589. // Actions
  21590. if (this.actionManager) {
  21591. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  21592. }
  21593. //Simplification Queue
  21594. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21595. this.simplificationQueue.executeNext();
  21596. }
  21597. // Animations
  21598. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  21599. this._animationRatio = deltaTime * (60.0 / 1000.0);
  21600. this._animate();
  21601. // Physics
  21602. if (this._physicsEngine) {
  21603. BABYLON.Tools.StartPerformanceCounter("Physics");
  21604. this._physicsEngine._step(deltaTime / 1000.0);
  21605. BABYLON.Tools.EndPerformanceCounter("Physics");
  21606. }
  21607. // Before render
  21608. this.onBeforeRenderObservable.notifyObservers(this);
  21609. // Customs render targets
  21610. this._renderTargetsDuration.beginMonitoring();
  21611. var beforeRenderTargetDate = BABYLON.Tools.Now;
  21612. var engine = this.getEngine();
  21613. var currentActiveCamera = this.activeCamera;
  21614. if (this.renderTargetsEnabled) {
  21615. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21616. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  21617. var renderTarget = this.customRenderTargets[customIndex];
  21618. if (renderTarget._shouldRender()) {
  21619. this._renderId++;
  21620. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  21621. if (!this.activeCamera)
  21622. throw new Error("Active camera not set");
  21623. // Viewport
  21624. engine.setViewport(this.activeCamera.viewport);
  21625. // Camera
  21626. this.updateTransformMatrix();
  21627. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  21628. }
  21629. }
  21630. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21631. this._renderId++;
  21632. }
  21633. if (this.customRenderTargets.length > 0) {
  21634. engine.restoreDefaultFramebuffer();
  21635. }
  21636. this._renderTargetsDuration.endMonitoring();
  21637. this.activeCamera = currentActiveCamera;
  21638. // Procedural textures
  21639. if (this.proceduralTexturesEnabled) {
  21640. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21641. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21642. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21643. if (proceduralTexture._shouldRender()) {
  21644. proceduralTexture.render();
  21645. }
  21646. }
  21647. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21648. }
  21649. // Clear
  21650. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  21651. // Shadows
  21652. if (this.shadowsEnabled) {
  21653. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21654. var light = this.lights[lightIndex];
  21655. var shadowGenerator = light.getShadowGenerator();
  21656. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  21657. this._renderTargets.push(shadowGenerator.getShadowMap());
  21658. }
  21659. }
  21660. }
  21661. // Depth renderer
  21662. if (this._depthRenderer) {
  21663. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21664. }
  21665. // RenderPipeline
  21666. this.postProcessRenderPipelineManager.update();
  21667. // Multi-cameras?
  21668. if (this.activeCameras.length > 0) {
  21669. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21670. if (cameraIndex > 0) {
  21671. this._engine.clear(null, false, true, true);
  21672. }
  21673. this._processSubCameras(this.activeCameras[cameraIndex]);
  21674. }
  21675. }
  21676. else {
  21677. if (!this.activeCamera) {
  21678. throw new Error("No camera defined");
  21679. }
  21680. this._processSubCameras(this.activeCamera);
  21681. }
  21682. // Intersection checks
  21683. this._checkIntersections();
  21684. // Update the audio listener attached to the camera
  21685. if (BABYLON.AudioEngine) {
  21686. this._updateAudioParameters();
  21687. }
  21688. // After render
  21689. if (this.afterRender) {
  21690. this.afterRender();
  21691. }
  21692. this.onAfterRenderObservable.notifyObservers(this);
  21693. // Cleaning
  21694. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21695. this._toBeDisposed.data[index].dispose();
  21696. this._toBeDisposed[index] = null;
  21697. }
  21698. this._toBeDisposed.reset();
  21699. if (this.dumpNextRenderTargets) {
  21700. this.dumpNextRenderTargets = false;
  21701. }
  21702. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  21703. this._lastFrameDuration.endMonitoring();
  21704. this._totalMeshesCounter.addCount(this.meshes.length, true);
  21705. this._totalLightsCounter.addCount(this.lights.length, true);
  21706. this._totalMaterialsCounter.addCount(this.materials.length, true);
  21707. this._totalTexturesCounter.addCount(this.textures.length, true);
  21708. this._activeBones.addCount(0, true);
  21709. this._activeIndices.addCount(0, true);
  21710. this._activeParticles.addCount(0, true);
  21711. };
  21712. Scene.prototype._updateAudioParameters = function () {
  21713. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21714. return;
  21715. }
  21716. var listeningCamera;
  21717. var audioEngine = BABYLON.Engine.audioEngine;
  21718. if (this.activeCameras.length > 0) {
  21719. listeningCamera = this.activeCameras[0];
  21720. }
  21721. else {
  21722. listeningCamera = this.activeCamera;
  21723. }
  21724. if (listeningCamera && audioEngine.canUseWebAudio) {
  21725. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21726. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21727. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21728. cameraDirection.normalize();
  21729. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21730. var i;
  21731. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21732. var sound = this.mainSoundTrack.soundCollection[i];
  21733. if (sound.useCustomAttenuation) {
  21734. sound.updateDistanceFromListener();
  21735. }
  21736. }
  21737. for (i = 0; i < this.soundTracks.length; i++) {
  21738. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21739. sound = this.soundTracks[i].soundCollection[j];
  21740. if (sound.useCustomAttenuation) {
  21741. sound.updateDistanceFromListener();
  21742. }
  21743. }
  21744. }
  21745. }
  21746. };
  21747. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21748. // Audio
  21749. get: function () {
  21750. return this._audioEnabled;
  21751. },
  21752. set: function (value) {
  21753. this._audioEnabled = value;
  21754. if (BABYLON.AudioEngine) {
  21755. if (this._audioEnabled) {
  21756. this._enableAudio();
  21757. }
  21758. else {
  21759. this._disableAudio();
  21760. }
  21761. }
  21762. },
  21763. enumerable: true,
  21764. configurable: true
  21765. });
  21766. Scene.prototype._disableAudio = function () {
  21767. var i;
  21768. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21769. this.mainSoundTrack.soundCollection[i].pause();
  21770. }
  21771. for (i = 0; i < this.soundTracks.length; i++) {
  21772. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21773. this.soundTracks[i].soundCollection[j].pause();
  21774. }
  21775. }
  21776. };
  21777. Scene.prototype._enableAudio = function () {
  21778. var i;
  21779. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21780. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21781. this.mainSoundTrack.soundCollection[i].play();
  21782. }
  21783. }
  21784. for (i = 0; i < this.soundTracks.length; i++) {
  21785. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21786. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21787. this.soundTracks[i].soundCollection[j].play();
  21788. }
  21789. }
  21790. }
  21791. };
  21792. Object.defineProperty(Scene.prototype, "headphone", {
  21793. get: function () {
  21794. return this._headphone;
  21795. },
  21796. set: function (value) {
  21797. this._headphone = value;
  21798. if (BABYLON.AudioEngine) {
  21799. if (this._headphone) {
  21800. this._switchAudioModeForHeadphones();
  21801. }
  21802. else {
  21803. this._switchAudioModeForNormalSpeakers();
  21804. }
  21805. }
  21806. },
  21807. enumerable: true,
  21808. configurable: true
  21809. });
  21810. Scene.prototype._switchAudioModeForHeadphones = function () {
  21811. this.mainSoundTrack.switchPanningModelToHRTF();
  21812. for (var i = 0; i < this.soundTracks.length; i++) {
  21813. this.soundTracks[i].switchPanningModelToHRTF();
  21814. }
  21815. };
  21816. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21817. this.mainSoundTrack.switchPanningModelToEqualPower();
  21818. for (var i = 0; i < this.soundTracks.length; i++) {
  21819. this.soundTracks[i].switchPanningModelToEqualPower();
  21820. }
  21821. };
  21822. Scene.prototype.enableDepthRenderer = function () {
  21823. if (this._depthRenderer) {
  21824. return this._depthRenderer;
  21825. }
  21826. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21827. return this._depthRenderer;
  21828. };
  21829. Scene.prototype.disableDepthRenderer = function () {
  21830. if (!this._depthRenderer) {
  21831. return;
  21832. }
  21833. this._depthRenderer.dispose();
  21834. this._depthRenderer = null;
  21835. };
  21836. Scene.prototype.freezeMaterials = function () {
  21837. for (var i = 0; i < this.materials.length; i++) {
  21838. this.materials[i].freeze();
  21839. }
  21840. };
  21841. Scene.prototype.unfreezeMaterials = function () {
  21842. for (var i = 0; i < this.materials.length; i++) {
  21843. this.materials[i].unfreeze();
  21844. }
  21845. };
  21846. Scene.prototype.dispose = function () {
  21847. this.beforeRender = null;
  21848. this.afterRender = null;
  21849. this.skeletons = [];
  21850. this._boundingBoxRenderer.dispose();
  21851. if (this._depthRenderer) {
  21852. this._depthRenderer.dispose();
  21853. }
  21854. // Smart arrays
  21855. if (this.activeCamera) {
  21856. this.activeCamera._activeMeshes.dispose();
  21857. this.activeCamera = null;
  21858. }
  21859. this._activeMeshes.dispose();
  21860. this._renderingManager.dispose();
  21861. this._processedMaterials.dispose();
  21862. this._activeParticleSystems.dispose();
  21863. this._activeSkeletons.dispose();
  21864. this._softwareSkinnedMeshes.dispose();
  21865. this._boundingBoxRenderer.dispose();
  21866. this._edgesRenderers.dispose();
  21867. this._meshesForIntersections.dispose();
  21868. this._toBeDisposed.dispose();
  21869. // Debug layer
  21870. if (this._debugLayer) {
  21871. this._debugLayer.hide();
  21872. }
  21873. // Events
  21874. this.onDisposeObservable.notifyObservers(this);
  21875. this.onDisposeObservable.clear();
  21876. this.onBeforeRenderObservable.clear();
  21877. this.onAfterRenderObservable.clear();
  21878. this.detachControl();
  21879. // Release sounds & sounds tracks
  21880. if (BABYLON.AudioEngine) {
  21881. this.disposeSounds();
  21882. }
  21883. // Detach cameras
  21884. var canvas = this._engine.getRenderingCanvas();
  21885. var index;
  21886. for (index = 0; index < this.cameras.length; index++) {
  21887. this.cameras[index].detachControl(canvas);
  21888. }
  21889. // Release lights
  21890. while (this.lights.length) {
  21891. this.lights[0].dispose();
  21892. }
  21893. // Release meshes
  21894. while (this.meshes.length) {
  21895. this.meshes[0].dispose(true);
  21896. }
  21897. // Release cameras
  21898. while (this.cameras.length) {
  21899. this.cameras[0].dispose();
  21900. }
  21901. // Release materials
  21902. while (this.materials.length) {
  21903. this.materials[0].dispose();
  21904. }
  21905. // Release particles
  21906. while (this.particleSystems.length) {
  21907. this.particleSystems[0].dispose();
  21908. }
  21909. // Release sprites
  21910. while (this.spriteManagers.length) {
  21911. this.spriteManagers[0].dispose();
  21912. }
  21913. // Release layers
  21914. while (this.layers.length) {
  21915. this.layers[0].dispose();
  21916. }
  21917. while (this.highlightLayers.length) {
  21918. this.highlightLayers[0].dispose();
  21919. }
  21920. // Release textures
  21921. while (this.textures.length) {
  21922. this.textures[0].dispose();
  21923. }
  21924. // Post-processes
  21925. this.postProcessManager.dispose();
  21926. // Physics
  21927. if (this._physicsEngine) {
  21928. this.disablePhysicsEngine();
  21929. }
  21930. // Remove from engine
  21931. index = this._engine.scenes.indexOf(this);
  21932. if (index > -1) {
  21933. this._engine.scenes.splice(index, 1);
  21934. }
  21935. this._engine.wipeCaches();
  21936. this._engine = null;
  21937. };
  21938. Object.defineProperty(Scene.prototype, "isDisposed", {
  21939. get: function () {
  21940. return !this._engine;
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. // Release sounds & sounds tracks
  21946. Scene.prototype.disposeSounds = function () {
  21947. this.mainSoundTrack.dispose();
  21948. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21949. this.soundTracks[scIndex].dispose();
  21950. }
  21951. };
  21952. // Octrees
  21953. Scene.prototype.getWorldExtends = function () {
  21954. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21955. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21956. for (var index = 0; index < this.meshes.length; index++) {
  21957. var mesh = this.meshes[index];
  21958. mesh.computeWorldMatrix(true);
  21959. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  21960. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  21961. BABYLON.Tools.CheckExtends(minBox, min, max);
  21962. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21963. }
  21964. return {
  21965. min: min,
  21966. max: max
  21967. };
  21968. };
  21969. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21970. if (maxCapacity === void 0) { maxCapacity = 64; }
  21971. if (maxDepth === void 0) { maxDepth = 2; }
  21972. if (!this._selectionOctree) {
  21973. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21974. }
  21975. var worldExtends = this.getWorldExtends();
  21976. // Update octree
  21977. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21978. return this._selectionOctree;
  21979. };
  21980. // Picking
  21981. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21982. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21983. var engine = this._engine;
  21984. if (!camera) {
  21985. if (!this.activeCamera)
  21986. throw new Error("Active camera not set");
  21987. camera = this.activeCamera;
  21988. }
  21989. var cameraViewport = camera.viewport;
  21990. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21991. // Moving coordinates to local viewport world
  21992. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21993. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21994. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21995. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  21996. };
  21997. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21998. var engine = this._engine;
  21999. if (!camera) {
  22000. if (!this.activeCamera)
  22001. throw new Error("Active camera not set");
  22002. camera = this.activeCamera;
  22003. }
  22004. var cameraViewport = camera.viewport;
  22005. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22006. var identity = BABYLON.Matrix.Identity();
  22007. // Moving coordinates to local viewport world
  22008. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22009. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22010. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22011. };
  22012. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22013. var pickingInfo = null;
  22014. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22015. var mesh = this.meshes[meshIndex];
  22016. if (predicate) {
  22017. if (!predicate(mesh)) {
  22018. continue;
  22019. }
  22020. }
  22021. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22022. continue;
  22023. }
  22024. var world = mesh.getWorldMatrix();
  22025. var ray = rayFunction(world);
  22026. var result = mesh.intersects(ray, fastCheck);
  22027. if (!result || !result.hit)
  22028. continue;
  22029. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22030. continue;
  22031. pickingInfo = result;
  22032. if (fastCheck) {
  22033. break;
  22034. }
  22035. }
  22036. return pickingInfo || new BABYLON.PickingInfo();
  22037. };
  22038. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22039. var pickingInfos = new Array();
  22040. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22041. var mesh = this.meshes[meshIndex];
  22042. if (predicate) {
  22043. if (!predicate(mesh)) {
  22044. continue;
  22045. }
  22046. }
  22047. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22048. continue;
  22049. }
  22050. var world = mesh.getWorldMatrix();
  22051. var ray = rayFunction(world);
  22052. var result = mesh.intersects(ray, false);
  22053. if (!result || !result.hit)
  22054. continue;
  22055. pickingInfos.push(result);
  22056. }
  22057. return pickingInfos;
  22058. };
  22059. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22060. var pickingInfo = null;
  22061. camera = camera || this.activeCamera;
  22062. if (this.spriteManagers.length > 0) {
  22063. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22064. var spriteManager = this.spriteManagers[spriteIndex];
  22065. if (!spriteManager.isPickable) {
  22066. continue;
  22067. }
  22068. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22069. if (!result || !result.hit)
  22070. continue;
  22071. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22072. continue;
  22073. pickingInfo = result;
  22074. if (fastCheck) {
  22075. break;
  22076. }
  22077. }
  22078. }
  22079. return pickingInfo || new BABYLON.PickingInfo();
  22080. };
  22081. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22082. /// <param name="x">X position on screen</param>
  22083. /// <param name="y">Y position on screen</param>
  22084. /// <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>
  22085. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22086. /// <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>
  22087. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22088. var _this = this;
  22089. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  22090. };
  22091. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22092. /// <param name="x">X position on screen</param>
  22093. /// <param name="y">Y position on screen</param>
  22094. /// <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>
  22095. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  22096. /// <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>
  22097. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22098. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  22099. };
  22100. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22101. var _this = this;
  22102. return this._internalPick(function (world) {
  22103. if (!_this._pickWithRayInverseMatrix) {
  22104. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22105. }
  22106. world.invertToRef(_this._pickWithRayInverseMatrix);
  22107. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22108. }, predicate, fastCheck);
  22109. };
  22110. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22111. /// <param name="x">X position on screen</param>
  22112. /// <param name="y">Y position on screen</param>
  22113. /// <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>
  22114. /// <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>
  22115. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22116. var _this = this;
  22117. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  22118. };
  22119. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  22120. /// <param name="ray">Ray to use</param>
  22121. /// <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>
  22122. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22123. var _this = this;
  22124. return this._internalMultiPick(function (world) {
  22125. if (!_this._pickWithRayInverseMatrix) {
  22126. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22127. }
  22128. world.invertToRef(_this._pickWithRayInverseMatrix);
  22129. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  22130. }, predicate);
  22131. };
  22132. Scene.prototype.setPointerOverMesh = function (mesh) {
  22133. if (this._pointerOverMesh === mesh) {
  22134. return;
  22135. }
  22136. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22137. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22138. }
  22139. this._pointerOverMesh = mesh;
  22140. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22141. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22142. }
  22143. };
  22144. Scene.prototype.getPointerOverMesh = function () {
  22145. return this._pointerOverMesh;
  22146. };
  22147. Scene.prototype.setPointerOverSprite = function (sprite) {
  22148. if (this._pointerOverSprite === sprite) {
  22149. return;
  22150. }
  22151. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22152. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22153. }
  22154. this._pointerOverSprite = sprite;
  22155. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22156. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22157. }
  22158. };
  22159. Scene.prototype.getPointerOverSprite = function () {
  22160. return this._pointerOverSprite;
  22161. };
  22162. // Physics
  22163. Scene.prototype.getPhysicsEngine = function () {
  22164. return this._physicsEngine;
  22165. };
  22166. /**
  22167. * Enables physics to the current scene
  22168. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22169. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22170. * @return {boolean} was the physics engine initialized
  22171. */
  22172. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22173. if (this._physicsEngine) {
  22174. return true;
  22175. }
  22176. try {
  22177. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22178. return true;
  22179. }
  22180. catch (e) {
  22181. BABYLON.Tools.Error(e.message);
  22182. return false;
  22183. }
  22184. };
  22185. Scene.prototype.disablePhysicsEngine = function () {
  22186. if (!this._physicsEngine) {
  22187. return;
  22188. }
  22189. this._physicsEngine.dispose();
  22190. this._physicsEngine = undefined;
  22191. };
  22192. Scene.prototype.isPhysicsEnabled = function () {
  22193. return this._physicsEngine !== undefined;
  22194. };
  22195. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22196. var mesh = compound.parts[0].mesh;
  22197. mesh.physicsImpostor.dispose();
  22198. mesh.physicsImpostor = null;
  22199. };
  22200. // Misc.
  22201. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  22202. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  22203. // Light
  22204. if (this.lights.length === 0) {
  22205. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  22206. }
  22207. // Camera
  22208. if (!this.activeCamera) {
  22209. // Compute position
  22210. var worldExtends = this.getWorldExtends();
  22211. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  22212. var camera;
  22213. if (createArcRotateCamera) {
  22214. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  22215. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  22216. camera.setTarget(worldCenter);
  22217. }
  22218. else {
  22219. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  22220. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  22221. camera.setTarget(worldCenter);
  22222. }
  22223. this.activeCamera = camera;
  22224. }
  22225. };
  22226. // Tags
  22227. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22228. if (tagsQuery === undefined) {
  22229. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22230. return list;
  22231. }
  22232. var listByTags = [];
  22233. forEach = forEach || (function (item) { return; });
  22234. for (var i in list) {
  22235. var item = list[i];
  22236. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22237. listByTags.push(item);
  22238. forEach(item);
  22239. }
  22240. }
  22241. return listByTags;
  22242. };
  22243. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22244. return this._getByTags(this.meshes, tagsQuery, forEach);
  22245. };
  22246. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22247. return this._getByTags(this.cameras, tagsQuery, forEach);
  22248. };
  22249. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22250. return this._getByTags(this.lights, tagsQuery, forEach);
  22251. };
  22252. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22253. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22254. };
  22255. /**
  22256. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22257. * This allowed control for front to back rendering or reversly depending of the special needs.
  22258. *
  22259. * @param renderingGroupId The rendering group id corresponding to its index
  22260. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22261. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22262. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22263. */
  22264. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22265. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22266. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22267. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22268. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22269. };
  22270. /**
  22271. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22272. *
  22273. * @param renderingGroupId The rendering group id corresponding to its index
  22274. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22275. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22276. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22277. */
  22278. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22279. if (depth === void 0) { depth = true; }
  22280. if (stencil === void 0) { stencil = true; }
  22281. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22282. };
  22283. return Scene;
  22284. }());
  22285. // Statics
  22286. Scene._FOGMODE_NONE = 0;
  22287. Scene._FOGMODE_EXP = 1;
  22288. Scene._FOGMODE_EXP2 = 2;
  22289. Scene._FOGMODE_LINEAR = 3;
  22290. Scene.MinDeltaTime = 1.0;
  22291. Scene.MaxDeltaTime = 1000.0;
  22292. Scene.DragMovementThreshold = 10; // in pixels
  22293. Scene.LongPressDelay = 500; // in milliseconds
  22294. Scene.DoubleClickDelay = 300; // in milliseconds
  22295. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  22296. BABYLON.Scene = Scene;
  22297. })(BABYLON || (BABYLON = {}));
  22298. //# sourceMappingURL=babylon.scene.js.map
  22299. var BABYLON;
  22300. (function (BABYLON) {
  22301. var Buffer = (function () {
  22302. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  22303. if (engine instanceof BABYLON.Mesh) {
  22304. this._engine = engine.getScene().getEngine();
  22305. }
  22306. else {
  22307. this._engine = engine;
  22308. }
  22309. this._updatable = updatable;
  22310. this._data = data;
  22311. this._strideSize = stride;
  22312. if (!postponeInternalCreation) {
  22313. this.create();
  22314. }
  22315. this._instanced = instanced;
  22316. }
  22317. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  22318. // a lot of these parameters are ignored as they are overriden by the buffer
  22319. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  22320. };
  22321. // Properties
  22322. Buffer.prototype.isUpdatable = function () {
  22323. return this._updatable;
  22324. };
  22325. Buffer.prototype.getData = function () {
  22326. return this._data;
  22327. };
  22328. Buffer.prototype.getBuffer = function () {
  22329. return this._buffer;
  22330. };
  22331. Buffer.prototype.getStrideSize = function () {
  22332. return this._strideSize;
  22333. };
  22334. Buffer.prototype.getIsInstanced = function () {
  22335. return this._instanced;
  22336. };
  22337. // Methods
  22338. Buffer.prototype.create = function (data) {
  22339. if (!data && this._buffer) {
  22340. return; // nothing to do
  22341. }
  22342. data = data || this._data;
  22343. if (!this._buffer) {
  22344. if (this._updatable) {
  22345. this._buffer = this._engine.createDynamicVertexBuffer(data);
  22346. this._data = data;
  22347. }
  22348. else {
  22349. this._buffer = this._engine.createVertexBuffer(data);
  22350. }
  22351. }
  22352. else if (this._updatable) {
  22353. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  22354. this._data = data;
  22355. }
  22356. };
  22357. Buffer.prototype.update = function (data) {
  22358. this.create(data);
  22359. };
  22360. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  22361. if (!this._buffer) {
  22362. return;
  22363. }
  22364. if (this._updatable) {
  22365. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  22366. this._data = null;
  22367. }
  22368. };
  22369. Buffer.prototype.dispose = function () {
  22370. if (!this._buffer) {
  22371. return;
  22372. }
  22373. if (this._engine._releaseBuffer(this._buffer)) {
  22374. this._buffer = null;
  22375. }
  22376. };
  22377. return Buffer;
  22378. }());
  22379. BABYLON.Buffer = Buffer;
  22380. })(BABYLON || (BABYLON = {}));
  22381. //# sourceMappingURL=babylon.buffer.js.map
  22382. var BABYLON;
  22383. (function (BABYLON) {
  22384. var VertexBuffer = (function () {
  22385. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22386. if (!stride) {
  22387. // Deduce stride from kind
  22388. switch (kind) {
  22389. case VertexBuffer.PositionKind:
  22390. stride = 3;
  22391. break;
  22392. case VertexBuffer.NormalKind:
  22393. stride = 3;
  22394. break;
  22395. case VertexBuffer.UVKind:
  22396. case VertexBuffer.UV2Kind:
  22397. case VertexBuffer.UV3Kind:
  22398. case VertexBuffer.UV4Kind:
  22399. case VertexBuffer.UV5Kind:
  22400. case VertexBuffer.UV6Kind:
  22401. stride = 2;
  22402. break;
  22403. case VertexBuffer.TangentKind:
  22404. case VertexBuffer.ColorKind:
  22405. stride = 4;
  22406. break;
  22407. case VertexBuffer.MatricesIndicesKind:
  22408. case VertexBuffer.MatricesIndicesExtraKind:
  22409. stride = 4;
  22410. break;
  22411. case VertexBuffer.MatricesWeightsKind:
  22412. case VertexBuffer.MatricesWeightsExtraKind:
  22413. stride = 4;
  22414. break;
  22415. }
  22416. }
  22417. if (data instanceof BABYLON.Buffer) {
  22418. if (!stride) {
  22419. stride = data.getStrideSize();
  22420. }
  22421. this._buffer = data;
  22422. this._ownsBuffer = false;
  22423. }
  22424. else {
  22425. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22426. this._ownsBuffer = true;
  22427. }
  22428. this._stride = stride;
  22429. this._offset = offset ? offset : 0;
  22430. this._size = size ? size : stride;
  22431. this._kind = kind;
  22432. }
  22433. /**
  22434. * Returns the kind of the VertexBuffer (string).
  22435. */
  22436. VertexBuffer.prototype.getKind = function () {
  22437. return this._kind;
  22438. };
  22439. // Properties
  22440. /**
  22441. * Boolean : is the VertexBuffer updatable ?
  22442. */
  22443. VertexBuffer.prototype.isUpdatable = function () {
  22444. return this._buffer.isUpdatable();
  22445. };
  22446. /**
  22447. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22448. */
  22449. VertexBuffer.prototype.getData = function () {
  22450. return this._buffer.getData();
  22451. };
  22452. /**
  22453. * Returns the WebGLBuffer associated to the VertexBuffer.
  22454. */
  22455. VertexBuffer.prototype.getBuffer = function () {
  22456. return this._buffer.getBuffer();
  22457. };
  22458. /**
  22459. * Returns the stride of the VertexBuffer (integer).
  22460. */
  22461. VertexBuffer.prototype.getStrideSize = function () {
  22462. return this._stride;
  22463. };
  22464. /**
  22465. * Returns the offset (integer).
  22466. */
  22467. VertexBuffer.prototype.getOffset = function () {
  22468. return this._offset;
  22469. };
  22470. /**
  22471. * Returns the VertexBuffer total size (integer).
  22472. */
  22473. VertexBuffer.prototype.getSize = function () {
  22474. return this._size;
  22475. };
  22476. /**
  22477. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22478. */
  22479. VertexBuffer.prototype.getIsInstanced = function () {
  22480. return this._buffer.getIsInstanced();
  22481. };
  22482. // Methods
  22483. /**
  22484. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22485. * Returns the created WebGLBuffer.
  22486. */
  22487. VertexBuffer.prototype.create = function (data) {
  22488. return this._buffer.create(data);
  22489. };
  22490. /**
  22491. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22492. * Returns the updated WebGLBuffer.
  22493. */
  22494. VertexBuffer.prototype.update = function (data) {
  22495. return this._buffer.update(data);
  22496. };
  22497. /**
  22498. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22499. * Returns the directly updated WebGLBuffer.
  22500. */
  22501. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22502. return this._buffer.updateDirectly(data, offset);
  22503. };
  22504. /**
  22505. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22506. */
  22507. VertexBuffer.prototype.dispose = function () {
  22508. if (this._ownsBuffer) {
  22509. this._buffer.dispose();
  22510. }
  22511. };
  22512. Object.defineProperty(VertexBuffer, "PositionKind", {
  22513. get: function () {
  22514. return VertexBuffer._PositionKind;
  22515. },
  22516. enumerable: true,
  22517. configurable: true
  22518. });
  22519. Object.defineProperty(VertexBuffer, "NormalKind", {
  22520. get: function () {
  22521. return VertexBuffer._NormalKind;
  22522. },
  22523. enumerable: true,
  22524. configurable: true
  22525. });
  22526. Object.defineProperty(VertexBuffer, "TangentKind", {
  22527. get: function () {
  22528. return VertexBuffer._TangentKind;
  22529. },
  22530. enumerable: true,
  22531. configurable: true
  22532. });
  22533. Object.defineProperty(VertexBuffer, "UVKind", {
  22534. get: function () {
  22535. return VertexBuffer._UVKind;
  22536. },
  22537. enumerable: true,
  22538. configurable: true
  22539. });
  22540. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22541. get: function () {
  22542. return VertexBuffer._UV2Kind;
  22543. },
  22544. enumerable: true,
  22545. configurable: true
  22546. });
  22547. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22548. get: function () {
  22549. return VertexBuffer._UV3Kind;
  22550. },
  22551. enumerable: true,
  22552. configurable: true
  22553. });
  22554. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22555. get: function () {
  22556. return VertexBuffer._UV4Kind;
  22557. },
  22558. enumerable: true,
  22559. configurable: true
  22560. });
  22561. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22562. get: function () {
  22563. return VertexBuffer._UV5Kind;
  22564. },
  22565. enumerable: true,
  22566. configurable: true
  22567. });
  22568. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22569. get: function () {
  22570. return VertexBuffer._UV6Kind;
  22571. },
  22572. enumerable: true,
  22573. configurable: true
  22574. });
  22575. Object.defineProperty(VertexBuffer, "ColorKind", {
  22576. get: function () {
  22577. return VertexBuffer._ColorKind;
  22578. },
  22579. enumerable: true,
  22580. configurable: true
  22581. });
  22582. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22583. get: function () {
  22584. return VertexBuffer._MatricesIndicesKind;
  22585. },
  22586. enumerable: true,
  22587. configurable: true
  22588. });
  22589. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22590. get: function () {
  22591. return VertexBuffer._MatricesWeightsKind;
  22592. },
  22593. enumerable: true,
  22594. configurable: true
  22595. });
  22596. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22597. get: function () {
  22598. return VertexBuffer._MatricesIndicesExtraKind;
  22599. },
  22600. enumerable: true,
  22601. configurable: true
  22602. });
  22603. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22604. get: function () {
  22605. return VertexBuffer._MatricesWeightsExtraKind;
  22606. },
  22607. enumerable: true,
  22608. configurable: true
  22609. });
  22610. return VertexBuffer;
  22611. }());
  22612. // Enums
  22613. VertexBuffer._PositionKind = "position";
  22614. VertexBuffer._NormalKind = "normal";
  22615. VertexBuffer._TangentKind = "tangent";
  22616. VertexBuffer._UVKind = "uv";
  22617. VertexBuffer._UV2Kind = "uv2";
  22618. VertexBuffer._UV3Kind = "uv3";
  22619. VertexBuffer._UV4Kind = "uv4";
  22620. VertexBuffer._UV5Kind = "uv5";
  22621. VertexBuffer._UV6Kind = "uv6";
  22622. VertexBuffer._ColorKind = "color";
  22623. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22624. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22625. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22626. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22627. BABYLON.VertexBuffer = VertexBuffer;
  22628. })(BABYLON || (BABYLON = {}));
  22629. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22630. var BABYLON;
  22631. (function (BABYLON) {
  22632. /**
  22633. * Creates an instance based on a source mesh.
  22634. */
  22635. var InstancedMesh = (function (_super) {
  22636. __extends(InstancedMesh, _super);
  22637. function InstancedMesh(name, source) {
  22638. var _this = _super.call(this, name, source.getScene()) || this;
  22639. source.instances.push(_this);
  22640. _this._sourceMesh = source;
  22641. _this.position.copyFrom(source.position);
  22642. _this.rotation.copyFrom(source.rotation);
  22643. _this.scaling.copyFrom(source.scaling);
  22644. if (source.rotationQuaternion) {
  22645. _this.rotationQuaternion = source.rotationQuaternion.clone();
  22646. }
  22647. _this.infiniteDistance = source.infiniteDistance;
  22648. _this.setPivotMatrix(source.getPivotMatrix());
  22649. _this.refreshBoundingInfo();
  22650. _this._syncSubMeshes();
  22651. return _this;
  22652. }
  22653. /**
  22654. * Returns the string "InstancedMesh".
  22655. */
  22656. InstancedMesh.prototype.getClassName = function () {
  22657. return "InstancedMesh";
  22658. };
  22659. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  22660. // Methods
  22661. get: function () {
  22662. return this._sourceMesh.receiveShadows;
  22663. },
  22664. enumerable: true,
  22665. configurable: true
  22666. });
  22667. Object.defineProperty(InstancedMesh.prototype, "material", {
  22668. get: function () {
  22669. return this._sourceMesh.material;
  22670. },
  22671. enumerable: true,
  22672. configurable: true
  22673. });
  22674. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  22675. get: function () {
  22676. return this._sourceMesh.visibility;
  22677. },
  22678. enumerable: true,
  22679. configurable: true
  22680. });
  22681. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  22682. get: function () {
  22683. return this._sourceMesh.skeleton;
  22684. },
  22685. enumerable: true,
  22686. configurable: true
  22687. });
  22688. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  22689. get: function () {
  22690. return this._sourceMesh.renderingGroupId;
  22691. },
  22692. enumerable: true,
  22693. configurable: true
  22694. });
  22695. /**
  22696. * Returns the total number of vertices (integer).
  22697. */
  22698. InstancedMesh.prototype.getTotalVertices = function () {
  22699. return this._sourceMesh.getTotalVertices();
  22700. };
  22701. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  22702. get: function () {
  22703. return this._sourceMesh;
  22704. },
  22705. enumerable: true,
  22706. configurable: true
  22707. });
  22708. /**
  22709. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  22710. */
  22711. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  22712. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  22713. };
  22714. /**
  22715. * Boolean : True if the mesh owns the requested kind of data.
  22716. */
  22717. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  22718. return this._sourceMesh.isVerticesDataPresent(kind);
  22719. };
  22720. /**
  22721. * Returns an array of indices (IndicesArray).
  22722. */
  22723. InstancedMesh.prototype.getIndices = function () {
  22724. return this._sourceMesh.getIndices();
  22725. };
  22726. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  22727. get: function () {
  22728. return this._sourceMesh._positions;
  22729. },
  22730. enumerable: true,
  22731. configurable: true
  22732. });
  22733. /**
  22734. * Sets a new updated BoundingInfo to the mesh.
  22735. * Returns the mesh.
  22736. */
  22737. InstancedMesh.prototype.refreshBoundingInfo = function () {
  22738. var meshBB = this._sourceMesh.getBoundingInfo();
  22739. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  22740. this._updateBoundingInfo();
  22741. return this;
  22742. };
  22743. InstancedMesh.prototype._preActivate = function () {
  22744. if (this._currentLOD) {
  22745. this._currentLOD._preActivate();
  22746. }
  22747. return this;
  22748. };
  22749. InstancedMesh.prototype._activate = function (renderId) {
  22750. if (this._currentLOD) {
  22751. this._currentLOD._registerInstanceForRenderId(this, renderId);
  22752. }
  22753. return this;
  22754. };
  22755. /**
  22756. * Returns the current associated LOD AbstractMesh.
  22757. */
  22758. InstancedMesh.prototype.getLOD = function (camera) {
  22759. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  22760. if (this._currentLOD === this.sourceMesh) {
  22761. return this;
  22762. }
  22763. return this._currentLOD;
  22764. };
  22765. InstancedMesh.prototype._syncSubMeshes = function () {
  22766. this.releaseSubMeshes();
  22767. if (this._sourceMesh.subMeshes) {
  22768. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  22769. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  22770. }
  22771. }
  22772. return this;
  22773. };
  22774. InstancedMesh.prototype._generatePointsArray = function () {
  22775. return this._sourceMesh._generatePointsArray();
  22776. };
  22777. /**
  22778. * Creates a new InstancedMesh from the current mesh.
  22779. * - name (string) : the cloned mesh name
  22780. * - newParent (optional Node) : the optional Node to parent the clone to.
  22781. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  22782. *
  22783. * Returns the clone.
  22784. */
  22785. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  22786. var result = this._sourceMesh.createInstance(name);
  22787. // Deep copy
  22788. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  22789. // Bounding info
  22790. this.refreshBoundingInfo();
  22791. // Parent
  22792. if (newParent) {
  22793. result.parent = newParent;
  22794. }
  22795. if (!doNotCloneChildren) {
  22796. // Children
  22797. for (var index = 0; index < this.getScene().meshes.length; index++) {
  22798. var mesh = this.getScene().meshes[index];
  22799. if (mesh.parent === this) {
  22800. mesh.clone(mesh.name, result);
  22801. }
  22802. }
  22803. }
  22804. result.computeWorldMatrix(true);
  22805. return result;
  22806. };
  22807. /**
  22808. * Disposes the InstancedMesh.
  22809. * Returns nothing.
  22810. */
  22811. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  22812. // Remove from mesh
  22813. var index = this._sourceMesh.instances.indexOf(this);
  22814. this._sourceMesh.instances.splice(index, 1);
  22815. _super.prototype.dispose.call(this, doNotRecurse);
  22816. };
  22817. return InstancedMesh;
  22818. }(BABYLON.AbstractMesh));
  22819. BABYLON.InstancedMesh = InstancedMesh;
  22820. })(BABYLON || (BABYLON = {}));
  22821. //# sourceMappingURL=babylon.instancedMesh.js.map
  22822. var BABYLON;
  22823. (function (BABYLON) {
  22824. var _InstancesBatch = (function () {
  22825. function _InstancesBatch() {
  22826. this.mustReturn = false;
  22827. this.visibleInstances = new Array();
  22828. this.renderSelf = new Array();
  22829. }
  22830. return _InstancesBatch;
  22831. }());
  22832. BABYLON._InstancesBatch = _InstancesBatch;
  22833. var Mesh = (function (_super) {
  22834. __extends(Mesh, _super);
  22835. /**
  22836. * @constructor
  22837. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22838. * @param {Scene} scene The scene to add this mesh to.
  22839. * @param {Node} parent The parent of this mesh, if it has one
  22840. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22841. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22842. * When false, achieved by calling a clone(), also passing False.
  22843. * This will make creation of children, recursive.
  22844. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22845. */
  22846. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22847. if (parent === void 0) { parent = null; }
  22848. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22849. var _this = _super.call(this, name, scene) || this;
  22850. // Events
  22851. /**
  22852. * An event triggered before rendering the mesh
  22853. * @type {BABYLON.Observable}
  22854. */
  22855. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22856. /**
  22857. * An event triggered after rendering the mesh
  22858. * @type {BABYLON.Observable}
  22859. */
  22860. _this.onAfterRenderObservable = new BABYLON.Observable();
  22861. /**
  22862. * An event triggered before drawing the mesh
  22863. * @type {BABYLON.Observable}
  22864. */
  22865. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22866. // Members
  22867. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22868. _this.instances = new Array();
  22869. _this._LODLevels = new Array();
  22870. _this._visibleInstances = {};
  22871. _this._renderIdForInstances = new Array();
  22872. _this._batchCache = new _InstancesBatch();
  22873. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22874. _this._sideOrientation = Mesh._DEFAULTSIDE;
  22875. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22876. // Will be used to save a source mesh reference, If any
  22877. _this._source = null;
  22878. if (source) {
  22879. // Source mesh
  22880. _this._source = source;
  22881. // Geometry
  22882. if (source._geometry) {
  22883. source._geometry.applyToMesh(_this);
  22884. }
  22885. // Deep copy
  22886. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  22887. // Parent
  22888. _this.parent = source.parent;
  22889. // Pivot
  22890. _this.setPivotMatrix(source.getPivotMatrix());
  22891. _this.id = name + "." + source.id;
  22892. // Material
  22893. _this.material = source.material;
  22894. var index;
  22895. if (!doNotCloneChildren) {
  22896. // Children
  22897. for (index = 0; index < scene.meshes.length; index++) {
  22898. var mesh = scene.meshes[index];
  22899. if (mesh.parent === source) {
  22900. // doNotCloneChildren is always going to be False
  22901. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22902. }
  22903. }
  22904. }
  22905. // Physics clone
  22906. var physicsEngine = _this.getScene().getPhysicsEngine();
  22907. if (clonePhysicsImpostor && physicsEngine) {
  22908. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22909. if (impostor) {
  22910. _this.physicsImpostor = impostor.clone(_this);
  22911. }
  22912. }
  22913. // Particles
  22914. for (index = 0; index < scene.particleSystems.length; index++) {
  22915. var system = scene.particleSystems[index];
  22916. if (system.emitter === source) {
  22917. system.clone(system.name, _this);
  22918. }
  22919. }
  22920. _this.computeWorldMatrix(true);
  22921. }
  22922. // Parent
  22923. if (parent !== null) {
  22924. _this.parent = parent;
  22925. }
  22926. return _this;
  22927. }
  22928. Object.defineProperty(Mesh, "FRONTSIDE", {
  22929. /**
  22930. * Mesh side orientation : usually the external or front surface
  22931. */
  22932. get: function () {
  22933. return Mesh._FRONTSIDE;
  22934. },
  22935. enumerable: true,
  22936. configurable: true
  22937. });
  22938. Object.defineProperty(Mesh, "BACKSIDE", {
  22939. /**
  22940. * Mesh side orientation : usually the internal or back surface
  22941. */
  22942. get: function () {
  22943. return Mesh._BACKSIDE;
  22944. },
  22945. enumerable: true,
  22946. configurable: true
  22947. });
  22948. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22949. /**
  22950. * Mesh side orientation : both internal and external or front and back surfaces
  22951. */
  22952. get: function () {
  22953. return Mesh._DOUBLESIDE;
  22954. },
  22955. enumerable: true,
  22956. configurable: true
  22957. });
  22958. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22959. /**
  22960. * Mesh side orientation : by default, `FRONTSIDE`
  22961. */
  22962. get: function () {
  22963. return Mesh._DEFAULTSIDE;
  22964. },
  22965. enumerable: true,
  22966. configurable: true
  22967. });
  22968. Object.defineProperty(Mesh, "NO_CAP", {
  22969. /**
  22970. * Mesh cap setting : no cap
  22971. */
  22972. get: function () {
  22973. return Mesh._NO_CAP;
  22974. },
  22975. enumerable: true,
  22976. configurable: true
  22977. });
  22978. Object.defineProperty(Mesh, "CAP_START", {
  22979. /**
  22980. * Mesh cap setting : one cap at the beginning of the mesh
  22981. */
  22982. get: function () {
  22983. return Mesh._CAP_START;
  22984. },
  22985. enumerable: true,
  22986. configurable: true
  22987. });
  22988. Object.defineProperty(Mesh, "CAP_END", {
  22989. /**
  22990. * Mesh cap setting : one cap at the end of the mesh
  22991. */
  22992. get: function () {
  22993. return Mesh._CAP_END;
  22994. },
  22995. enumerable: true,
  22996. configurable: true
  22997. });
  22998. Object.defineProperty(Mesh, "CAP_ALL", {
  22999. /**
  23000. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23001. */
  23002. get: function () {
  23003. return Mesh._CAP_ALL;
  23004. },
  23005. enumerable: true,
  23006. configurable: true
  23007. });
  23008. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23009. set: function (callback) {
  23010. if (this._onBeforeDrawObserver) {
  23011. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23012. }
  23013. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23014. },
  23015. enumerable: true,
  23016. configurable: true
  23017. });
  23018. Object.defineProperty(Mesh.prototype, "source", {
  23019. get: function () {
  23020. return this._source;
  23021. },
  23022. enumerable: true,
  23023. configurable: true
  23024. });
  23025. // Methods
  23026. /**
  23027. * Returns the string "Mesh".
  23028. */
  23029. Mesh.prototype.getClassName = function () {
  23030. return "Mesh";
  23031. };
  23032. /**
  23033. * Returns a string.
  23034. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23035. */
  23036. Mesh.prototype.toString = function (fullDetails) {
  23037. var ret = _super.prototype.toString.call(this, fullDetails);
  23038. ret += ", n vertices: " + this.getTotalVertices();
  23039. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23040. if (this.animations) {
  23041. for (var i = 0; i < this.animations.length; i++) {
  23042. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23043. }
  23044. }
  23045. if (fullDetails) {
  23046. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  23047. }
  23048. return ret;
  23049. };
  23050. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23051. /**
  23052. * True if the mesh has some Levels Of Details (LOD).
  23053. * Returns a boolean.
  23054. */
  23055. get: function () {
  23056. return this._LODLevels.length > 0;
  23057. },
  23058. enumerable: true,
  23059. configurable: true
  23060. });
  23061. Mesh.prototype._sortLODLevels = function () {
  23062. this._LODLevels.sort(function (a, b) {
  23063. if (a.distance < b.distance) {
  23064. return 1;
  23065. }
  23066. if (a.distance > b.distance) {
  23067. return -1;
  23068. }
  23069. return 0;
  23070. });
  23071. };
  23072. /**
  23073. * Add a mesh as LOD level triggered at the given distance.
  23074. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23075. * @param {number} distance The distance from the center of the object to show this level
  23076. * @param {Mesh} mesh The mesh to be added as LOD level
  23077. * @return {Mesh} This mesh (for chaining)
  23078. */
  23079. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23080. if (mesh && mesh._masterMesh) {
  23081. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23082. return this;
  23083. }
  23084. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23085. this._LODLevels.push(level);
  23086. if (mesh) {
  23087. mesh._masterMesh = this;
  23088. }
  23089. this._sortLODLevels();
  23090. return this;
  23091. };
  23092. /**
  23093. * Returns the LOD level mesh at the passed distance or null if not found.
  23094. * It is related to the method `addLODLevel(distance, mesh)`.
  23095. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23096. * Returns an object Mesh or `null`.
  23097. */
  23098. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23099. for (var index = 0; index < this._LODLevels.length; index++) {
  23100. var level = this._LODLevels[index];
  23101. if (level.distance === distance) {
  23102. return level.mesh;
  23103. }
  23104. }
  23105. return null;
  23106. };
  23107. /**
  23108. * Remove a mesh from the LOD array
  23109. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23110. * @param {Mesh} mesh The mesh to be removed.
  23111. * @return {Mesh} This mesh (for chaining)
  23112. */
  23113. Mesh.prototype.removeLODLevel = function (mesh) {
  23114. for (var index = 0; index < this._LODLevels.length; index++) {
  23115. if (this._LODLevels[index].mesh === mesh) {
  23116. this._LODLevels.splice(index, 1);
  23117. if (mesh) {
  23118. mesh._masterMesh = null;
  23119. }
  23120. }
  23121. }
  23122. this._sortLODLevels();
  23123. return this;
  23124. };
  23125. /**
  23126. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23127. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23128. */
  23129. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23130. if (!this._LODLevels || this._LODLevels.length === 0) {
  23131. return this;
  23132. }
  23133. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  23134. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23135. if (this.onLODLevelSelection) {
  23136. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23137. }
  23138. return this;
  23139. }
  23140. for (var index = 0; index < this._LODLevels.length; index++) {
  23141. var level = this._LODLevels[index];
  23142. if (level.distance < distanceToCamera) {
  23143. if (level.mesh) {
  23144. level.mesh._preActivate();
  23145. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23146. }
  23147. if (this.onLODLevelSelection) {
  23148. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23149. }
  23150. return level.mesh;
  23151. }
  23152. }
  23153. if (this.onLODLevelSelection) {
  23154. this.onLODLevelSelection(distanceToCamera, this, this);
  23155. }
  23156. return this;
  23157. };
  23158. Object.defineProperty(Mesh.prototype, "geometry", {
  23159. /**
  23160. * Returns the mesh internal Geometry object.
  23161. */
  23162. get: function () {
  23163. return this._geometry;
  23164. },
  23165. enumerable: true,
  23166. configurable: true
  23167. });
  23168. /**
  23169. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23170. */
  23171. Mesh.prototype.getTotalVertices = function () {
  23172. if (!this._geometry) {
  23173. return 0;
  23174. }
  23175. return this._geometry.getTotalVertices();
  23176. };
  23177. /**
  23178. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23179. * 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.
  23180. * Returns null if the mesh has no geometry or no vertex buffer.
  23181. * Possible `kind` values :
  23182. * - BABYLON.VertexBuffer.PositionKind
  23183. * - BABYLON.VertexBuffer.UVKind
  23184. * - BABYLON.VertexBuffer.UV2Kind
  23185. * - BABYLON.VertexBuffer.UV3Kind
  23186. * - BABYLON.VertexBuffer.UV4Kind
  23187. * - BABYLON.VertexBuffer.UV5Kind
  23188. * - BABYLON.VertexBuffer.UV6Kind
  23189. * - BABYLON.VertexBuffer.ColorKind
  23190. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23191. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23192. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23193. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23194. */
  23195. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  23196. if (!this._geometry) {
  23197. return null;
  23198. }
  23199. return this._geometry.getVerticesData(kind, copyWhenShared);
  23200. };
  23201. /**
  23202. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23203. * Returns `undefined` if the mesh has no geometry.
  23204. * Possible `kind` values :
  23205. * - BABYLON.VertexBuffer.PositionKind
  23206. * - BABYLON.VertexBuffer.UVKind
  23207. * - BABYLON.VertexBuffer.UV2Kind
  23208. * - BABYLON.VertexBuffer.UV3Kind
  23209. * - BABYLON.VertexBuffer.UV4Kind
  23210. * - BABYLON.VertexBuffer.UV5Kind
  23211. * - BABYLON.VertexBuffer.UV6Kind
  23212. * - BABYLON.VertexBuffer.ColorKind
  23213. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23214. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23215. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23216. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23217. */
  23218. Mesh.prototype.getVertexBuffer = function (kind) {
  23219. if (!this._geometry) {
  23220. return undefined;
  23221. }
  23222. return this._geometry.getVertexBuffer(kind);
  23223. };
  23224. /**
  23225. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23226. * Possible `kind` values :
  23227. * - BABYLON.VertexBuffer.PositionKind
  23228. * - BABYLON.VertexBuffer.UVKind
  23229. * - BABYLON.VertexBuffer.UV2Kind
  23230. * - BABYLON.VertexBuffer.UV3Kind
  23231. * - BABYLON.VertexBuffer.UV4Kind
  23232. * - BABYLON.VertexBuffer.UV5Kind
  23233. * - BABYLON.VertexBuffer.UV6Kind
  23234. * - BABYLON.VertexBuffer.ColorKind
  23235. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23236. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23237. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23238. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23239. */
  23240. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23241. if (!this._geometry) {
  23242. if (this._delayInfo) {
  23243. return this._delayInfo.indexOf(kind) !== -1;
  23244. }
  23245. return false;
  23246. }
  23247. return this._geometry.isVerticesDataPresent(kind);
  23248. };
  23249. /**
  23250. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23251. * Possible `kind` values :
  23252. * - BABYLON.VertexBuffer.PositionKind
  23253. * - BABYLON.VertexBuffer.UVKind
  23254. * - BABYLON.VertexBuffer.UV2Kind
  23255. * - BABYLON.VertexBuffer.UV3Kind
  23256. * - BABYLON.VertexBuffer.UV4Kind
  23257. * - BABYLON.VertexBuffer.UV5Kind
  23258. * - BABYLON.VertexBuffer.UV6Kind
  23259. * - BABYLON.VertexBuffer.ColorKind
  23260. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23261. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23262. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23263. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23264. */
  23265. Mesh.prototype.getVerticesDataKinds = function () {
  23266. if (!this._geometry) {
  23267. var result = [];
  23268. if (this._delayInfo) {
  23269. this._delayInfo.forEach(function (kind, index, array) {
  23270. result.push(kind);
  23271. });
  23272. }
  23273. return result;
  23274. }
  23275. return this._geometry.getVerticesDataKinds();
  23276. };
  23277. /**
  23278. * Returns a positive integer : the total number of indices in this mesh geometry.
  23279. * Returns zero if the mesh has no geometry.
  23280. */
  23281. Mesh.prototype.getTotalIndices = function () {
  23282. if (!this._geometry) {
  23283. return 0;
  23284. }
  23285. return this._geometry.getTotalIndices();
  23286. };
  23287. /**
  23288. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23289. * 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.
  23290. * Returns an empty array if the mesh has no geometry.
  23291. */
  23292. Mesh.prototype.getIndices = function (copyWhenShared) {
  23293. if (!this._geometry) {
  23294. return [];
  23295. }
  23296. return this._geometry.getIndices(copyWhenShared);
  23297. };
  23298. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23299. get: function () {
  23300. return this._masterMesh !== null && this._masterMesh !== undefined;
  23301. },
  23302. enumerable: true,
  23303. configurable: true
  23304. });
  23305. /**
  23306. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23307. */
  23308. Mesh.prototype.isReady = function () {
  23309. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23310. return false;
  23311. }
  23312. return _super.prototype.isReady.call(this);
  23313. };
  23314. /**
  23315. * Boolean : true if the mesh has been disposed.
  23316. */
  23317. Mesh.prototype.isDisposed = function () {
  23318. return this._isDisposed;
  23319. };
  23320. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  23321. get: function () {
  23322. return this._sideOrientation;
  23323. },
  23324. /**
  23325. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  23326. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  23327. */
  23328. set: function (sideO) {
  23329. this._sideOrientation = sideO;
  23330. },
  23331. enumerable: true,
  23332. configurable: true
  23333. });
  23334. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23335. /**
  23336. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23337. * This property is pertinent only for updatable parametric shapes.
  23338. */
  23339. get: function () {
  23340. return this._areNormalsFrozen;
  23341. },
  23342. enumerable: true,
  23343. configurable: true
  23344. });
  23345. /**
  23346. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23347. * It has no effect at all on other shapes.
  23348. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23349. * Returns the Mesh.
  23350. */
  23351. Mesh.prototype.freezeNormals = function () {
  23352. this._areNormalsFrozen = true;
  23353. return this;
  23354. };
  23355. /**
  23356. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23357. * It has no effect at all on other shapes.
  23358. * It reactivates the mesh normals computation if it was previously frozen.
  23359. * Returns the Mesh.
  23360. */
  23361. Mesh.prototype.unfreezeNormals = function () {
  23362. this._areNormalsFrozen = false;
  23363. return this;
  23364. };
  23365. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23366. /**
  23367. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23368. */
  23369. set: function (count) {
  23370. this._overridenInstanceCount = count;
  23371. },
  23372. enumerable: true,
  23373. configurable: true
  23374. });
  23375. // Methods
  23376. Mesh.prototype._preActivate = function () {
  23377. var sceneRenderId = this.getScene().getRenderId();
  23378. if (this._preActivateId === sceneRenderId) {
  23379. return this;
  23380. }
  23381. this._preActivateId = sceneRenderId;
  23382. this._visibleInstances = null;
  23383. return this;
  23384. };
  23385. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23386. if (this._visibleInstances) {
  23387. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23388. }
  23389. return this;
  23390. };
  23391. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23392. if (!this._visibleInstances) {
  23393. this._visibleInstances = {};
  23394. this._visibleInstances.defaultRenderId = renderId;
  23395. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23396. }
  23397. if (!this._visibleInstances[renderId]) {
  23398. this._visibleInstances[renderId] = new Array();
  23399. }
  23400. this._visibleInstances[renderId].push(instance);
  23401. return this;
  23402. };
  23403. /**
  23404. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23405. * This means the mesh underlying bounding box and sphere are recomputed.
  23406. * Returns the Mesh.
  23407. */
  23408. Mesh.prototype.refreshBoundingInfo = function () {
  23409. if (this._boundingInfo.isLocked) {
  23410. return;
  23411. }
  23412. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23413. if (data) {
  23414. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23415. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23416. }
  23417. if (this.subMeshes) {
  23418. for (var index = 0; index < this.subMeshes.length; index++) {
  23419. this.subMeshes[index].refreshBoundingInfo();
  23420. }
  23421. }
  23422. this._updateBoundingInfo();
  23423. return this;
  23424. };
  23425. Mesh.prototype._createGlobalSubMesh = function () {
  23426. var totalVertices = this.getTotalVertices();
  23427. if (!totalVertices || !this.getIndices()) {
  23428. return null;
  23429. }
  23430. this.releaseSubMeshes();
  23431. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23432. };
  23433. Mesh.prototype.subdivide = function (count) {
  23434. if (count < 1) {
  23435. return;
  23436. }
  23437. var totalIndices = this.getTotalIndices();
  23438. var subdivisionSize = (totalIndices / count) | 0;
  23439. var offset = 0;
  23440. // Ensure that subdivisionSize is a multiple of 3
  23441. while (subdivisionSize % 3 !== 0) {
  23442. subdivisionSize++;
  23443. }
  23444. this.releaseSubMeshes();
  23445. for (var index = 0; index < count; index++) {
  23446. if (offset >= totalIndices) {
  23447. break;
  23448. }
  23449. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23450. offset += subdivisionSize;
  23451. }
  23452. this.synchronizeInstances();
  23453. };
  23454. /**
  23455. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23456. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23457. * The `data` are either a numeric array either a Float32Array.
  23458. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23459. * 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).
  23460. * Note that a new underlying VertexBuffer object is created each call.
  23461. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23462. *
  23463. * Possible `kind` values :
  23464. * - BABYLON.VertexBuffer.PositionKind
  23465. * - BABYLON.VertexBuffer.UVKind
  23466. * - BABYLON.VertexBuffer.UV2Kind
  23467. * - BABYLON.VertexBuffer.UV3Kind
  23468. * - BABYLON.VertexBuffer.UV4Kind
  23469. * - BABYLON.VertexBuffer.UV5Kind
  23470. * - BABYLON.VertexBuffer.UV6Kind
  23471. * - BABYLON.VertexBuffer.ColorKind
  23472. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23473. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23474. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23475. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23476. *
  23477. * Returns the Mesh.
  23478. */
  23479. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23480. if (!this._geometry) {
  23481. var vertexData = new BABYLON.VertexData();
  23482. vertexData.set(data, kind);
  23483. var scene = this.getScene();
  23484. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23485. }
  23486. else {
  23487. this._geometry.setVerticesData(kind, data, updatable, stride);
  23488. }
  23489. return this;
  23490. };
  23491. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23492. if (updatable === void 0) { updatable = true; }
  23493. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  23494. return;
  23495. }
  23496. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23497. };
  23498. /**
  23499. * Sets the mesh VertexBuffer.
  23500. * Returns the Mesh.
  23501. */
  23502. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23503. if (!this._geometry) {
  23504. var scene = this.getScene();
  23505. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  23506. }
  23507. this._geometry.setVerticesBuffer(buffer);
  23508. return this;
  23509. };
  23510. /**
  23511. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23512. * If the mesh has no geometry, it is simply returned as it is.
  23513. * The `data` are either a numeric array either a Float32Array.
  23514. * No new underlying VertexBuffer object is created.
  23515. * 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.
  23516. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23517. *
  23518. * Possible `kind` values :
  23519. * - BABYLON.VertexBuffer.PositionKind
  23520. * - BABYLON.VertexBuffer.UVKind
  23521. * - BABYLON.VertexBuffer.UV2Kind
  23522. * - BABYLON.VertexBuffer.UV3Kind
  23523. * - BABYLON.VertexBuffer.UV4Kind
  23524. * - BABYLON.VertexBuffer.UV5Kind
  23525. * - BABYLON.VertexBuffer.UV6Kind
  23526. * - BABYLON.VertexBuffer.ColorKind
  23527. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23528. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23529. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23530. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23531. *
  23532. * Returns the Mesh.
  23533. */
  23534. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23535. if (!this._geometry) {
  23536. return;
  23537. }
  23538. if (!makeItUnique) {
  23539. this._geometry.updateVerticesData(kind, data, updateExtends);
  23540. }
  23541. else {
  23542. this.makeGeometryUnique();
  23543. this.updateVerticesData(kind, data, updateExtends, false);
  23544. }
  23545. return this;
  23546. };
  23547. /**
  23548. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23549. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23550. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23551. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23552. * Returns the Mesh.
  23553. */
  23554. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23555. if (computeNormals === void 0) { computeNormals = true; }
  23556. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23557. positionFunction(positions);
  23558. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23559. if (computeNormals) {
  23560. var indices = this.getIndices();
  23561. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23562. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23563. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23564. }
  23565. return this;
  23566. };
  23567. /**
  23568. * Creates a un-shared specific occurence of the geometry for the mesh.
  23569. * Returns the Mesh.
  23570. */
  23571. Mesh.prototype.makeGeometryUnique = function () {
  23572. if (!this._geometry) {
  23573. return;
  23574. }
  23575. var oldGeometry = this._geometry;
  23576. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23577. oldGeometry.releaseForMesh(this, true);
  23578. geometry.applyToMesh(this);
  23579. return this;
  23580. };
  23581. /**
  23582. * Sets the mesh indices.
  23583. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23584. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23585. * This method creates a new index buffer each call.
  23586. * Returns the Mesh.
  23587. */
  23588. Mesh.prototype.setIndices = function (indices, totalVertices) {
  23589. if (!this._geometry) {
  23590. var vertexData = new BABYLON.VertexData();
  23591. vertexData.indices = indices;
  23592. var scene = this.getScene();
  23593. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  23594. }
  23595. else {
  23596. this._geometry.setIndices(indices, totalVertices);
  23597. }
  23598. return this;
  23599. };
  23600. /**
  23601. * Invert the geometry to move from a right handed system to a left handed one.
  23602. * Returns the Mesh.
  23603. */
  23604. Mesh.prototype.toLeftHanded = function () {
  23605. if (!this._geometry) {
  23606. return;
  23607. }
  23608. this._geometry.toLeftHanded();
  23609. return this;
  23610. };
  23611. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23612. var engine = this.getScene().getEngine();
  23613. // Wireframe
  23614. var indexToBind;
  23615. if (this._unIndexed) {
  23616. indexToBind = null;
  23617. }
  23618. else {
  23619. switch (fillMode) {
  23620. case BABYLON.Material.PointFillMode:
  23621. indexToBind = null;
  23622. break;
  23623. case BABYLON.Material.WireFrameFillMode:
  23624. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23625. break;
  23626. default:
  23627. case BABYLON.Material.TriangleFillMode:
  23628. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23629. break;
  23630. }
  23631. }
  23632. // VBOs
  23633. this._geometry._bind(effect, indexToBind);
  23634. return this;
  23635. };
  23636. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23637. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23638. return this;
  23639. }
  23640. this.onBeforeDrawObservable.notifyObservers(this);
  23641. var engine = this.getScene().getEngine();
  23642. // Draw order
  23643. switch (fillMode) {
  23644. case BABYLON.Material.PointFillMode:
  23645. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23646. break;
  23647. case BABYLON.Material.WireFrameFillMode:
  23648. if (this._unIndexed) {
  23649. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23650. }
  23651. else {
  23652. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  23653. }
  23654. break;
  23655. default:
  23656. if (this._unIndexed) {
  23657. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23658. }
  23659. else {
  23660. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23661. }
  23662. }
  23663. return this;
  23664. };
  23665. /**
  23666. * Registers for this mesh a javascript function called just before the rendering process.
  23667. * This function is passed the current mesh.
  23668. * Return the Mesh.
  23669. */
  23670. Mesh.prototype.registerBeforeRender = function (func) {
  23671. this.onBeforeRenderObservable.add(func);
  23672. return this;
  23673. };
  23674. /**
  23675. * Disposes a previously registered javascript function called before the rendering.
  23676. * This function is passed the current mesh.
  23677. * Returns the Mesh.
  23678. */
  23679. Mesh.prototype.unregisterBeforeRender = function (func) {
  23680. this.onBeforeRenderObservable.removeCallback(func);
  23681. return this;
  23682. };
  23683. /**
  23684. * Registers for this mesh a javascript function called just after the rendering is complete.
  23685. * This function is passed the current mesh.
  23686. * Returns the Mesh.
  23687. */
  23688. Mesh.prototype.registerAfterRender = function (func) {
  23689. this.onAfterRenderObservable.add(func);
  23690. return this;
  23691. };
  23692. /**
  23693. * Disposes a previously registered javascript function called after the rendering.
  23694. * This function is passed the current mesh.
  23695. * Return the Mesh.
  23696. */
  23697. Mesh.prototype.unregisterAfterRender = function (func) {
  23698. this.onAfterRenderObservable.removeCallback(func);
  23699. return this;
  23700. };
  23701. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23702. var scene = this.getScene();
  23703. this._batchCache.mustReturn = false;
  23704. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23705. this._batchCache.visibleInstances[subMeshId] = null;
  23706. if (this._visibleInstances) {
  23707. var currentRenderId = scene.getRenderId();
  23708. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23709. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23710. var selfRenderId = this._renderId;
  23711. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23712. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23713. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23714. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23715. }
  23716. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  23717. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23718. this._batchCache.mustReturn = true;
  23719. return this._batchCache;
  23720. }
  23721. if (currentRenderId !== selfRenderId) {
  23722. this._batchCache.renderSelf[subMeshId] = false;
  23723. }
  23724. }
  23725. this._renderIdForInstances[subMeshId] = currentRenderId;
  23726. }
  23727. return this._batchCache;
  23728. };
  23729. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23730. var visibleInstances = batch.visibleInstances[subMesh._id];
  23731. var matricesCount = visibleInstances.length + 1;
  23732. var bufferSize = matricesCount * 16 * 4;
  23733. var currentInstancesBufferSize = this._instancesBufferSize;
  23734. var instancesBuffer = this._instancesBuffer;
  23735. while (this._instancesBufferSize < bufferSize) {
  23736. this._instancesBufferSize *= 2;
  23737. }
  23738. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23739. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23740. }
  23741. var offset = 0;
  23742. var instancesCount = 0;
  23743. var world = this.getWorldMatrix();
  23744. if (batch.renderSelf[subMesh._id]) {
  23745. world.copyToArray(this._instancesData, offset);
  23746. offset += 16;
  23747. instancesCount++;
  23748. }
  23749. if (visibleInstances) {
  23750. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23751. var instance = visibleInstances[instanceIndex];
  23752. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23753. offset += 16;
  23754. instancesCount++;
  23755. }
  23756. }
  23757. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23758. if (instancesBuffer) {
  23759. instancesBuffer.dispose();
  23760. }
  23761. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23762. this._instancesBuffer = instancesBuffer;
  23763. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23764. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23765. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23766. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23767. }
  23768. else {
  23769. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23770. }
  23771. this.geometry._bind(effect);
  23772. this._draw(subMesh, fillMode, instancesCount);
  23773. engine.unbindInstanceAttributes();
  23774. return this;
  23775. };
  23776. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23777. var scene = this.getScene();
  23778. var engine = scene.getEngine();
  23779. if (hardwareInstancedRendering) {
  23780. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23781. }
  23782. else {
  23783. if (batch.renderSelf[subMesh._id]) {
  23784. // Draw
  23785. if (onBeforeDraw) {
  23786. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23787. }
  23788. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23789. }
  23790. if (batch.visibleInstances[subMesh._id]) {
  23791. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23792. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23793. // World
  23794. var world = instance.getWorldMatrix();
  23795. if (onBeforeDraw) {
  23796. onBeforeDraw(true, world, effectiveMaterial);
  23797. }
  23798. // Draw
  23799. this._draw(subMesh, fillMode);
  23800. }
  23801. }
  23802. }
  23803. return this;
  23804. };
  23805. /**
  23806. * Triggers the draw call for the mesh.
  23807. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23808. * Returns the Mesh.
  23809. */
  23810. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23811. var scene = this.getScene();
  23812. // Managing instances
  23813. var batch = this._getInstancesRenderList(subMesh._id);
  23814. if (batch.mustReturn) {
  23815. return this;
  23816. }
  23817. // Checking geometry state
  23818. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23819. return this;
  23820. }
  23821. var callbackIndex;
  23822. this.onBeforeRenderObservable.notifyObservers(this);
  23823. var engine = scene.getEngine();
  23824. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23825. // Material
  23826. var effectiveMaterial = subMesh.getMaterial();
  23827. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23828. return this;
  23829. }
  23830. // Outline - step 1
  23831. var savedDepthWrite = engine.getDepthWrite();
  23832. if (this.renderOutline) {
  23833. engine.setDepthWrite(false);
  23834. scene.getOutlineRenderer().render(subMesh, batch);
  23835. engine.setDepthWrite(savedDepthWrite);
  23836. }
  23837. effectiveMaterial._preBind();
  23838. var effect = effectiveMaterial.getEffect();
  23839. // Bind
  23840. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  23841. this._bind(subMesh, effect, fillMode);
  23842. var world = this.getWorldMatrix();
  23843. effectiveMaterial.bind(world, this);
  23844. // Alpha mode
  23845. if (enableAlphaMode) {
  23846. engine.setAlphaMode(effectiveMaterial.alphaMode);
  23847. }
  23848. // Draw
  23849. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  23850. // Unbind
  23851. effectiveMaterial.unbind();
  23852. // Outline - step 2
  23853. if (this.renderOutline && savedDepthWrite) {
  23854. engine.setDepthWrite(true);
  23855. engine.setColorWrite(false);
  23856. scene.getOutlineRenderer().render(subMesh, batch);
  23857. engine.setColorWrite(true);
  23858. }
  23859. // Overlay
  23860. if (this.renderOverlay) {
  23861. var currentMode = engine.getAlphaMode();
  23862. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23863. scene.getOutlineRenderer().render(subMesh, batch, true);
  23864. engine.setAlphaMode(currentMode);
  23865. }
  23866. this.onAfterRenderObservable.notifyObservers(this);
  23867. return this;
  23868. };
  23869. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23870. if (isInstance) {
  23871. effectiveMaterial.bindOnlyWorldMatrix(world);
  23872. }
  23873. return this;
  23874. };
  23875. /**
  23876. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23877. */
  23878. Mesh.prototype.getEmittedParticleSystems = function () {
  23879. var results = new Array();
  23880. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23881. var particleSystem = this.getScene().particleSystems[index];
  23882. if (particleSystem.emitter === this) {
  23883. results.push(particleSystem);
  23884. }
  23885. }
  23886. return results;
  23887. };
  23888. /**
  23889. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23890. */
  23891. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23892. var results = new Array();
  23893. var descendants = this.getDescendants();
  23894. descendants.push(this);
  23895. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23896. var particleSystem = this.getScene().particleSystems[index];
  23897. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  23898. results.push(particleSystem);
  23899. }
  23900. }
  23901. return results;
  23902. };
  23903. Mesh.prototype._checkDelayState = function () {
  23904. var scene = this.getScene();
  23905. if (this._geometry) {
  23906. this._geometry.load(scene);
  23907. }
  23908. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23909. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23910. this._queueLoad(this, scene);
  23911. }
  23912. return this;
  23913. };
  23914. Mesh.prototype._queueLoad = function (mesh, scene) {
  23915. var _this = this;
  23916. scene._addPendingData(mesh);
  23917. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23918. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23919. if (data instanceof ArrayBuffer) {
  23920. _this._delayLoadingFunction(data, _this);
  23921. }
  23922. else {
  23923. _this._delayLoadingFunction(JSON.parse(data), _this);
  23924. }
  23925. _this.instances.forEach(function (instance) {
  23926. instance._syncSubMeshes();
  23927. });
  23928. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23929. scene._removePendingData(_this);
  23930. }, function () { }, scene.database, getBinaryData);
  23931. return this;
  23932. };
  23933. /**
  23934. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23935. */
  23936. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23937. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23938. return false;
  23939. }
  23940. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23941. return false;
  23942. }
  23943. this._checkDelayState();
  23944. return true;
  23945. };
  23946. /**
  23947. * Sets the mesh material by the material or multiMaterial `id` property.
  23948. * The material `id` is a string identifying the material or the multiMaterial.
  23949. * This method returns the Mesh.
  23950. */
  23951. Mesh.prototype.setMaterialByID = function (id) {
  23952. var materials = this.getScene().materials;
  23953. var index;
  23954. for (index = 0; index < materials.length; index++) {
  23955. if (materials[index].id === id) {
  23956. this.material = materials[index];
  23957. return this;
  23958. }
  23959. }
  23960. // Multi
  23961. var multiMaterials = this.getScene().multiMaterials;
  23962. for (index = 0; index < multiMaterials.length; index++) {
  23963. if (multiMaterials[index].id === id) {
  23964. this.material = multiMaterials[index];
  23965. return this;
  23966. }
  23967. }
  23968. return this;
  23969. };
  23970. /**
  23971. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23972. */
  23973. Mesh.prototype.getAnimatables = function () {
  23974. var results = [];
  23975. if (this.material) {
  23976. results.push(this.material);
  23977. }
  23978. if (this.skeleton) {
  23979. results.push(this.skeleton);
  23980. }
  23981. return results;
  23982. };
  23983. /**
  23984. * Modifies the mesh geometry according to the passed transformation matrix.
  23985. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23986. * The mesh normals are modified accordingly the same transformation.
  23987. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23988. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23989. * Returns the Mesh.
  23990. */
  23991. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23992. // Position
  23993. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23994. return this;
  23995. }
  23996. var submeshes = this.subMeshes.splice(0);
  23997. this._resetPointsArrayCache();
  23998. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23999. var temp = [];
  24000. var index;
  24001. for (index = 0; index < data.length; index += 3) {
  24002. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24003. }
  24004. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24005. // Normals
  24006. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24007. return this;
  24008. }
  24009. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24010. temp = [];
  24011. for (index = 0; index < data.length; index += 3) {
  24012. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24013. }
  24014. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24015. // flip faces?
  24016. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24017. this.flipFaces();
  24018. }
  24019. // Restore submeshes
  24020. this.releaseSubMeshes();
  24021. this.subMeshes = submeshes;
  24022. return this;
  24023. };
  24024. /**
  24025. * Modifies the mesh geometry according to its own current World Matrix.
  24026. * The mesh World Matrix is then reset.
  24027. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24028. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24029. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24030. * Returns the Mesh.
  24031. */
  24032. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24033. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24034. this.scaling.copyFromFloats(1, 1, 1);
  24035. this.position.copyFromFloats(0, 0, 0);
  24036. this.rotation.copyFromFloats(0, 0, 0);
  24037. //only if quaternion is already set
  24038. if (this.rotationQuaternion) {
  24039. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24040. }
  24041. this._worldMatrix = BABYLON.Matrix.Identity();
  24042. return this;
  24043. };
  24044. // Cache
  24045. Mesh.prototype._resetPointsArrayCache = function () {
  24046. this._positions = null;
  24047. return this;
  24048. };
  24049. Mesh.prototype._generatePointsArray = function () {
  24050. if (this._positions)
  24051. return true;
  24052. this._positions = [];
  24053. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24054. if (!data) {
  24055. return false;
  24056. }
  24057. for (var index = 0; index < data.length; index += 3) {
  24058. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  24059. }
  24060. return true;
  24061. };
  24062. /**
  24063. * Returns a new Mesh object generated from the current mesh properties.
  24064. * This method must not get confused with createInstance().
  24065. * The parameter `name` is a string, the name given to the new mesh.
  24066. * The optional parameter `newParent` can be any Node object (default `null`).
  24067. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24068. * 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.
  24069. */
  24070. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24071. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24072. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24073. };
  24074. /**
  24075. * Disposes the mesh.
  24076. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  24077. */
  24078. Mesh.prototype.dispose = function (doNotRecurse) {
  24079. var _this = this;
  24080. if (this._geometry) {
  24081. this._geometry.releaseForMesh(this, true);
  24082. }
  24083. // Sources
  24084. var meshes = this.getScene().meshes;
  24085. meshes.forEach(function (mesh) {
  24086. if (mesh._source && mesh._source === _this) {
  24087. mesh._source = null;
  24088. }
  24089. });
  24090. this._source = null;
  24091. // Instances
  24092. if (this._instancesBuffer) {
  24093. this._instancesBuffer.dispose();
  24094. this._instancesBuffer = null;
  24095. }
  24096. while (this.instances.length) {
  24097. this.instances[0].dispose();
  24098. }
  24099. // Highlight layers.
  24100. var highlightLayers = this.getScene().highlightLayers;
  24101. for (var i = 0; i < highlightLayers.length; i++) {
  24102. var highlightLayer = highlightLayers[i];
  24103. if (highlightLayer) {
  24104. highlightLayer.removeMesh(this);
  24105. highlightLayer.removeExcludedMesh(this);
  24106. }
  24107. }
  24108. _super.prototype.dispose.call(this, doNotRecurse);
  24109. };
  24110. /**
  24111. * Modifies the mesh geometry according to a displacement map.
  24112. * 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.
  24113. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24114. * This method returns nothing.
  24115. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24116. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24117. * 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.
  24118. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24119. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24120. *
  24121. * Returns the Mesh.
  24122. */
  24123. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24124. var _this = this;
  24125. var scene = this.getScene();
  24126. var onload = function (img) {
  24127. // Getting height map data
  24128. var canvas = document.createElement("canvas");
  24129. var context = canvas.getContext("2d");
  24130. var heightMapWidth = img.width;
  24131. var heightMapHeight = img.height;
  24132. canvas.width = heightMapWidth;
  24133. canvas.height = heightMapHeight;
  24134. context.drawImage(img, 0, 0);
  24135. // Create VertexData from map data
  24136. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24137. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24138. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24139. //execute success callback, if set
  24140. if (onSuccess) {
  24141. onSuccess(_this);
  24142. }
  24143. };
  24144. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24145. return this;
  24146. };
  24147. /**
  24148. * Modifies the mesh geometry according to a displacementMap buffer.
  24149. * 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.
  24150. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24151. * This method returns nothing.
  24152. * 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.
  24153. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24154. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24155. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24156. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24157. *
  24158. * Returns the Mesh.
  24159. */
  24160. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24161. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24162. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24163. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24164. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24165. return this;
  24166. }
  24167. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24168. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24169. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24170. var position = BABYLON.Vector3.Zero();
  24171. var normal = BABYLON.Vector3.Zero();
  24172. var uv = BABYLON.Vector2.Zero();
  24173. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24174. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24175. for (var index = 0; index < positions.length; index += 3) {
  24176. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24177. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24178. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24179. // Compute height
  24180. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24181. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24182. var pos = (u + v * heightMapWidth) * 4;
  24183. var r = buffer[pos] / 255.0;
  24184. var g = buffer[pos + 1] / 255.0;
  24185. var b = buffer[pos + 2] / 255.0;
  24186. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24187. normal.normalize();
  24188. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24189. position = position.add(normal);
  24190. position.toArray(positions, index);
  24191. }
  24192. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24193. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24194. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24195. return this;
  24196. };
  24197. /**
  24198. * Modify the mesh to get a flat shading rendering.
  24199. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24200. * This method returns the Mesh.
  24201. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24202. */
  24203. Mesh.prototype.convertToFlatShadedMesh = function () {
  24204. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24205. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24206. var kinds = this.getVerticesDataKinds();
  24207. var vbs = [];
  24208. var data = [];
  24209. var newdata = [];
  24210. var updatableNormals = false;
  24211. var kindIndex;
  24212. var kind;
  24213. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24214. kind = kinds[kindIndex];
  24215. var vertexBuffer = this.getVertexBuffer(kind);
  24216. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24217. updatableNormals = vertexBuffer.isUpdatable();
  24218. kinds.splice(kindIndex, 1);
  24219. kindIndex--;
  24220. continue;
  24221. }
  24222. vbs[kind] = vertexBuffer;
  24223. data[kind] = vbs[kind].getData();
  24224. newdata[kind] = [];
  24225. }
  24226. // Save previous submeshes
  24227. var previousSubmeshes = this.subMeshes.slice(0);
  24228. var indices = this.getIndices();
  24229. var totalIndices = this.getTotalIndices();
  24230. // Generating unique vertices per face
  24231. var index;
  24232. for (index = 0; index < totalIndices; index++) {
  24233. var vertexIndex = indices[index];
  24234. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24235. kind = kinds[kindIndex];
  24236. var stride = vbs[kind].getStrideSize();
  24237. for (var offset = 0; offset < stride; offset++) {
  24238. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24239. }
  24240. }
  24241. }
  24242. // Updating faces & normal
  24243. var normals = [];
  24244. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24245. for (index = 0; index < totalIndices; index += 3) {
  24246. indices[index] = index;
  24247. indices[index + 1] = index + 1;
  24248. indices[index + 2] = index + 2;
  24249. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24250. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24251. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24252. var p1p2 = p1.subtract(p2);
  24253. var p3p2 = p3.subtract(p2);
  24254. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24255. // Store same normals for every vertex
  24256. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24257. normals.push(normal.x);
  24258. normals.push(normal.y);
  24259. normals.push(normal.z);
  24260. }
  24261. }
  24262. this.setIndices(indices);
  24263. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24264. // Updating vertex buffers
  24265. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24266. kind = kinds[kindIndex];
  24267. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24268. }
  24269. // Updating submeshes
  24270. this.releaseSubMeshes();
  24271. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24272. var previousOne = previousSubmeshes[submeshIndex];
  24273. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24274. }
  24275. this.synchronizeInstances();
  24276. return this;
  24277. };
  24278. /**
  24279. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24280. * In other words, more vertices, no more indices and a single bigger VBO.
  24281. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24282. * Returns the Mesh.
  24283. */
  24284. Mesh.prototype.convertToUnIndexedMesh = function () {
  24285. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24286. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24287. var kinds = this.getVerticesDataKinds();
  24288. var vbs = [];
  24289. var data = [];
  24290. var newdata = [];
  24291. var updatableNormals = false;
  24292. var kindIndex;
  24293. var kind;
  24294. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24295. kind = kinds[kindIndex];
  24296. var vertexBuffer = this.getVertexBuffer(kind);
  24297. vbs[kind] = vertexBuffer;
  24298. data[kind] = vbs[kind].getData();
  24299. newdata[kind] = [];
  24300. }
  24301. // Save previous submeshes
  24302. var previousSubmeshes = this.subMeshes.slice(0);
  24303. var indices = this.getIndices();
  24304. var totalIndices = this.getTotalIndices();
  24305. // Generating unique vertices per face
  24306. var index;
  24307. for (index = 0; index < totalIndices; index++) {
  24308. var vertexIndex = indices[index];
  24309. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24310. kind = kinds[kindIndex];
  24311. var stride = vbs[kind].getStrideSize();
  24312. for (var offset = 0; offset < stride; offset++) {
  24313. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24314. }
  24315. }
  24316. }
  24317. // Updating indices
  24318. for (index = 0; index < totalIndices; index += 3) {
  24319. indices[index] = index;
  24320. indices[index + 1] = index + 1;
  24321. indices[index + 2] = index + 2;
  24322. }
  24323. this.setIndices(indices);
  24324. // Updating vertex buffers
  24325. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24326. kind = kinds[kindIndex];
  24327. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24328. }
  24329. // Updating submeshes
  24330. this.releaseSubMeshes();
  24331. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24332. var previousOne = previousSubmeshes[submeshIndex];
  24333. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24334. }
  24335. this._unIndexed = true;
  24336. this.synchronizeInstances();
  24337. return this;
  24338. };
  24339. /**
  24340. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24341. * This method returns the Mesh.
  24342. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24343. */
  24344. Mesh.prototype.flipFaces = function (flipNormals) {
  24345. if (flipNormals === void 0) { flipNormals = false; }
  24346. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24347. var i;
  24348. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24349. for (i = 0; i < vertex_data.normals.length; i++) {
  24350. vertex_data.normals[i] *= -1;
  24351. }
  24352. }
  24353. var temp;
  24354. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24355. // reassign indices
  24356. temp = vertex_data.indices[i + 1];
  24357. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24358. vertex_data.indices[i + 2] = temp;
  24359. }
  24360. vertex_data.applyToMesh(this);
  24361. return this;
  24362. };
  24363. // Instances
  24364. /**
  24365. * Creates a new InstancedMesh object from the mesh model.
  24366. * An instance shares the same properties and the same material than its model.
  24367. * Only these properties of each instance can then be set individually :
  24368. * - position
  24369. * - rotation
  24370. * - rotationQuaternion
  24371. * - setPivotMatrix
  24372. * - scaling
  24373. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24374. * Warning : this method is not supported for Line mesh and LineSystem
  24375. */
  24376. Mesh.prototype.createInstance = function (name) {
  24377. return new BABYLON.InstancedMesh(name, this);
  24378. };
  24379. /**
  24380. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24381. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24382. * This method returns the Mesh.
  24383. */
  24384. Mesh.prototype.synchronizeInstances = function () {
  24385. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24386. var instance = this.instances[instanceIndex];
  24387. instance._syncSubMeshes();
  24388. }
  24389. return this;
  24390. };
  24391. /**
  24392. * Simplify the mesh according to the given array of settings.
  24393. * Function will return immediately and will simplify async. It returns the Mesh.
  24394. * @param settings a collection of simplification settings.
  24395. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24396. * @param type the type of simplification to run.
  24397. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24398. */
  24399. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24400. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24401. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24402. this.getScene().simplificationQueue.addTask({
  24403. settings: settings,
  24404. parallelProcessing: parallelProcessing,
  24405. mesh: this,
  24406. simplificationType: simplificationType,
  24407. successCallback: successCallback
  24408. });
  24409. return this;
  24410. };
  24411. /**
  24412. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24413. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24414. * This should be used together with the simplification to avoid disappearing triangles.
  24415. * Returns the Mesh.
  24416. * @param successCallback an optional success callback to be called after the optimization finished.
  24417. */
  24418. Mesh.prototype.optimizeIndices = function (successCallback) {
  24419. var _this = this;
  24420. var indices = this.getIndices();
  24421. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24422. var vectorPositions = [];
  24423. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24424. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24425. }
  24426. var dupes = [];
  24427. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24428. var realPos = vectorPositions.length - 1 - iteration;
  24429. var testedPosition = vectorPositions[realPos];
  24430. for (var j = 0; j < realPos; ++j) {
  24431. var againstPosition = vectorPositions[j];
  24432. if (testedPosition.equals(againstPosition)) {
  24433. dupes[realPos] = j;
  24434. break;
  24435. }
  24436. }
  24437. }, function () {
  24438. for (var i = 0; i < indices.length; ++i) {
  24439. indices[i] = dupes[indices[i]] || indices[i];
  24440. }
  24441. //indices are now reordered
  24442. var originalSubMeshes = _this.subMeshes.slice(0);
  24443. _this.setIndices(indices);
  24444. _this.subMeshes = originalSubMeshes;
  24445. if (successCallback) {
  24446. successCallback(_this);
  24447. }
  24448. });
  24449. return this;
  24450. };
  24451. Mesh.prototype.serialize = function (serializationObject) {
  24452. serializationObject.name = this.name;
  24453. serializationObject.id = this.id;
  24454. serializationObject.type = this.getClassName();
  24455. if (BABYLON.Tags.HasTags(this)) {
  24456. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24457. }
  24458. serializationObject.position = this.position.asArray();
  24459. if (this.rotationQuaternion) {
  24460. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24461. }
  24462. else if (this.rotation) {
  24463. serializationObject.rotation = this.rotation.asArray();
  24464. }
  24465. serializationObject.scaling = this.scaling.asArray();
  24466. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24467. serializationObject.isEnabled = this.isEnabled();
  24468. serializationObject.isVisible = this.isVisible;
  24469. serializationObject.infiniteDistance = this.infiniteDistance;
  24470. serializationObject.pickable = this.isPickable;
  24471. serializationObject.receiveShadows = this.receiveShadows;
  24472. serializationObject.billboardMode = this.billboardMode;
  24473. serializationObject.visibility = this.visibility;
  24474. serializationObject.checkCollisions = this.checkCollisions;
  24475. serializationObject.isBlocker = this.isBlocker;
  24476. // Parent
  24477. if (this.parent) {
  24478. serializationObject.parentId = this.parent.id;
  24479. }
  24480. // Geometry
  24481. var geometry = this._geometry;
  24482. if (geometry) {
  24483. var geometryId = geometry.id;
  24484. serializationObject.geometryId = geometryId;
  24485. // SubMeshes
  24486. serializationObject.subMeshes = [];
  24487. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24488. var subMesh = this.subMeshes[subIndex];
  24489. serializationObject.subMeshes.push({
  24490. materialIndex: subMesh.materialIndex,
  24491. verticesStart: subMesh.verticesStart,
  24492. verticesCount: subMesh.verticesCount,
  24493. indexStart: subMesh.indexStart,
  24494. indexCount: subMesh.indexCount
  24495. });
  24496. }
  24497. }
  24498. // Material
  24499. if (this.material) {
  24500. serializationObject.materialId = this.material.id;
  24501. }
  24502. else {
  24503. this.material = null;
  24504. }
  24505. // Skeleton
  24506. if (this.skeleton) {
  24507. serializationObject.skeletonId = this.skeleton.id;
  24508. }
  24509. // Physics
  24510. //TODO implement correct serialization for physics impostors.
  24511. if (this.getPhysicsImpostor()) {
  24512. var impostor = this.getPhysicsImpostor();
  24513. serializationObject.physicsMass = impostor.getParam("mass");
  24514. serializationObject.physicsFriction = impostor.getParam("friction");
  24515. serializationObject.physicsRestitution = impostor.getParam("mass");
  24516. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  24517. }
  24518. // Metadata
  24519. if (this.metadata) {
  24520. serializationObject.metadata = this.metadata;
  24521. }
  24522. // Instances
  24523. serializationObject.instances = [];
  24524. for (var index = 0; index < this.instances.length; index++) {
  24525. var instance = this.instances[index];
  24526. var serializationInstance = {
  24527. name: instance.name,
  24528. position: instance.position.asArray(),
  24529. scaling: instance.scaling.asArray()
  24530. };
  24531. if (instance.rotationQuaternion) {
  24532. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24533. }
  24534. else if (instance.rotation) {
  24535. serializationInstance.rotation = instance.rotation.asArray();
  24536. }
  24537. serializationObject.instances.push(serializationInstance);
  24538. // Animations
  24539. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24540. serializationInstance.ranges = instance.serializeAnimationRanges();
  24541. }
  24542. // Animations
  24543. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24544. serializationObject.ranges = this.serializeAnimationRanges();
  24545. // Layer mask
  24546. serializationObject.layerMask = this.layerMask;
  24547. // Alpha
  24548. serializationObject.alphaIndex = this.alphaIndex;
  24549. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24550. // Overlay
  24551. serializationObject.overlayAlpha = this.overlayAlpha;
  24552. serializationObject.overlayColor = this.overlayColor.asArray();
  24553. serializationObject.renderOverlay = this.renderOverlay;
  24554. // Fog
  24555. serializationObject.applyFog = this.applyFog;
  24556. // Action Manager
  24557. if (this.actionManager) {
  24558. serializationObject.actions = this.actionManager.serialize(this.name);
  24559. }
  24560. };
  24561. // Statics
  24562. /**
  24563. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24564. * The parameter `parsedMesh` is the mesh to be copied.
  24565. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24566. */
  24567. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24568. var mesh;
  24569. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24570. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24571. }
  24572. else {
  24573. mesh = new Mesh(parsedMesh.name, scene);
  24574. }
  24575. mesh.id = parsedMesh.id;
  24576. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24577. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24578. if (parsedMesh.metadata !== undefined) {
  24579. mesh.metadata = parsedMesh.metadata;
  24580. }
  24581. if (parsedMesh.rotationQuaternion) {
  24582. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24583. }
  24584. else if (parsedMesh.rotation) {
  24585. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24586. }
  24587. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24588. if (parsedMesh.localMatrix) {
  24589. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24590. }
  24591. else if (parsedMesh.pivotMatrix) {
  24592. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24593. }
  24594. mesh.setEnabled(parsedMesh.isEnabled);
  24595. mesh.isVisible = parsedMesh.isVisible;
  24596. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24597. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24598. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24599. if (parsedMesh.applyFog !== undefined) {
  24600. mesh.applyFog = parsedMesh.applyFog;
  24601. }
  24602. if (parsedMesh.pickable !== undefined) {
  24603. mesh.isPickable = parsedMesh.pickable;
  24604. }
  24605. if (parsedMesh.alphaIndex !== undefined) {
  24606. mesh.alphaIndex = parsedMesh.alphaIndex;
  24607. }
  24608. mesh.receiveShadows = parsedMesh.receiveShadows;
  24609. mesh.billboardMode = parsedMesh.billboardMode;
  24610. if (parsedMesh.visibility !== undefined) {
  24611. mesh.visibility = parsedMesh.visibility;
  24612. }
  24613. mesh.checkCollisions = parsedMesh.checkCollisions;
  24614. if (parsedMesh.isBlocker !== undefined) {
  24615. mesh.isBlocker = parsedMesh.isBlocker;
  24616. }
  24617. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24618. // freezeWorldMatrix
  24619. if (parsedMesh.freezeWorldMatrix) {
  24620. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24621. }
  24622. // Parent
  24623. if (parsedMesh.parentId) {
  24624. mesh._waitingParentId = parsedMesh.parentId;
  24625. }
  24626. // Actions
  24627. if (parsedMesh.actions !== undefined) {
  24628. mesh._waitingActions = parsedMesh.actions;
  24629. }
  24630. // Overlay
  24631. if (parsedMesh.overlayAlpha !== undefined) {
  24632. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24633. }
  24634. if (parsedMesh.overlayColor !== undefined) {
  24635. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24636. }
  24637. if (parsedMesh.renderOverlay !== undefined) {
  24638. mesh.renderOverlay = parsedMesh.renderOverlay;
  24639. }
  24640. // Geometry
  24641. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24642. if (parsedMesh.delayLoadingFile) {
  24643. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24644. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24645. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24646. if (parsedMesh._binaryInfo) {
  24647. mesh._binaryInfo = parsedMesh._binaryInfo;
  24648. }
  24649. mesh._delayInfo = [];
  24650. if (parsedMesh.hasUVs) {
  24651. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24652. }
  24653. if (parsedMesh.hasUVs2) {
  24654. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24655. }
  24656. if (parsedMesh.hasUVs3) {
  24657. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24658. }
  24659. if (parsedMesh.hasUVs4) {
  24660. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24661. }
  24662. if (parsedMesh.hasUVs5) {
  24663. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24664. }
  24665. if (parsedMesh.hasUVs6) {
  24666. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24667. }
  24668. if (parsedMesh.hasColors) {
  24669. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24670. }
  24671. if (parsedMesh.hasMatricesIndices) {
  24672. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24673. }
  24674. if (parsedMesh.hasMatricesWeights) {
  24675. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24676. }
  24677. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24678. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24679. mesh._checkDelayState();
  24680. }
  24681. }
  24682. else {
  24683. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24684. }
  24685. // Material
  24686. if (parsedMesh.materialId) {
  24687. mesh.setMaterialByID(parsedMesh.materialId);
  24688. }
  24689. else {
  24690. mesh.material = null;
  24691. }
  24692. // Skeleton
  24693. if (parsedMesh.skeletonId > -1) {
  24694. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24695. if (parsedMesh.numBoneInfluencers) {
  24696. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24697. }
  24698. }
  24699. // Animations
  24700. if (parsedMesh.animations) {
  24701. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24702. var parsedAnimation = parsedMesh.animations[animationIndex];
  24703. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24704. }
  24705. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24706. }
  24707. if (parsedMesh.autoAnimate) {
  24708. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24709. }
  24710. // Layer Mask
  24711. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24712. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24713. }
  24714. else {
  24715. mesh.layerMask = 0x0FFFFFFF;
  24716. }
  24717. // Physics
  24718. if (parsedMesh.physicsImpostor) {
  24719. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24720. mass: parsedMesh.physicsMass,
  24721. friction: parsedMesh.physicsFriction,
  24722. restitution: parsedMesh.physicsRestitution
  24723. }, scene);
  24724. }
  24725. // Instances
  24726. if (parsedMesh.instances) {
  24727. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24728. var parsedInstance = parsedMesh.instances[index];
  24729. var instance = mesh.createInstance(parsedInstance.name);
  24730. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24731. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24732. if (parsedInstance.parentId) {
  24733. instance._waitingParentId = parsedInstance.parentId;
  24734. }
  24735. if (parsedInstance.rotationQuaternion) {
  24736. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24737. }
  24738. else if (parsedInstance.rotation) {
  24739. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24740. }
  24741. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24742. instance.checkCollisions = mesh.checkCollisions;
  24743. if (parsedMesh.animations) {
  24744. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24745. parsedAnimation = parsedMesh.animations[animationIndex];
  24746. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24747. }
  24748. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24749. }
  24750. }
  24751. }
  24752. return mesh;
  24753. };
  24754. /**
  24755. * Creates a ribbon mesh.
  24756. * Please consider using the same method from the MeshBuilder class instead.
  24757. * 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.
  24758. *
  24759. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24760. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24761. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24762. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24763. * 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.
  24764. * 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.
  24765. * 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
  24766. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24767. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24769. */
  24770. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24771. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24772. pathArray: pathArray,
  24773. closeArray: closeArray,
  24774. closePath: closePath,
  24775. offset: offset,
  24776. updatable: updatable,
  24777. sideOrientation: sideOrientation,
  24778. instance: instance
  24779. }, scene);
  24780. };
  24781. /**
  24782. * Creates a plane polygonal mesh. By default, this is a disc.
  24783. * Please consider using the same method from the MeshBuilder class instead.
  24784. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24785. * 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.
  24786. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24789. */
  24790. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24791. var options = {
  24792. radius: radius,
  24793. tessellation: tessellation,
  24794. sideOrientation: sideOrientation,
  24795. updatable: updatable
  24796. };
  24797. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24798. };
  24799. /**
  24800. * Creates a box mesh.
  24801. * Please consider using the same method from the MeshBuilder class instead.
  24802. * The parameter `size` sets the size (float) of each box side (default 1).
  24803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24806. */
  24807. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24808. var options = {
  24809. size: size,
  24810. sideOrientation: sideOrientation,
  24811. updatable: updatable
  24812. };
  24813. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24814. };
  24815. /**
  24816. * Creates a sphere mesh.
  24817. * Please consider using the same method from the MeshBuilder class instead.
  24818. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24819. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24820. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24821. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24822. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24823. */
  24824. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24825. var options = {
  24826. segments: segments,
  24827. diameterX: diameter,
  24828. diameterY: diameter,
  24829. diameterZ: diameter,
  24830. sideOrientation: sideOrientation,
  24831. updatable: updatable
  24832. };
  24833. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24834. };
  24835. /**
  24836. * Creates a cylinder or a cone mesh.
  24837. * Please consider using the same method from the MeshBuilder class instead.
  24838. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24839. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24840. * 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.
  24841. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24842. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24843. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24844. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24846. */
  24847. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24848. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24849. if (scene !== undefined) {
  24850. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24851. updatable = scene;
  24852. }
  24853. scene = subdivisions;
  24854. subdivisions = 1;
  24855. }
  24856. var options = {
  24857. height: height,
  24858. diameterTop: diameterTop,
  24859. diameterBottom: diameterBottom,
  24860. tessellation: tessellation,
  24861. subdivisions: subdivisions,
  24862. sideOrientation: sideOrientation,
  24863. updatable: updatable
  24864. };
  24865. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24866. };
  24867. // Torus (Code from SharpDX.org)
  24868. /**
  24869. * Creates a torus mesh.
  24870. * Please consider using the same method from the MeshBuilder class instead.
  24871. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24872. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24873. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24874. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24875. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24877. */
  24878. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24879. var options = {
  24880. diameter: diameter,
  24881. thickness: thickness,
  24882. tessellation: tessellation,
  24883. sideOrientation: sideOrientation,
  24884. updatable: updatable
  24885. };
  24886. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24887. };
  24888. /**
  24889. * Creates a torus knot mesh.
  24890. * Please consider using the same method from the MeshBuilder class instead.
  24891. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24892. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24893. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24894. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24895. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24896. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24898. */
  24899. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24900. var options = {
  24901. radius: radius,
  24902. tube: tube,
  24903. radialSegments: radialSegments,
  24904. tubularSegments: tubularSegments,
  24905. p: p,
  24906. q: q,
  24907. sideOrientation: sideOrientation,
  24908. updatable: updatable
  24909. };
  24910. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24911. };
  24912. /**
  24913. * Creates a line mesh.
  24914. * Please consider using the same method from the MeshBuilder class instead.
  24915. * 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.
  24916. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24917. * The parameter `points` is an array successive Vector3.
  24918. * 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
  24919. * When updating an instance, remember that only point positions can change, not the number of points.
  24920. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24921. */
  24922. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24923. var options = {
  24924. points: points,
  24925. updatable: updatable,
  24926. instance: instance
  24927. };
  24928. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24929. };
  24930. /**
  24931. * Creates a dashed line mesh.
  24932. * Please consider using the same method from the MeshBuilder class instead.
  24933. * 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.
  24934. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24935. * The parameter `points` is an array successive Vector3.
  24936. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24937. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24938. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24939. * 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
  24940. * When updating an instance, remember that only point positions can change, not the number of points.
  24941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24942. */
  24943. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24944. var options = {
  24945. points: points,
  24946. dashSize: dashSize,
  24947. gapSize: gapSize,
  24948. dashNb: dashNb,
  24949. updatable: updatable,
  24950. instance: instance
  24951. };
  24952. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24953. };
  24954. /**
  24955. * Creates an extruded shape mesh.
  24956. * 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.
  24957. * Please consider using the same method from the MeshBuilder class instead.
  24958. *
  24959. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24960. * 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
  24961. * extruded along the Z axis.
  24962. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24963. * 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.
  24964. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24965. * 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
  24966. * 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
  24967. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24968. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24969. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24970. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24971. */
  24972. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24973. var options = {
  24974. shape: shape,
  24975. path: path,
  24976. scale: scale,
  24977. rotation: rotation,
  24978. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24979. sideOrientation: sideOrientation,
  24980. instance: instance,
  24981. updatable: updatable
  24982. };
  24983. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24984. };
  24985. /**
  24986. * Creates an custom extruded shape mesh.
  24987. * 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.
  24988. * Please consider using the same method from the MeshBuilder class instead.
  24989. *
  24990. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24991. * 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
  24992. * extruded along the Z axis.
  24993. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24994. * 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
  24995. * and the distance of this point from the begining of the path :
  24996. * ```javascript
  24997. * var rotationFunction = function(i, distance) {
  24998. * // do things
  24999. * return rotationValue; }
  25000. * ```
  25001. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25002. * 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
  25003. * and the distance of this point from the begining of the path :
  25004. * ```javascript
  25005. * var scaleFunction = function(i, distance) {
  25006. * // do things
  25007. * return scaleValue;}
  25008. * ```
  25009. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25010. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25011. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25012. * 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
  25013. * 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
  25014. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25015. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25018. */
  25019. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25020. var options = {
  25021. shape: shape,
  25022. path: path,
  25023. scaleFunction: scaleFunction,
  25024. rotationFunction: rotationFunction,
  25025. ribbonCloseArray: ribbonCloseArray,
  25026. ribbonClosePath: ribbonClosePath,
  25027. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25028. sideOrientation: sideOrientation,
  25029. instance: instance,
  25030. updatable: updatable
  25031. };
  25032. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25033. };
  25034. /**
  25035. * Creates lathe mesh.
  25036. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25037. * Please consider using the same method from the MeshBuilder class instead.
  25038. * 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
  25039. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25040. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25041. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25043. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25045. */
  25046. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25047. var options = {
  25048. shape: shape,
  25049. radius: radius,
  25050. tessellation: tessellation,
  25051. sideOrientation: sideOrientation,
  25052. updatable: updatable
  25053. };
  25054. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25055. };
  25056. /**
  25057. * Creates a plane mesh.
  25058. * Please consider using the same method from the MeshBuilder class instead.
  25059. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25060. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25061. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25063. */
  25064. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25065. var options = {
  25066. size: size,
  25067. width: size,
  25068. height: size,
  25069. sideOrientation: sideOrientation,
  25070. updatable: updatable
  25071. };
  25072. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25073. };
  25074. /**
  25075. * Creates a ground mesh.
  25076. * Please consider using the same method from the MeshBuilder class instead.
  25077. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25078. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25079. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25080. */
  25081. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25082. var options = {
  25083. width: width,
  25084. height: height,
  25085. subdivisions: subdivisions,
  25086. updatable: updatable
  25087. };
  25088. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25089. };
  25090. /**
  25091. * Creates a tiled ground mesh.
  25092. * Please consider using the same method from the MeshBuilder class instead.
  25093. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25094. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25095. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25096. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25097. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25098. * numbers of subdivisions on the ground width and height of each tile.
  25099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25100. */
  25101. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25102. var options = {
  25103. xmin: xmin,
  25104. zmin: zmin,
  25105. xmax: xmax,
  25106. zmax: zmax,
  25107. subdivisions: subdivisions,
  25108. precision: precision,
  25109. updatable: updatable
  25110. };
  25111. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25112. };
  25113. /**
  25114. * Creates a ground mesh from a height map.
  25115. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25116. * Please consider using the same method from the MeshBuilder class instead.
  25117. * The parameter `url` sets the URL of the height map image resource.
  25118. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25119. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25120. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25121. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25122. * 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).
  25123. * This function is passed the newly built mesh :
  25124. * ```javascript
  25125. * function(mesh) { // do things
  25126. * return; }
  25127. * ```
  25128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25129. */
  25130. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25131. var options = {
  25132. width: width,
  25133. height: height,
  25134. subdivisions: subdivisions,
  25135. minHeight: minHeight,
  25136. maxHeight: maxHeight,
  25137. updatable: updatable,
  25138. onReady: onReady
  25139. };
  25140. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25141. };
  25142. /**
  25143. * Creates a tube mesh.
  25144. * 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.
  25145. * Please consider using the same method from the MeshBuilder class instead.
  25146. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25147. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25148. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25149. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25150. * 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.
  25151. * It must return a radius value (positive float) :
  25152. * ```javascript
  25153. * var radiusFunction = function(i, distance) {
  25154. * // do things
  25155. * return radius; }
  25156. * ```
  25157. * 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
  25158. * 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
  25159. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25160. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25162. */
  25163. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25164. var options = {
  25165. path: path,
  25166. radius: radius,
  25167. tessellation: tessellation,
  25168. radiusFunction: radiusFunction,
  25169. arc: 1,
  25170. cap: cap,
  25171. updatable: updatable,
  25172. sideOrientation: sideOrientation,
  25173. instance: instance
  25174. };
  25175. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25176. };
  25177. /**
  25178. * Creates a polyhedron mesh.
  25179. * Please consider using the same method from the MeshBuilder class instead.
  25180. * 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
  25181. * to choose the wanted type.
  25182. * The parameter `size` (positive float, default 1) sets the polygon size.
  25183. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25184. * 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`.
  25185. * 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
  25186. * 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)`).
  25187. * 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
  25188. * 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.
  25189. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25190. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25192. */
  25193. Mesh.CreatePolyhedron = function (name, options, scene) {
  25194. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25195. };
  25196. /**
  25197. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25198. * Please consider using the same method from the MeshBuilder class instead.
  25199. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25200. * 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`).
  25201. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25202. * 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.
  25203. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25204. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25206. */
  25207. Mesh.CreateIcoSphere = function (name, options, scene) {
  25208. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25209. };
  25210. /**
  25211. * Creates a decal mesh.
  25212. * Please consider using the same method from the MeshBuilder class instead.
  25213. * 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.
  25214. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25215. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25216. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25217. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25218. */
  25219. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25220. var options = {
  25221. position: position,
  25222. normal: normal,
  25223. size: size,
  25224. angle: angle
  25225. };
  25226. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25227. };
  25228. // Skeletons
  25229. /**
  25230. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25231. */
  25232. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25233. var source;
  25234. if (!this._sourcePositions) {
  25235. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25236. this._sourcePositions = new Float32Array(source);
  25237. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  25238. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25239. }
  25240. }
  25241. return this._sourcePositions;
  25242. };
  25243. /**
  25244. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25245. */
  25246. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25247. var source;
  25248. if (!this._sourceNormals) {
  25249. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25250. this._sourceNormals = new Float32Array(source);
  25251. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  25252. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25253. }
  25254. }
  25255. return this._sourceNormals;
  25256. };
  25257. /**
  25258. * Updates the vertex buffer by applying transformation from the bones.
  25259. * Returns the Mesh.
  25260. *
  25261. * @param {skeleton} skeleton to apply
  25262. */
  25263. Mesh.prototype.applySkeleton = function (skeleton) {
  25264. if (!this.geometry) {
  25265. return this;
  25266. }
  25267. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25268. return this;
  25269. }
  25270. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25271. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25272. return this;
  25273. }
  25274. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25275. return this;
  25276. }
  25277. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25278. return this;
  25279. }
  25280. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25281. return this;
  25282. }
  25283. if (!this._sourcePositions) {
  25284. var submeshes = this.subMeshes.slice();
  25285. this.setPositionsForCPUSkinning();
  25286. this.subMeshes = submeshes;
  25287. }
  25288. if (!this._sourceNormals) {
  25289. this.setNormalsForCPUSkinning();
  25290. }
  25291. // positionsData checks for not being Float32Array will only pass at most once
  25292. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25293. if (!(positionsData instanceof Float32Array)) {
  25294. positionsData = new Float32Array(positionsData);
  25295. }
  25296. // normalsData checks for not being Float32Array will only pass at most once
  25297. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25298. if (!(normalsData instanceof Float32Array)) {
  25299. normalsData = new Float32Array(normalsData);
  25300. }
  25301. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25302. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25303. var needExtras = this.numBoneInfluencers > 4;
  25304. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25305. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25306. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25307. var tempVector3 = BABYLON.Vector3.Zero();
  25308. var finalMatrix = new BABYLON.Matrix();
  25309. var tempMatrix = new BABYLON.Matrix();
  25310. var matWeightIdx = 0;
  25311. var inf;
  25312. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25313. var weight;
  25314. for (inf = 0; inf < 4; inf++) {
  25315. weight = matricesWeightsData[matWeightIdx + inf];
  25316. if (weight > 0) {
  25317. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25318. finalMatrix.addToSelf(tempMatrix);
  25319. }
  25320. else
  25321. break;
  25322. }
  25323. if (needExtras) {
  25324. for (inf = 0; inf < 4; inf++) {
  25325. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25326. if (weight > 0) {
  25327. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25328. finalMatrix.addToSelf(tempMatrix);
  25329. }
  25330. else
  25331. break;
  25332. }
  25333. }
  25334. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25335. tempVector3.toArray(positionsData, index);
  25336. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25337. tempVector3.toArray(normalsData, index);
  25338. finalMatrix.reset();
  25339. }
  25340. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25341. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25342. return this;
  25343. };
  25344. // Tools
  25345. /**
  25346. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25347. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25348. */
  25349. Mesh.MinMax = function (meshes) {
  25350. var minVector = null;
  25351. var maxVector = null;
  25352. meshes.forEach(function (mesh, index, array) {
  25353. var boundingBox = mesh.getBoundingInfo().boundingBox;
  25354. if (!minVector) {
  25355. minVector = boundingBox.minimumWorld;
  25356. maxVector = boundingBox.maximumWorld;
  25357. }
  25358. else {
  25359. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25360. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25361. }
  25362. });
  25363. return {
  25364. min: minVector,
  25365. max: maxVector
  25366. };
  25367. };
  25368. /**
  25369. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25370. */
  25371. Mesh.Center = function (meshesOrMinMaxVector) {
  25372. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25373. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25374. };
  25375. /**
  25376. * Merge the array of meshes into a single mesh for performance reasons.
  25377. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25378. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25379. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25380. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25381. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25382. */
  25383. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25384. if (disposeSource === void 0) { disposeSource = true; }
  25385. var index;
  25386. if (!allow32BitsIndices) {
  25387. var totalVertices = 0;
  25388. // Counting vertices
  25389. for (index = 0; index < meshes.length; index++) {
  25390. if (meshes[index]) {
  25391. totalVertices += meshes[index].getTotalVertices();
  25392. if (totalVertices > 65536) {
  25393. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25394. return null;
  25395. }
  25396. }
  25397. }
  25398. }
  25399. // Merge
  25400. var vertexData;
  25401. var otherVertexData;
  25402. var indiceArray = new Array();
  25403. var source;
  25404. for (index = 0; index < meshes.length; index++) {
  25405. if (meshes[index]) {
  25406. meshes[index].computeWorldMatrix(true);
  25407. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25408. otherVertexData.transform(meshes[index].getWorldMatrix());
  25409. if (vertexData) {
  25410. vertexData.merge(otherVertexData);
  25411. }
  25412. else {
  25413. vertexData = otherVertexData;
  25414. source = meshes[index];
  25415. }
  25416. if (subdivideWithSubMeshes) {
  25417. indiceArray.push(meshes[index].getTotalIndices());
  25418. }
  25419. }
  25420. }
  25421. if (!meshSubclass) {
  25422. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25423. }
  25424. vertexData.applyToMesh(meshSubclass);
  25425. // Setting properties
  25426. meshSubclass.material = source.material;
  25427. meshSubclass.checkCollisions = source.checkCollisions;
  25428. // Cleaning
  25429. if (disposeSource) {
  25430. for (index = 0; index < meshes.length; index++) {
  25431. if (meshes[index]) {
  25432. meshes[index].dispose();
  25433. }
  25434. }
  25435. }
  25436. // Subdivide
  25437. if (subdivideWithSubMeshes) {
  25438. //-- Suppresions du submesh global
  25439. meshSubclass.releaseSubMeshes();
  25440. index = 0;
  25441. var offset = 0;
  25442. //-- aplique la subdivision en fonction du tableau d'indices
  25443. while (index < indiceArray.length) {
  25444. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25445. offset += indiceArray[index];
  25446. index++;
  25447. }
  25448. }
  25449. return meshSubclass;
  25450. };
  25451. return Mesh;
  25452. }(BABYLON.AbstractMesh));
  25453. // Consts
  25454. Mesh._FRONTSIDE = 0;
  25455. Mesh._BACKSIDE = 1;
  25456. Mesh._DOUBLESIDE = 2;
  25457. Mesh._DEFAULTSIDE = 0;
  25458. Mesh._NO_CAP = 0;
  25459. Mesh._CAP_START = 1;
  25460. Mesh._CAP_END = 2;
  25461. Mesh._CAP_ALL = 3;
  25462. BABYLON.Mesh = Mesh;
  25463. })(BABYLON || (BABYLON = {}));
  25464. //# sourceMappingURL=babylon.mesh.js.map
  25465. var BABYLON;
  25466. (function (BABYLON) {
  25467. var SubMesh = (function () {
  25468. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25469. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25470. this.materialIndex = materialIndex;
  25471. this.verticesStart = verticesStart;
  25472. this.verticesCount = verticesCount;
  25473. this.indexStart = indexStart;
  25474. this.indexCount = indexCount;
  25475. this._renderId = 0;
  25476. this._mesh = mesh;
  25477. this._renderingMesh = renderingMesh || mesh;
  25478. mesh.subMeshes.push(this);
  25479. this._trianglePlanes = [];
  25480. this._id = mesh.subMeshes.length - 1;
  25481. if (createBoundingBox) {
  25482. this.refreshBoundingInfo();
  25483. mesh.computeWorldMatrix(true);
  25484. }
  25485. }
  25486. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25487. get: function () {
  25488. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25489. },
  25490. enumerable: true,
  25491. configurable: true
  25492. });
  25493. /**
  25494. * Returns the submesh BoudingInfo object.
  25495. */
  25496. SubMesh.prototype.getBoundingInfo = function () {
  25497. if (this.IsGlobal) {
  25498. return this._mesh.getBoundingInfo();
  25499. }
  25500. return this._boundingInfo;
  25501. };
  25502. /**
  25503. * Sets the submesh BoundingInfo.
  25504. * Return the SubMesh.
  25505. */
  25506. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25507. this._boundingInfo = boundingInfo;
  25508. return this;
  25509. };
  25510. /**
  25511. * Returns the mesh of the current submesh.
  25512. */
  25513. SubMesh.prototype.getMesh = function () {
  25514. return this._mesh;
  25515. };
  25516. /**
  25517. * Returns the rendering mesh of the submesh.
  25518. */
  25519. SubMesh.prototype.getRenderingMesh = function () {
  25520. return this._renderingMesh;
  25521. };
  25522. /**
  25523. * Returns the submesh material.
  25524. */
  25525. SubMesh.prototype.getMaterial = function () {
  25526. var rootMaterial = this._renderingMesh.material;
  25527. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  25528. var multiMaterial = rootMaterial;
  25529. return multiMaterial.getSubMaterial(this.materialIndex);
  25530. }
  25531. if (!rootMaterial) {
  25532. return this._mesh.getScene().defaultMaterial;
  25533. }
  25534. return rootMaterial;
  25535. };
  25536. // Methods
  25537. /**
  25538. * Sets a new updated BoundingInfo object to the submesh.
  25539. * Returns the SubMesh.
  25540. */
  25541. SubMesh.prototype.refreshBoundingInfo = function () {
  25542. this._lastColliderWorldVertices = null;
  25543. if (this.IsGlobal) {
  25544. return;
  25545. }
  25546. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25547. if (!data) {
  25548. this._boundingInfo = this._mesh._boundingInfo;
  25549. return;
  25550. }
  25551. var indices = this._renderingMesh.getIndices();
  25552. var extend;
  25553. //is this the only submesh?
  25554. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25555. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25556. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  25557. }
  25558. else {
  25559. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25560. }
  25561. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25562. return this;
  25563. };
  25564. SubMesh.prototype._checkCollision = function (collider) {
  25565. return this.getBoundingInfo()._checkCollision(collider);
  25566. };
  25567. /**
  25568. * Updates the submesh BoundingInfo.
  25569. * Returns the Submesh.
  25570. */
  25571. SubMesh.prototype.updateBoundingInfo = function (world) {
  25572. if (!this.getBoundingInfo()) {
  25573. this.refreshBoundingInfo();
  25574. }
  25575. this.getBoundingInfo().update(world);
  25576. return this;
  25577. };
  25578. /**
  25579. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25580. * Boolean returned.
  25581. */
  25582. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25583. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  25584. };
  25585. /**
  25586. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25587. * Boolean returned.
  25588. */
  25589. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25590. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  25591. };
  25592. /**
  25593. * Renders the submesh.
  25594. * Returns it.
  25595. */
  25596. SubMesh.prototype.render = function (enableAlphaMode) {
  25597. this._renderingMesh.render(this, enableAlphaMode);
  25598. return this;
  25599. };
  25600. /**
  25601. * Returns a new Index Buffer.
  25602. * Type returned : WebGLBuffer.
  25603. */
  25604. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25605. if (!this._linesIndexBuffer) {
  25606. var linesIndices = [];
  25607. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25608. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25609. }
  25610. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25611. this.linesIndexCount = linesIndices.length;
  25612. }
  25613. return this._linesIndexBuffer;
  25614. };
  25615. /**
  25616. * True is the passed Ray intersects the submesh bounding box.
  25617. * Boolean returned.
  25618. */
  25619. SubMesh.prototype.canIntersects = function (ray) {
  25620. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  25621. };
  25622. /**
  25623. * Returns an object IntersectionInfo.
  25624. */
  25625. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25626. var intersectInfo = null;
  25627. // LineMesh first as it's also a Mesh...
  25628. if (this._mesh instanceof BABYLON.LinesMesh) {
  25629. var lineMesh = this._mesh;
  25630. // Line test
  25631. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25632. var p0 = positions[indices[index]];
  25633. var p1 = positions[indices[index + 1]];
  25634. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25635. if (length < 0) {
  25636. continue;
  25637. }
  25638. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25639. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25640. if (fastCheck) {
  25641. break;
  25642. }
  25643. }
  25644. }
  25645. }
  25646. else {
  25647. // Triangles test
  25648. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25649. var p0 = positions[indices[index]];
  25650. var p1 = positions[indices[index + 1]];
  25651. var p2 = positions[indices[index + 2]];
  25652. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25653. if (currentIntersectInfo) {
  25654. if (currentIntersectInfo.distance < 0) {
  25655. continue;
  25656. }
  25657. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25658. intersectInfo = currentIntersectInfo;
  25659. intersectInfo.faceId = index / 3;
  25660. if (fastCheck) {
  25661. break;
  25662. }
  25663. }
  25664. }
  25665. }
  25666. }
  25667. return intersectInfo;
  25668. };
  25669. // Clone
  25670. /**
  25671. * Creates a new Submesh from the passed Mesh.
  25672. */
  25673. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25674. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25675. if (!this.IsGlobal) {
  25676. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  25677. }
  25678. return result;
  25679. };
  25680. // Dispose
  25681. /**
  25682. * Disposes the Submesh.
  25683. * Returns nothing.
  25684. */
  25685. SubMesh.prototype.dispose = function () {
  25686. if (this._linesIndexBuffer) {
  25687. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25688. this._linesIndexBuffer = null;
  25689. }
  25690. // Remove from mesh
  25691. var index = this._mesh.subMeshes.indexOf(this);
  25692. this._mesh.subMeshes.splice(index, 1);
  25693. };
  25694. // Statics
  25695. /**
  25696. * Creates a new Submesh from the passed parameters :
  25697. * - materialIndex (integer) : the index of the main mesh material.
  25698. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25699. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25700. * - mesh (Mesh) : the main mesh to create the submesh from.
  25701. * - renderingMesh (optional Mesh) : rendering mesh.
  25702. */
  25703. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25704. var minVertexIndex = Number.MAX_VALUE;
  25705. var maxVertexIndex = -Number.MAX_VALUE;
  25706. renderingMesh = renderingMesh || mesh;
  25707. var indices = renderingMesh.getIndices();
  25708. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25709. var vertexIndex = indices[index];
  25710. if (vertexIndex < minVertexIndex)
  25711. minVertexIndex = vertexIndex;
  25712. if (vertexIndex > maxVertexIndex)
  25713. maxVertexIndex = vertexIndex;
  25714. }
  25715. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25716. };
  25717. return SubMesh;
  25718. }());
  25719. BABYLON.SubMesh = SubMesh;
  25720. })(BABYLON || (BABYLON = {}));
  25721. //# sourceMappingURL=babylon.subMesh.js.map
  25722. var BABYLON;
  25723. (function (BABYLON) {
  25724. var MeshBuilder = (function () {
  25725. function MeshBuilder() {
  25726. }
  25727. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  25728. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  25729. return BABYLON.Mesh.DOUBLESIDE;
  25730. }
  25731. if (orientation === undefined || orientation === null) {
  25732. return BABYLON.Mesh.FRONTSIDE;
  25733. }
  25734. return orientation;
  25735. };
  25736. /**
  25737. * Creates a box mesh.
  25738. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  25739. * The parameter `size` sets the size (float) of each box side (default 1).
  25740. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  25741. * 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).
  25742. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  25743. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25744. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25746. */
  25747. MeshBuilder.CreateBox = function (name, options, scene) {
  25748. var box = new BABYLON.Mesh(name, scene);
  25749. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25750. box.sideOrientation = options.sideOrientation;
  25751. var vertexData = BABYLON.VertexData.CreateBox(options);
  25752. vertexData.applyToMesh(box, options.updatable);
  25753. return box;
  25754. };
  25755. /**
  25756. * Creates a sphere mesh.
  25757. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  25758. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25759. * 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`).
  25760. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25761. * 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
  25762. * 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).
  25763. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25764. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25766. */
  25767. MeshBuilder.CreateSphere = function (name, options, scene) {
  25768. var sphere = new BABYLON.Mesh(name, scene);
  25769. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25770. sphere.sideOrientation = options.sideOrientation;
  25771. var vertexData = BABYLON.VertexData.CreateSphere(options);
  25772. vertexData.applyToMesh(sphere, options.updatable);
  25773. return sphere;
  25774. };
  25775. /**
  25776. * Creates a plane polygonal mesh. By default, this is a disc.
  25777. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  25778. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25779. * 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.
  25780. * 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
  25781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25782. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25784. */
  25785. MeshBuilder.CreateDisc = function (name, options, scene) {
  25786. var disc = new BABYLON.Mesh(name, scene);
  25787. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25788. disc.sideOrientation = options.sideOrientation;
  25789. var vertexData = BABYLON.VertexData.CreateDisc(options);
  25790. vertexData.applyToMesh(disc, options.updatable);
  25791. return disc;
  25792. };
  25793. /**
  25794. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25795. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  25796. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25797. * 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`).
  25798. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25799. * 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.
  25800. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25801. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25803. */
  25804. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  25805. var sphere = new BABYLON.Mesh(name, scene);
  25806. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25807. sphere.sideOrientation = options.sideOrientation;
  25808. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  25809. vertexData.applyToMesh(sphere, options.updatable);
  25810. return sphere;
  25811. };
  25812. ;
  25813. /**
  25814. * Creates a ribbon mesh.
  25815. * 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.
  25816. *
  25817. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25818. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25819. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25820. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25821. * 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.
  25822. * 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.
  25823. * 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
  25824. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25825. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25826. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  25827. * 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.
  25828. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  25829. * 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
  25830. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  25831. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  25832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25833. */
  25834. MeshBuilder.CreateRibbon = function (name, options, scene) {
  25835. var pathArray = options.pathArray;
  25836. var closeArray = options.closeArray;
  25837. var closePath = options.closePath;
  25838. var offset = options.offset;
  25839. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25840. var instance = options.instance;
  25841. var updatable = options.updatable;
  25842. if (instance) {
  25843. // positionFunction : ribbon case
  25844. // only pathArray and sideOrientation parameters are taken into account for positions update
  25845. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  25846. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  25847. var positionFunction = function (positions) {
  25848. var minlg = pathArray[0].length;
  25849. var i = 0;
  25850. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  25851. for (var si = 1; si <= ns; si++) {
  25852. for (var p = 0; p < pathArray.length; p++) {
  25853. var path = pathArray[p];
  25854. var l = path.length;
  25855. minlg = (minlg < l) ? minlg : l;
  25856. var j = 0;
  25857. while (j < minlg) {
  25858. positions[i] = path[j].x;
  25859. positions[i + 1] = path[j].y;
  25860. positions[i + 2] = path[j].z;
  25861. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  25862. BABYLON.Tmp.Vector3[0].x = path[j].x;
  25863. }
  25864. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  25865. BABYLON.Tmp.Vector3[1].x = path[j].x;
  25866. }
  25867. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  25868. BABYLON.Tmp.Vector3[0].y = path[j].y;
  25869. }
  25870. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  25871. BABYLON.Tmp.Vector3[1].y = path[j].y;
  25872. }
  25873. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  25874. BABYLON.Tmp.Vector3[0].z = path[j].z;
  25875. }
  25876. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  25877. BABYLON.Tmp.Vector3[1].z = path[j].z;
  25878. }
  25879. j++;
  25880. i += 3;
  25881. }
  25882. if (instance._closePath) {
  25883. positions[i] = path[0].x;
  25884. positions[i + 1] = path[0].y;
  25885. positions[i + 2] = path[0].z;
  25886. i += 3;
  25887. }
  25888. }
  25889. }
  25890. };
  25891. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25892. positionFunction(positions);
  25893. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  25894. instance._boundingInfo.update(instance._worldMatrix);
  25895. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25896. if (options.colors) {
  25897. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  25898. for (var c = 0; c < options.colors.length; c++) {
  25899. colors[c * 4] = options.colors[c].r;
  25900. colors[c * 4 + 1] = options.colors[c].g;
  25901. colors[c * 4 + 2] = options.colors[c].b;
  25902. colors[c * 4 + 3] = options.colors[c].a;
  25903. }
  25904. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  25905. }
  25906. if (options.uvs) {
  25907. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25908. for (var i = 0; i < options.uvs.length; i++) {
  25909. uvs[i * 2] = options.uvs[i].x;
  25910. uvs[i * 2 + 1] = options.uvs[i].y;
  25911. }
  25912. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  25913. }
  25914. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  25915. var indices = instance.getIndices();
  25916. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25917. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  25918. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  25919. if (instance._closePath) {
  25920. var indexFirst = 0;
  25921. var indexLast = 0;
  25922. for (var p = 0; p < pathArray.length; p++) {
  25923. indexFirst = instance._idx[p] * 3;
  25924. if (p + 1 < pathArray.length) {
  25925. indexLast = (instance._idx[p + 1] - 1) * 3;
  25926. }
  25927. else {
  25928. indexLast = normals.length - 3;
  25929. }
  25930. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25931. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25932. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25933. normals[indexLast] = normals[indexFirst];
  25934. normals[indexLast + 1] = normals[indexFirst + 1];
  25935. normals[indexLast + 2] = normals[indexFirst + 2];
  25936. }
  25937. }
  25938. if (!(instance.areNormalsFrozen)) {
  25939. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25940. }
  25941. }
  25942. return instance;
  25943. }
  25944. else {
  25945. var ribbon = new BABYLON.Mesh(name, scene);
  25946. ribbon.sideOrientation = sideOrientation;
  25947. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  25948. if (closePath) {
  25949. ribbon._idx = vertexData._idx;
  25950. }
  25951. ribbon._closePath = closePath;
  25952. ribbon._closeArray = closeArray;
  25953. vertexData.applyToMesh(ribbon, updatable);
  25954. return ribbon;
  25955. }
  25956. };
  25957. /**
  25958. * Creates a cylinder or a cone mesh.
  25959. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  25960. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25961. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25962. * 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.
  25963. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25964. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25965. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  25966. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  25967. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  25968. * 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).
  25969. * 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
  25970. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  25971. * 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
  25972. * 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.
  25973. * If `enclose` is false, a ring surface is one element.
  25974. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  25975. * 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
  25976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25979. */
  25980. MeshBuilder.CreateCylinder = function (name, options, scene) {
  25981. var cylinder = new BABYLON.Mesh(name, scene);
  25982. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  25983. cylinder.sideOrientation = options.sideOrientation;
  25984. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  25985. vertexData.applyToMesh(cylinder, options.updatable);
  25986. return cylinder;
  25987. };
  25988. /**
  25989. * Creates a torus mesh.
  25990. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  25991. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25992. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25993. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25994. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25995. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25996. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25997. */
  25998. MeshBuilder.CreateTorus = function (name, options, scene) {
  25999. var torus = new BABYLON.Mesh(name, scene);
  26000. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26001. torus.sideOrientation = options.sideOrientation;
  26002. var vertexData = BABYLON.VertexData.CreateTorus(options);
  26003. vertexData.applyToMesh(torus, options.updatable);
  26004. return torus;
  26005. };
  26006. /**
  26007. * Creates a torus knot mesh.
  26008. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  26009. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  26010. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  26011. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  26012. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  26013. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26016. */
  26017. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  26018. var torusKnot = new BABYLON.Mesh(name, scene);
  26019. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26020. torusKnot.sideOrientation = options.sideOrientation;
  26021. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  26022. vertexData.applyToMesh(torusKnot, options.updatable);
  26023. return torusKnot;
  26024. };
  26025. /**
  26026. * Creates a line system mesh.
  26027. * A line system is a pool of many lines gathered in a single mesh.
  26028. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  26029. * 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.
  26030. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  26031. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  26032. * 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
  26033. * 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
  26034. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  26035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26036. */
  26037. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  26038. var instance = options.instance;
  26039. var lines = options.lines;
  26040. if (instance) {
  26041. var positionFunction = function (positions) {
  26042. var i = 0;
  26043. for (var l = 0; l < lines.length; l++) {
  26044. var points = lines[l];
  26045. for (var p = 0; p < points.length; p++) {
  26046. positions[i] = points[p].x;
  26047. positions[i + 1] = points[p].y;
  26048. positions[i + 2] = points[p].z;
  26049. i += 3;
  26050. }
  26051. }
  26052. };
  26053. instance.updateMeshPositions(positionFunction, false);
  26054. return instance;
  26055. }
  26056. // line system creation
  26057. var lineSystem = new BABYLON.LinesMesh(name, scene);
  26058. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  26059. vertexData.applyToMesh(lineSystem, options.updatable);
  26060. return lineSystem;
  26061. };
  26062. /**
  26063. * Creates a line mesh.
  26064. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  26065. * 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.
  26066. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26067. * The parameter `points` is an array successive Vector3.
  26068. * 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
  26069. * When updating an instance, remember that only point positions can change, not the number of points.
  26070. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26071. */
  26072. MeshBuilder.CreateLines = function (name, options, scene) {
  26073. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  26074. return lines;
  26075. };
  26076. /**
  26077. * Creates a dashed line mesh.
  26078. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  26079. * 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.
  26080. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  26081. * The parameter `points` is an array successive Vector3.
  26082. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  26083. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  26084. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  26085. * 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
  26086. * When updating an instance, remember that only point positions can change, not the number of points.
  26087. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26088. */
  26089. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  26090. var points = options.points;
  26091. var instance = options.instance;
  26092. var gapSize = options.gapSize;
  26093. var dashNb = options.dashNb;
  26094. var dashSize = options.dashSize;
  26095. if (instance) {
  26096. var positionFunction = function (positions) {
  26097. var curvect = BABYLON.Vector3.Zero();
  26098. var nbSeg = positions.length / 6;
  26099. var lg = 0;
  26100. var nb = 0;
  26101. var shft = 0;
  26102. var dashshft = 0;
  26103. var curshft = 0;
  26104. var p = 0;
  26105. var i = 0;
  26106. var j = 0;
  26107. for (i = 0; i < points.length - 1; i++) {
  26108. points[i + 1].subtractToRef(points[i], curvect);
  26109. lg += curvect.length();
  26110. }
  26111. shft = lg / nbSeg;
  26112. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  26113. for (i = 0; i < points.length - 1; i++) {
  26114. points[i + 1].subtractToRef(points[i], curvect);
  26115. nb = Math.floor(curvect.length() / shft);
  26116. curvect.normalize();
  26117. j = 0;
  26118. while (j < nb && p < positions.length) {
  26119. curshft = shft * j;
  26120. positions[p] = points[i].x + curshft * curvect.x;
  26121. positions[p + 1] = points[i].y + curshft * curvect.y;
  26122. positions[p + 2] = points[i].z + curshft * curvect.z;
  26123. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  26124. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  26125. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  26126. p += 6;
  26127. j++;
  26128. }
  26129. }
  26130. while (p < positions.length) {
  26131. positions[p] = points[i].x;
  26132. positions[p + 1] = points[i].y;
  26133. positions[p + 2] = points[i].z;
  26134. p += 3;
  26135. }
  26136. };
  26137. instance.updateMeshPositions(positionFunction, false);
  26138. return instance;
  26139. }
  26140. // dashed lines creation
  26141. var dashedLines = new BABYLON.LinesMesh(name, scene);
  26142. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  26143. vertexData.applyToMesh(dashedLines, options.updatable);
  26144. dashedLines.dashSize = dashSize;
  26145. dashedLines.gapSize = gapSize;
  26146. return dashedLines;
  26147. };
  26148. /**
  26149. * Creates an extruded shape mesh.
  26150. * 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.
  26151. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  26152. *
  26153. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26154. * 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
  26155. * extruded along the Z axis.
  26156. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26157. * 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.
  26158. * The parameter `scale` (float, default 1) is the value to scale the shape.
  26159. * 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
  26160. * 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
  26161. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26162. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26163. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26164. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26166. */
  26167. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  26168. var path = options.path;
  26169. var shape = options.shape;
  26170. var scale = options.scale || 1;
  26171. var rotation = options.rotation || 0;
  26172. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26173. var updatable = options.updatable;
  26174. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26175. var instance = options.instance;
  26176. var invertUV = options.invertUV || false;
  26177. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  26178. };
  26179. /**
  26180. * Creates an custom extruded shape mesh.
  26181. * 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.
  26182. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  26183. *
  26184. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26185. * 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
  26186. * extruded along the Z axis.
  26187. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26188. * 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
  26189. * and the distance of this point from the begining of the path :
  26190. * ```javascript
  26191. * var rotationFunction = function(i, distance) {
  26192. * // do things
  26193. * return rotationValue; }
  26194. * ```
  26195. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26196. * 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
  26197. * and the distance of this point from the begining of the path :
  26198. * ```javascript
  26199. * var scaleFunction = function(i, distance) {
  26200. * // do things
  26201. * return scaleValue;}
  26202. * ```
  26203. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26204. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26205. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26206. * 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
  26207. * 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
  26208. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26209. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26210. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26211. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26212. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26213. */
  26214. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  26215. var path = options.path;
  26216. var shape = options.shape;
  26217. var scaleFunction = options.scaleFunction || (function () { return 1; });
  26218. var rotationFunction = options.rotationFunction || (function () { return 0; });
  26219. var ribbonCloseArray = options.ribbonCloseArray || false;
  26220. var ribbonClosePath = options.ribbonClosePath || false;
  26221. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  26222. var updatable = options.updatable;
  26223. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26224. var instance = options.instance;
  26225. var invertUV = options.invertUV || false;
  26226. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  26227. };
  26228. /**
  26229. * Creates lathe mesh.
  26230. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26231. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  26232. *
  26233. * 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
  26234. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26235. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26236. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26237. * 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.
  26238. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  26239. * 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
  26240. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26241. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26242. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26243. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26244. */
  26245. MeshBuilder.CreateLathe = function (name, options, scene) {
  26246. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  26247. var closed = (options.closed === undefined) ? true : options.closed;
  26248. var shape = options.shape;
  26249. var radius = options.radius || 1;
  26250. var tessellation = options.tessellation || 64;
  26251. var updatable = options.updatable;
  26252. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26253. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26254. var pi2 = Math.PI * 2;
  26255. var paths = new Array();
  26256. var invertUV = options.invertUV || false;
  26257. var i = 0;
  26258. var p = 0;
  26259. var step = pi2 / tessellation * arc;
  26260. var rotated;
  26261. var path = new Array();
  26262. ;
  26263. for (i = 0; i <= tessellation; i++) {
  26264. var path = [];
  26265. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  26266. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  26267. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  26268. }
  26269. for (p = 0; p < shape.length; p++) {
  26270. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  26271. path.push(rotated);
  26272. }
  26273. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  26274. 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));
  26275. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  26276. }
  26277. paths.push(path);
  26278. }
  26279. // lathe ribbon
  26280. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  26281. return lathe;
  26282. };
  26283. /**
  26284. * Creates a plane mesh.
  26285. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26286. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26287. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  26288. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  26289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26290. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26292. */
  26293. MeshBuilder.CreatePlane = function (name, options, scene) {
  26294. var plane = new BABYLON.Mesh(name, scene);
  26295. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26296. plane.sideOrientation = options.sideOrientation;
  26297. var vertexData = BABYLON.VertexData.CreatePlane(options);
  26298. vertexData.applyToMesh(plane, options.updatable);
  26299. if (options.sourcePlane) {
  26300. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  26301. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  26302. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  26303. plane.rotate(vectorProduct, product);
  26304. }
  26305. return plane;
  26306. };
  26307. /**
  26308. * Creates a ground mesh.
  26309. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  26310. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26311. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  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.CreateGround = function (name, options, scene) {
  26315. var ground = new BABYLON.GroundMesh(name, scene);
  26316. ground._setReady(false);
  26317. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26318. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26319. ground._width = options.width || 1;
  26320. ground._height = options.height || 1;
  26321. ground._maxX = ground._width / 2;
  26322. ground._maxZ = ground._height / 2;
  26323. ground._minX = -ground._maxX;
  26324. ground._minZ = -ground._maxZ;
  26325. var vertexData = BABYLON.VertexData.CreateGround(options);
  26326. vertexData.applyToMesh(ground, options.updatable);
  26327. ground._setReady(true);
  26328. return ground;
  26329. };
  26330. /**
  26331. * Creates a tiled ground mesh.
  26332. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  26333. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26334. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26335. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26336. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26337. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26338. * numbers of subdivisions on the ground width and height of each tile.
  26339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26340. */
  26341. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  26342. var tiledGround = new BABYLON.Mesh(name, scene);
  26343. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  26344. vertexData.applyToMesh(tiledGround, options.updatable);
  26345. return tiledGround;
  26346. };
  26347. /**
  26348. * Creates a ground mesh from a height map.
  26349. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26350. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  26351. * The parameter `url` sets the URL of the height map image resource.
  26352. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26353. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26354. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26355. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26356. * 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.
  26357. * 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).
  26358. * This function is passed the newly built mesh :
  26359. * ```javascript
  26360. * function(mesh) { // do things
  26361. * return; }
  26362. * ```
  26363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26364. */
  26365. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  26366. var width = options.width || 10.0;
  26367. var height = options.height || 10.0;
  26368. var subdivisions = options.subdivisions || 1 | 0;
  26369. var minHeight = options.minHeight || 0.0;
  26370. var maxHeight = options.maxHeight || 10.0;
  26371. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26372. var updatable = options.updatable;
  26373. var onReady = options.onReady;
  26374. var ground = new BABYLON.GroundMesh(name, scene);
  26375. ground._subdivisionsX = subdivisions;
  26376. ground._subdivisionsY = subdivisions;
  26377. ground._width = width;
  26378. ground._height = height;
  26379. ground._maxX = ground._width / 2.0;
  26380. ground._maxZ = ground._height / 2.0;
  26381. ground._minX = -ground._maxX;
  26382. ground._minZ = -ground._maxZ;
  26383. ground._setReady(false);
  26384. var onload = function (img) {
  26385. // Getting height map data
  26386. var canvas = document.createElement("canvas");
  26387. var context = canvas.getContext("2d");
  26388. var bufferWidth = img.width;
  26389. var bufferHeight = img.height;
  26390. canvas.width = bufferWidth;
  26391. canvas.height = bufferHeight;
  26392. context.drawImage(img, 0, 0);
  26393. // Create VertexData from map data
  26394. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26395. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  26396. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  26397. width: width, height: height,
  26398. subdivisions: subdivisions,
  26399. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  26400. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  26401. });
  26402. vertexData.applyToMesh(ground, updatable);
  26403. ground._setReady(true);
  26404. //execute ready callback, if set
  26405. if (onReady) {
  26406. onReady(ground);
  26407. }
  26408. };
  26409. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26410. return ground;
  26411. };
  26412. /**
  26413. * Creates a tube mesh.
  26414. * 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.
  26415. *
  26416. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  26417. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26418. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26419. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26420. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26421. * 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.
  26422. * It must return a radius value (positive float) :
  26423. * ```javascript
  26424. * var radiusFunction = function(i, distance) {
  26425. * // do things
  26426. * return radius; }
  26427. * ```
  26428. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  26429. * 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
  26430. * 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
  26431. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26432. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26433. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  26434. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26435. */
  26436. MeshBuilder.CreateTube = function (name, options, scene) {
  26437. var path = options.path;
  26438. var radius = options.radius || 1.0;
  26439. var tessellation = options.tessellation || 64 | 0;
  26440. var radiusFunction = options.radiusFunction;
  26441. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  26442. var invertUV = options.invertUV || false;
  26443. var updatable = options.updatable;
  26444. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26445. var instance = options.instance;
  26446. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  26447. // tube geometry
  26448. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  26449. var tangents = path3D.getTangents();
  26450. var normals = path3D.getNormals();
  26451. var distances = path3D.getDistances();
  26452. var pi2 = Math.PI * 2;
  26453. var step = pi2 / tessellation * arc;
  26454. var returnRadius = function () { return radius; };
  26455. var radiusFunctionFinal = radiusFunction || returnRadius;
  26456. var circlePath;
  26457. var rad;
  26458. var normal;
  26459. var rotated;
  26460. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26461. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26462. for (var i = 0; i < path.length; i++) {
  26463. rad = radiusFunctionFinal(i, distances[i]); // current radius
  26464. circlePath = Array(); // current circle array
  26465. normal = normals[i]; // current normal
  26466. for (var t = 0; t < tessellation; t++) {
  26467. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  26468. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  26469. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  26470. rotated.scaleInPlace(rad).addInPlace(path[i]);
  26471. circlePath[t] = rotated;
  26472. }
  26473. circlePaths[index] = circlePath;
  26474. index++;
  26475. }
  26476. // cap
  26477. var capPath = function (nbPoints, pathIndex) {
  26478. var pointCap = Array();
  26479. for (var i = 0; i < nbPoints; i++) {
  26480. pointCap.push(path[pathIndex]);
  26481. }
  26482. return pointCap;
  26483. };
  26484. switch (cap) {
  26485. case BABYLON.Mesh.NO_CAP:
  26486. break;
  26487. case BABYLON.Mesh.CAP_START:
  26488. circlePaths[0] = capPath(tessellation, 0);
  26489. circlePaths[1] = circlePaths[2].slice(0);
  26490. break;
  26491. case BABYLON.Mesh.CAP_END:
  26492. circlePaths[index] = circlePaths[index - 1].slice(0);
  26493. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26494. break;
  26495. case BABYLON.Mesh.CAP_ALL:
  26496. circlePaths[0] = capPath(tessellation, 0);
  26497. circlePaths[1] = circlePaths[2].slice(0);
  26498. circlePaths[index] = circlePaths[index - 1].slice(0);
  26499. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  26500. break;
  26501. default:
  26502. break;
  26503. }
  26504. return circlePaths;
  26505. };
  26506. var path3D;
  26507. var pathArray;
  26508. if (instance) {
  26509. var arc = options.arc || instance.arc;
  26510. path3D = (instance.path3D).update(path);
  26511. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  26512. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  26513. instance.path3D = path3D;
  26514. instance.pathArray = pathArray;
  26515. instance.arc = arc;
  26516. return instance;
  26517. }
  26518. // tube creation
  26519. path3D = new BABYLON.Path3D(path);
  26520. var newPathArray = new Array();
  26521. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26522. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  26523. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  26524. tube.pathArray = pathArray;
  26525. tube.path3D = path3D;
  26526. tube.tessellation = tessellation;
  26527. tube.cap = cap;
  26528. tube.arc = options.arc;
  26529. return tube;
  26530. };
  26531. /**
  26532. * Creates a polyhedron mesh.
  26533. *
  26534. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  26535. * 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
  26536. * to choose the wanted type.
  26537. * The parameter `size` (positive float, default 1) sets the polygon size.
  26538. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26539. * 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`.
  26540. * 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
  26541. * 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)`).
  26542. * 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
  26543. * 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.
  26544. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26545. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26546. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26547. */
  26548. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  26549. var polyhedron = new BABYLON.Mesh(name, scene);
  26550. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  26551. polyhedron.sideOrientation = options.sideOrientation;
  26552. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  26553. vertexData.applyToMesh(polyhedron, options.updatable);
  26554. return polyhedron;
  26555. };
  26556. /**
  26557. * Creates a decal mesh.
  26558. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  26559. * 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.
  26560. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  26561. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  26562. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  26563. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  26564. */
  26565. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  26566. var indices = sourceMesh.getIndices();
  26567. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26568. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26569. var position = options.position || BABYLON.Vector3.Zero();
  26570. var normal = options.normal || BABYLON.Vector3.Up();
  26571. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  26572. var angle = options.angle || 0;
  26573. // Getting correct rotation
  26574. if (!normal) {
  26575. var target = new BABYLON.Vector3(0, 0, 1);
  26576. var camera = sourceMesh.getScene().activeCamera;
  26577. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  26578. normal = camera.globalPosition.subtract(cameraWorldTarget);
  26579. }
  26580. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  26581. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  26582. var pitch = Math.atan2(normal.y, len);
  26583. // Matrix
  26584. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  26585. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  26586. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  26587. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  26588. var vertexData = new BABYLON.VertexData();
  26589. vertexData.indices = [];
  26590. vertexData.positions = [];
  26591. vertexData.normals = [];
  26592. vertexData.uvs = [];
  26593. var currentVertexDataIndex = 0;
  26594. var extractDecalVector3 = function (indexId) {
  26595. var vertexId = indices[indexId];
  26596. var result = new BABYLON.PositionNormalVertex();
  26597. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  26598. // Send vector to decal local world
  26599. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  26600. // Get normal
  26601. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  26602. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  26603. return result;
  26604. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  26605. var clip = function (vertices, axis) {
  26606. if (vertices.length === 0) {
  26607. return vertices;
  26608. }
  26609. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  26610. var clipVertices = function (v0, v1) {
  26611. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  26612. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  26613. };
  26614. var result = new Array();
  26615. for (var index = 0; index < vertices.length; index += 3) {
  26616. var v1Out;
  26617. var v2Out;
  26618. var v3Out;
  26619. var total = 0;
  26620. var nV1, nV2, nV3, nV4;
  26621. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  26622. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  26623. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  26624. v1Out = d1 > 0;
  26625. v2Out = d2 > 0;
  26626. v3Out = d3 > 0;
  26627. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  26628. switch (total) {
  26629. case 0:
  26630. result.push(vertices[index]);
  26631. result.push(vertices[index + 1]);
  26632. result.push(vertices[index + 2]);
  26633. break;
  26634. case 1:
  26635. if (v1Out) {
  26636. nV1 = vertices[index + 1];
  26637. nV2 = vertices[index + 2];
  26638. nV3 = clipVertices(vertices[index], nV1);
  26639. nV4 = clipVertices(vertices[index], nV2);
  26640. }
  26641. if (v2Out) {
  26642. nV1 = vertices[index];
  26643. nV2 = vertices[index + 2];
  26644. nV3 = clipVertices(vertices[index + 1], nV1);
  26645. nV4 = clipVertices(vertices[index + 1], nV2);
  26646. result.push(nV3);
  26647. result.push(nV2.clone());
  26648. result.push(nV1.clone());
  26649. result.push(nV2.clone());
  26650. result.push(nV3.clone());
  26651. result.push(nV4);
  26652. break;
  26653. }
  26654. if (v3Out) {
  26655. nV1 = vertices[index];
  26656. nV2 = vertices[index + 1];
  26657. nV3 = clipVertices(vertices[index + 2], nV1);
  26658. nV4 = clipVertices(vertices[index + 2], nV2);
  26659. }
  26660. result.push(nV1.clone());
  26661. result.push(nV2.clone());
  26662. result.push(nV3);
  26663. result.push(nV4);
  26664. result.push(nV3.clone());
  26665. result.push(nV2.clone());
  26666. break;
  26667. case 2:
  26668. if (!v1Out) {
  26669. nV1 = vertices[index].clone();
  26670. nV2 = clipVertices(nV1, vertices[index + 1]);
  26671. nV3 = clipVertices(nV1, vertices[index + 2]);
  26672. result.push(nV1);
  26673. result.push(nV2);
  26674. result.push(nV3);
  26675. }
  26676. if (!v2Out) {
  26677. nV1 = vertices[index + 1].clone();
  26678. nV2 = clipVertices(nV1, vertices[index + 2]);
  26679. nV3 = clipVertices(nV1, vertices[index]);
  26680. result.push(nV1);
  26681. result.push(nV2);
  26682. result.push(nV3);
  26683. }
  26684. if (!v3Out) {
  26685. nV1 = vertices[index + 2].clone();
  26686. nV2 = clipVertices(nV1, vertices[index]);
  26687. nV3 = clipVertices(nV1, vertices[index + 1]);
  26688. result.push(nV1);
  26689. result.push(nV2);
  26690. result.push(nV3);
  26691. }
  26692. break;
  26693. case 3:
  26694. break;
  26695. }
  26696. }
  26697. return result;
  26698. };
  26699. for (var index = 0; index < indices.length; index += 3) {
  26700. var faceVertices = new Array();
  26701. faceVertices.push(extractDecalVector3(index));
  26702. faceVertices.push(extractDecalVector3(index + 1));
  26703. faceVertices.push(extractDecalVector3(index + 2));
  26704. // Clip
  26705. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  26706. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  26707. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  26708. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  26709. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  26710. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  26711. if (faceVertices.length === 0) {
  26712. continue;
  26713. }
  26714. // Add UVs and get back to world
  26715. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  26716. var vertex = faceVertices[vIndex];
  26717. //TODO check for Int32Array | Uint32Array | Uint16Array
  26718. vertexData.indices.push(currentVertexDataIndex);
  26719. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  26720. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  26721. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  26722. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  26723. currentVertexDataIndex++;
  26724. }
  26725. }
  26726. // Return mesh
  26727. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  26728. vertexData.applyToMesh(decal);
  26729. decal.position = position.clone();
  26730. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  26731. return decal;
  26732. };
  26733. // Privates
  26734. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  26735. // extrusion geometry
  26736. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  26737. var tangents = path3D.getTangents();
  26738. var normals = path3D.getNormals();
  26739. var binormals = path3D.getBinormals();
  26740. var distances = path3D.getDistances();
  26741. var angle = 0;
  26742. var returnScale = function () { return scale; };
  26743. var returnRotation = function () { return rotation; };
  26744. var rotate = custom ? rotateFunction : returnRotation;
  26745. var scl = custom ? scaleFunction : returnScale;
  26746. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  26747. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  26748. for (var i = 0; i < curve.length; i++) {
  26749. var shapePath = new Array();
  26750. var angleStep = rotate(i, distances[i]);
  26751. var scaleRatio = scl(i, distances[i]);
  26752. for (var p = 0; p < shape.length; p++) {
  26753. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  26754. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  26755. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  26756. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  26757. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  26758. shapePath[p] = rotated;
  26759. }
  26760. shapePaths[index] = shapePath;
  26761. angle += angleStep;
  26762. index++;
  26763. }
  26764. // cap
  26765. var capPath = function (shapePath) {
  26766. var pointCap = Array();
  26767. var barycenter = BABYLON.Vector3.Zero();
  26768. var i;
  26769. for (i = 0; i < shapePath.length; i++) {
  26770. barycenter.addInPlace(shapePath[i]);
  26771. }
  26772. barycenter.scaleInPlace(1.0 / shapePath.length);
  26773. for (i = 0; i < shapePath.length; i++) {
  26774. pointCap.push(barycenter);
  26775. }
  26776. return pointCap;
  26777. };
  26778. switch (cap) {
  26779. case BABYLON.Mesh.NO_CAP:
  26780. break;
  26781. case BABYLON.Mesh.CAP_START:
  26782. shapePaths[0] = capPath(shapePaths[2]);
  26783. shapePaths[1] = shapePaths[2];
  26784. break;
  26785. case BABYLON.Mesh.CAP_END:
  26786. shapePaths[index] = shapePaths[index - 1];
  26787. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26788. break;
  26789. case BABYLON.Mesh.CAP_ALL:
  26790. shapePaths[0] = capPath(shapePaths[2]);
  26791. shapePaths[1] = shapePaths[2];
  26792. shapePaths[index] = shapePaths[index - 1];
  26793. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  26794. break;
  26795. default:
  26796. break;
  26797. }
  26798. return shapePaths;
  26799. };
  26800. var path3D;
  26801. var pathArray;
  26802. if (instance) {
  26803. path3D = (instance.path3D).update(curve);
  26804. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  26805. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  26806. return instance;
  26807. }
  26808. // extruded shape creation
  26809. path3D = new BABYLON.Path3D(curve);
  26810. var newShapePaths = new Array();
  26811. cap = (cap < 0 || cap > 3) ? 0 : cap;
  26812. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  26813. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  26814. extrudedGeneric.pathArray = pathArray;
  26815. extrudedGeneric.path3D = path3D;
  26816. extrudedGeneric.cap = cap;
  26817. return extrudedGeneric;
  26818. };
  26819. return MeshBuilder;
  26820. }());
  26821. BABYLON.MeshBuilder = MeshBuilder;
  26822. })(BABYLON || (BABYLON = {}));
  26823. //# sourceMappingURL=babylon.meshBuilder.js.map
  26824. var BABYLON;
  26825. (function (BABYLON) {
  26826. var BaseTexture = (function () {
  26827. function BaseTexture(scene) {
  26828. this.hasAlpha = false;
  26829. this.getAlphaFromRGB = false;
  26830. this.level = 1;
  26831. this.coordinatesIndex = 0;
  26832. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26833. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26834. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26835. this.anisotropicFilteringLevel = 4;
  26836. this.isCube = false;
  26837. this.isRenderTarget = false;
  26838. this.animations = new Array();
  26839. /**
  26840. * An event triggered when the texture is disposed.
  26841. * @type {BABYLON.Observable}
  26842. */
  26843. this.onDisposeObservable = new BABYLON.Observable();
  26844. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26845. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26846. this._scene.textures.push(this);
  26847. this._uid = null;
  26848. }
  26849. Object.defineProperty(BaseTexture.prototype, "uid", {
  26850. get: function () {
  26851. if (!this._uid) {
  26852. this._uid = BABYLON.Tools.RandomId();
  26853. }
  26854. return this._uid;
  26855. },
  26856. enumerable: true,
  26857. configurable: true
  26858. });
  26859. BaseTexture.prototype.toString = function () {
  26860. return this.name;
  26861. };
  26862. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26863. set: function (callback) {
  26864. if (this._onDisposeObserver) {
  26865. this.onDisposeObservable.remove(this._onDisposeObserver);
  26866. }
  26867. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26868. },
  26869. enumerable: true,
  26870. configurable: true
  26871. });
  26872. BaseTexture.prototype.getScene = function () {
  26873. return this._scene;
  26874. };
  26875. BaseTexture.prototype.getTextureMatrix = function () {
  26876. return null;
  26877. };
  26878. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26879. return null;
  26880. };
  26881. BaseTexture.prototype.getInternalTexture = function () {
  26882. return this._texture;
  26883. };
  26884. BaseTexture.prototype.isReady = function () {
  26885. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26886. return true;
  26887. }
  26888. if (this._texture) {
  26889. return this._texture.isReady;
  26890. }
  26891. return false;
  26892. };
  26893. BaseTexture.prototype.getSize = function () {
  26894. if (this._texture._width) {
  26895. return new BABYLON.Size(this._texture._width, this._texture._height);
  26896. }
  26897. if (this._texture._size) {
  26898. return new BABYLON.Size(this._texture._size, this._texture._size);
  26899. }
  26900. return BABYLON.Size.Zero();
  26901. };
  26902. BaseTexture.prototype.getBaseSize = function () {
  26903. if (!this.isReady() || !this._texture)
  26904. return BABYLON.Size.Zero();
  26905. if (this._texture._size) {
  26906. return new BABYLON.Size(this._texture._size, this._texture._size);
  26907. }
  26908. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  26909. };
  26910. BaseTexture.prototype.scale = function (ratio) {
  26911. };
  26912. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26913. get: function () {
  26914. return false;
  26915. },
  26916. enumerable: true,
  26917. configurable: true
  26918. });
  26919. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  26920. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26921. for (var index = 0; index < texturesCache.length; index++) {
  26922. var texturesCacheEntry = texturesCache[index];
  26923. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26924. texturesCache.splice(index, 1);
  26925. return;
  26926. }
  26927. }
  26928. };
  26929. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26930. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26931. for (var index = 0; index < texturesCache.length; index++) {
  26932. var texturesCacheEntry = texturesCache[index];
  26933. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  26934. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26935. texturesCacheEntry.references++;
  26936. return texturesCacheEntry;
  26937. }
  26938. }
  26939. }
  26940. return null;
  26941. };
  26942. BaseTexture.prototype.delayLoad = function () {
  26943. };
  26944. BaseTexture.prototype.clone = function () {
  26945. return null;
  26946. };
  26947. BaseTexture.prototype.releaseInternalTexture = function () {
  26948. if (this._texture) {
  26949. this._scene.getEngine().releaseInternalTexture(this._texture);
  26950. delete this._texture;
  26951. }
  26952. };
  26953. BaseTexture.prototype.dispose = function () {
  26954. // Animations
  26955. this.getScene().stopAnimation(this);
  26956. // Remove from scene
  26957. this._scene._removePendingData(this);
  26958. var index = this._scene.textures.indexOf(this);
  26959. if (index >= 0) {
  26960. this._scene.textures.splice(index, 1);
  26961. }
  26962. if (this._texture === undefined) {
  26963. return;
  26964. }
  26965. // Release
  26966. this.releaseInternalTexture();
  26967. // Callback
  26968. this.onDisposeObservable.notifyObservers(this);
  26969. this.onDisposeObservable.clear();
  26970. };
  26971. BaseTexture.prototype.serialize = function () {
  26972. if (!this.name) {
  26973. return null;
  26974. }
  26975. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26976. // Animations
  26977. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26978. return serializationObject;
  26979. };
  26980. return BaseTexture;
  26981. }());
  26982. __decorate([
  26983. BABYLON.serialize()
  26984. ], BaseTexture.prototype, "name", void 0);
  26985. __decorate([
  26986. BABYLON.serialize()
  26987. ], BaseTexture.prototype, "hasAlpha", void 0);
  26988. __decorate([
  26989. BABYLON.serialize()
  26990. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26991. __decorate([
  26992. BABYLON.serialize()
  26993. ], BaseTexture.prototype, "level", void 0);
  26994. __decorate([
  26995. BABYLON.serialize()
  26996. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26997. __decorate([
  26998. BABYLON.serialize()
  26999. ], BaseTexture.prototype, "coordinatesMode", void 0);
  27000. __decorate([
  27001. BABYLON.serialize()
  27002. ], BaseTexture.prototype, "wrapU", void 0);
  27003. __decorate([
  27004. BABYLON.serialize()
  27005. ], BaseTexture.prototype, "wrapV", void 0);
  27006. __decorate([
  27007. BABYLON.serialize()
  27008. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27009. __decorate([
  27010. BABYLON.serialize()
  27011. ], BaseTexture.prototype, "isCube", void 0);
  27012. __decorate([
  27013. BABYLON.serialize()
  27014. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27015. BABYLON.BaseTexture = BaseTexture;
  27016. })(BABYLON || (BABYLON = {}));
  27017. //# sourceMappingURL=babylon.baseTexture.js.map
  27018. var BABYLON;
  27019. (function (BABYLON) {
  27020. var Texture = (function (_super) {
  27021. __extends(Texture, _super);
  27022. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27023. if (noMipmap === void 0) { noMipmap = false; }
  27024. if (invertY === void 0) { invertY = true; }
  27025. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27026. if (onLoad === void 0) { onLoad = null; }
  27027. if (onError === void 0) { onError = null; }
  27028. if (buffer === void 0) { buffer = null; }
  27029. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27030. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27031. var _this = _super.call(this, scene) || this;
  27032. _this.uOffset = 0;
  27033. _this.vOffset = 0;
  27034. _this.uScale = 1.0;
  27035. _this.vScale = 1.0;
  27036. _this.uAng = 0;
  27037. _this.vAng = 0;
  27038. _this.wAng = 0;
  27039. _this.name = url;
  27040. _this.url = url;
  27041. _this._noMipmap = noMipmap;
  27042. _this._invertY = invertY;
  27043. _this._samplingMode = samplingMode;
  27044. _this._buffer = buffer;
  27045. _this._deleteBuffer = deleteBuffer;
  27046. _this._format = format;
  27047. if (!url) {
  27048. return _this;
  27049. }
  27050. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  27051. var load = function () {
  27052. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  27053. _this.onLoadObservable.notifyObservers(true);
  27054. }
  27055. if (onLoad) {
  27056. onLoad();
  27057. }
  27058. };
  27059. if (!_this._texture) {
  27060. if (!scene.useDelayedTextureLoading) {
  27061. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  27062. if (deleteBuffer) {
  27063. delete _this._buffer;
  27064. }
  27065. }
  27066. else {
  27067. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27068. _this._delayedOnLoad = load;
  27069. _this._delayedOnError = onError;
  27070. }
  27071. }
  27072. else {
  27073. if (_this._texture.isReady) {
  27074. BABYLON.Tools.SetImmediate(function () { return load(); });
  27075. }
  27076. else {
  27077. _this._texture.onLoadedCallbacks.push(load);
  27078. }
  27079. }
  27080. return _this;
  27081. }
  27082. Object.defineProperty(Texture.prototype, "noMipmap", {
  27083. get: function () {
  27084. return this._noMipmap;
  27085. },
  27086. enumerable: true,
  27087. configurable: true
  27088. });
  27089. Texture.prototype.delayLoad = function () {
  27090. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27091. return;
  27092. }
  27093. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27094. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27095. if (!this._texture) {
  27096. 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);
  27097. if (this._deleteBuffer) {
  27098. delete this._buffer;
  27099. }
  27100. }
  27101. };
  27102. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27103. if (!this._texture) {
  27104. return;
  27105. }
  27106. this._samplingMode = samplingMode;
  27107. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27108. };
  27109. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27110. x *= this.uScale;
  27111. y *= this.vScale;
  27112. x -= 0.5 * this.uScale;
  27113. y -= 0.5 * this.vScale;
  27114. z -= 0.5;
  27115. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27116. t.x += 0.5 * this.uScale + this.uOffset;
  27117. t.y += 0.5 * this.vScale + this.vOffset;
  27118. t.z += 0.5;
  27119. };
  27120. Texture.prototype.getTextureMatrix = function () {
  27121. if (this.uOffset === this._cachedUOffset &&
  27122. this.vOffset === this._cachedVOffset &&
  27123. this.uScale === this._cachedUScale &&
  27124. this.vScale === this._cachedVScale &&
  27125. this.uAng === this._cachedUAng &&
  27126. this.vAng === this._cachedVAng &&
  27127. this.wAng === this._cachedWAng) {
  27128. return this._cachedTextureMatrix;
  27129. }
  27130. this._cachedUOffset = this.uOffset;
  27131. this._cachedVOffset = this.vOffset;
  27132. this._cachedUScale = this.uScale;
  27133. this._cachedVScale = this.vScale;
  27134. this._cachedUAng = this.uAng;
  27135. this._cachedVAng = this.vAng;
  27136. this._cachedWAng = this.wAng;
  27137. if (!this._cachedTextureMatrix) {
  27138. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27139. this._rowGenerationMatrix = new BABYLON.Matrix();
  27140. this._t0 = BABYLON.Vector3.Zero();
  27141. this._t1 = BABYLON.Vector3.Zero();
  27142. this._t2 = BABYLON.Vector3.Zero();
  27143. }
  27144. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27145. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27146. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27147. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27148. this._t1.subtractInPlace(this._t0);
  27149. this._t2.subtractInPlace(this._t0);
  27150. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27151. this._cachedTextureMatrix.m[0] = this._t1.x;
  27152. this._cachedTextureMatrix.m[1] = this._t1.y;
  27153. this._cachedTextureMatrix.m[2] = this._t1.z;
  27154. this._cachedTextureMatrix.m[4] = this._t2.x;
  27155. this._cachedTextureMatrix.m[5] = this._t2.y;
  27156. this._cachedTextureMatrix.m[6] = this._t2.z;
  27157. this._cachedTextureMatrix.m[8] = this._t0.x;
  27158. this._cachedTextureMatrix.m[9] = this._t0.y;
  27159. this._cachedTextureMatrix.m[10] = this._t0.z;
  27160. return this._cachedTextureMatrix;
  27161. };
  27162. Texture.prototype.getReflectionTextureMatrix = function () {
  27163. if (this.uOffset === this._cachedUOffset &&
  27164. this.vOffset === this._cachedVOffset &&
  27165. this.uScale === this._cachedUScale &&
  27166. this.vScale === this._cachedVScale &&
  27167. this.coordinatesMode === this._cachedCoordinatesMode) {
  27168. return this._cachedTextureMatrix;
  27169. }
  27170. if (!this._cachedTextureMatrix) {
  27171. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27172. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27173. }
  27174. this._cachedCoordinatesMode = this.coordinatesMode;
  27175. switch (this.coordinatesMode) {
  27176. case Texture.PLANAR_MODE:
  27177. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27178. this._cachedTextureMatrix[0] = this.uScale;
  27179. this._cachedTextureMatrix[5] = this.vScale;
  27180. this._cachedTextureMatrix[12] = this.uOffset;
  27181. this._cachedTextureMatrix[13] = this.vOffset;
  27182. break;
  27183. case Texture.PROJECTION_MODE:
  27184. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27185. this._projectionModeMatrix.m[0] = 0.5;
  27186. this._projectionModeMatrix.m[5] = -0.5;
  27187. this._projectionModeMatrix.m[10] = 0.0;
  27188. this._projectionModeMatrix.m[12] = 0.5;
  27189. this._projectionModeMatrix.m[13] = 0.5;
  27190. this._projectionModeMatrix.m[14] = 1.0;
  27191. this._projectionModeMatrix.m[15] = 1.0;
  27192. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27193. break;
  27194. default:
  27195. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27196. break;
  27197. }
  27198. return this._cachedTextureMatrix;
  27199. };
  27200. Texture.prototype.clone = function () {
  27201. var _this = this;
  27202. return BABYLON.SerializationHelper.Clone(function () {
  27203. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27204. }, this);
  27205. };
  27206. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27207. get: function () {
  27208. if (!this._onLoadObservarble) {
  27209. this._onLoadObservarble = new BABYLON.Observable();
  27210. }
  27211. return this._onLoadObservarble;
  27212. },
  27213. enumerable: true,
  27214. configurable: true
  27215. });
  27216. // Statics
  27217. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27218. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27219. if (onLoad === void 0) { onLoad = null; }
  27220. if (onError === void 0) { onError = null; }
  27221. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27222. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27223. };
  27224. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27225. if (parsedTexture.customType) {
  27226. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27227. return customTexture.Parse(parsedTexture, scene, rootUrl);
  27228. }
  27229. if (parsedTexture.isCube) {
  27230. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27231. }
  27232. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27233. return null;
  27234. }
  27235. var texture = BABYLON.SerializationHelper.Parse(function () {
  27236. if (parsedTexture.mirrorPlane) {
  27237. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27238. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27239. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27240. return mirrorTexture;
  27241. }
  27242. else if (parsedTexture.isRenderTarget) {
  27243. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  27244. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27245. return renderTargetTexture;
  27246. }
  27247. else {
  27248. var texture;
  27249. if (parsedTexture.base64String) {
  27250. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  27251. }
  27252. else {
  27253. texture = new Texture(rootUrl + parsedTexture.name, scene);
  27254. }
  27255. return texture;
  27256. }
  27257. }, parsedTexture, scene);
  27258. // Animations
  27259. if (parsedTexture.animations) {
  27260. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27261. var parsedAnimation = parsedTexture.animations[animationIndex];
  27262. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27263. }
  27264. }
  27265. return texture;
  27266. };
  27267. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27268. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27269. if (noMipmap === void 0) { noMipmap = false; }
  27270. if (invertY === void 0) { invertY = true; }
  27271. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27272. if (onLoad === void 0) { onLoad = null; }
  27273. if (onError === void 0) { onError = null; }
  27274. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27275. if (name.substr(0, 5) !== "data:") {
  27276. name = "data:" + name;
  27277. }
  27278. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27279. };
  27280. return Texture;
  27281. }(BABYLON.BaseTexture));
  27282. // Constants
  27283. Texture.NEAREST_SAMPLINGMODE = 1;
  27284. Texture.BILINEAR_SAMPLINGMODE = 2;
  27285. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27286. Texture.EXPLICIT_MODE = 0;
  27287. Texture.SPHERICAL_MODE = 1;
  27288. Texture.PLANAR_MODE = 2;
  27289. Texture.CUBIC_MODE = 3;
  27290. Texture.PROJECTION_MODE = 4;
  27291. Texture.SKYBOX_MODE = 5;
  27292. Texture.INVCUBIC_MODE = 6;
  27293. Texture.EQUIRECTANGULAR_MODE = 7;
  27294. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27295. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27296. Texture.CLAMP_ADDRESSMODE = 0;
  27297. Texture.WRAP_ADDRESSMODE = 1;
  27298. Texture.MIRROR_ADDRESSMODE = 2;
  27299. __decorate([
  27300. BABYLON.serialize()
  27301. ], Texture.prototype, "url", void 0);
  27302. __decorate([
  27303. BABYLON.serialize()
  27304. ], Texture.prototype, "uOffset", void 0);
  27305. __decorate([
  27306. BABYLON.serialize()
  27307. ], Texture.prototype, "vOffset", void 0);
  27308. __decorate([
  27309. BABYLON.serialize()
  27310. ], Texture.prototype, "uScale", void 0);
  27311. __decorate([
  27312. BABYLON.serialize()
  27313. ], Texture.prototype, "vScale", void 0);
  27314. __decorate([
  27315. BABYLON.serialize()
  27316. ], Texture.prototype, "uAng", void 0);
  27317. __decorate([
  27318. BABYLON.serialize()
  27319. ], Texture.prototype, "vAng", void 0);
  27320. __decorate([
  27321. BABYLON.serialize()
  27322. ], Texture.prototype, "wAng", void 0);
  27323. BABYLON.Texture = Texture;
  27324. })(BABYLON || (BABYLON = {}));
  27325. //# sourceMappingURL=babylon.texture.js.map
  27326. var BABYLON;
  27327. (function (BABYLON) {
  27328. var CubeTexture = (function (_super) {
  27329. __extends(CubeTexture, _super);
  27330. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  27331. if (onLoad === void 0) { onLoad = null; }
  27332. if (onError === void 0) { onError = null; }
  27333. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27334. var _this = _super.call(this, scene) || this;
  27335. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  27336. _this.name = rootUrl;
  27337. _this.url = rootUrl;
  27338. _this._noMipmap = noMipmap;
  27339. _this.hasAlpha = false;
  27340. _this._format = format;
  27341. if (!rootUrl && !files) {
  27342. return _this;
  27343. }
  27344. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  27345. if (!files) {
  27346. if (!extensions) {
  27347. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  27348. }
  27349. files = [];
  27350. for (var index = 0; index < extensions.length; index++) {
  27351. files.push(rootUrl + extensions[index]);
  27352. }
  27353. _this._extensions = extensions;
  27354. }
  27355. _this._files = files;
  27356. if (!_this._texture) {
  27357. if (!scene.useDelayedTextureLoading) {
  27358. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  27359. }
  27360. else {
  27361. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27362. }
  27363. }
  27364. else if (onLoad) {
  27365. if (_this._texture.isReady) {
  27366. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  27367. }
  27368. else {
  27369. _this._texture.onLoadedCallbacks.push(onLoad);
  27370. }
  27371. }
  27372. _this.isCube = true;
  27373. _this._textureMatrix = BABYLON.Matrix.Identity();
  27374. return _this;
  27375. }
  27376. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  27377. return new CubeTexture("", scene, null, noMipmap, files);
  27378. };
  27379. // Methods
  27380. CubeTexture.prototype.delayLoad = function () {
  27381. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27382. return;
  27383. }
  27384. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27385. this._texture = this._getFromCache(this.url, this._noMipmap);
  27386. if (!this._texture) {
  27387. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  27388. }
  27389. };
  27390. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  27391. return this._textureMatrix;
  27392. };
  27393. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  27394. var texture = BABYLON.SerializationHelper.Parse(function () {
  27395. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  27396. }, parsedTexture, scene);
  27397. // Animations
  27398. if (parsedTexture.animations) {
  27399. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27400. var parsedAnimation = parsedTexture.animations[animationIndex];
  27401. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27402. }
  27403. }
  27404. return texture;
  27405. };
  27406. CubeTexture.prototype.clone = function () {
  27407. var _this = this;
  27408. return BABYLON.SerializationHelper.Clone(function () {
  27409. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  27410. }, this);
  27411. };
  27412. return CubeTexture;
  27413. }(BABYLON.BaseTexture));
  27414. BABYLON.CubeTexture = CubeTexture;
  27415. })(BABYLON || (BABYLON = {}));
  27416. //# sourceMappingURL=babylon.cubeTexture.js.map
  27417. var BABYLON;
  27418. (function (BABYLON) {
  27419. var RenderTargetTexture = (function (_super) {
  27420. __extends(RenderTargetTexture, _super);
  27421. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  27422. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  27423. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  27424. if (isCube === void 0) { isCube = false; }
  27425. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27426. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  27427. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  27428. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27429. _this.isCube = isCube;
  27430. /**
  27431. * Use this list to define the list of mesh you want to render.
  27432. */
  27433. _this.renderList = new Array();
  27434. _this.renderParticles = true;
  27435. _this.renderSprites = false;
  27436. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  27437. // Events
  27438. /**
  27439. * An event triggered when the texture is unbind.
  27440. * @type {BABYLON.Observable}
  27441. */
  27442. _this.onAfterUnbindObservable = new BABYLON.Observable();
  27443. /**
  27444. * An event triggered before rendering the texture
  27445. * @type {BABYLON.Observable}
  27446. */
  27447. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27448. /**
  27449. * An event triggered after rendering the texture
  27450. * @type {BABYLON.Observable}
  27451. */
  27452. _this.onAfterRenderObservable = new BABYLON.Observable();
  27453. /**
  27454. * An event triggered after the texture clear
  27455. * @type {BABYLON.Observable}
  27456. */
  27457. _this.onClearObservable = new BABYLON.Observable();
  27458. _this._currentRefreshId = -1;
  27459. _this._refreshRate = 1;
  27460. _this._samples = 1;
  27461. _this.name = name;
  27462. _this.isRenderTarget = true;
  27463. _this._size = size;
  27464. _this._generateMipMaps = generateMipMaps;
  27465. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  27466. _this._renderTargetOptions = {
  27467. generateMipMaps: generateMipMaps,
  27468. type: type,
  27469. samplingMode: samplingMode,
  27470. generateDepthBuffer: generateDepthBuffer,
  27471. generateStencilBuffer: generateStencilBuffer
  27472. };
  27473. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  27474. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27475. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27476. }
  27477. if (isCube) {
  27478. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  27479. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  27480. _this._textureMatrix = BABYLON.Matrix.Identity();
  27481. }
  27482. else {
  27483. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  27484. }
  27485. // Rendering groups
  27486. _this._renderingManager = new BABYLON.RenderingManager(scene);
  27487. return _this;
  27488. }
  27489. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  27490. get: function () {
  27491. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  27492. },
  27493. enumerable: true,
  27494. configurable: true
  27495. });
  27496. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  27497. get: function () {
  27498. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  27499. },
  27500. enumerable: true,
  27501. configurable: true
  27502. });
  27503. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  27504. get: function () {
  27505. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  27506. },
  27507. enumerable: true,
  27508. configurable: true
  27509. });
  27510. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  27511. set: function (callback) {
  27512. if (this._onAfterUnbindObserver) {
  27513. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  27514. }
  27515. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  27516. },
  27517. enumerable: true,
  27518. configurable: true
  27519. });
  27520. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  27521. set: function (callback) {
  27522. if (this._onBeforeRenderObserver) {
  27523. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27524. }
  27525. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27526. },
  27527. enumerable: true,
  27528. configurable: true
  27529. });
  27530. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  27531. set: function (callback) {
  27532. if (this._onAfterRenderObserver) {
  27533. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27534. }
  27535. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27536. },
  27537. enumerable: true,
  27538. configurable: true
  27539. });
  27540. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  27541. set: function (callback) {
  27542. if (this._onClearObserver) {
  27543. this.onClearObservable.remove(this._onClearObserver);
  27544. }
  27545. this._onClearObserver = this.onClearObservable.add(callback);
  27546. },
  27547. enumerable: true,
  27548. configurable: true
  27549. });
  27550. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  27551. get: function () {
  27552. return this._samples;
  27553. },
  27554. set: function (value) {
  27555. if (this._samples === value) {
  27556. return;
  27557. }
  27558. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  27559. },
  27560. enumerable: true,
  27561. configurable: true
  27562. });
  27563. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  27564. this._currentRefreshId = -1;
  27565. };
  27566. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  27567. get: function () {
  27568. return this._refreshRate;
  27569. },
  27570. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27571. set: function (value) {
  27572. this._refreshRate = value;
  27573. this.resetRefreshCounter();
  27574. },
  27575. enumerable: true,
  27576. configurable: true
  27577. });
  27578. RenderTargetTexture.prototype._shouldRender = function () {
  27579. if (this._currentRefreshId === -1) {
  27580. this._currentRefreshId = 1;
  27581. return true;
  27582. }
  27583. if (this.refreshRate === this._currentRefreshId) {
  27584. this._currentRefreshId = 1;
  27585. return true;
  27586. }
  27587. this._currentRefreshId++;
  27588. return false;
  27589. };
  27590. RenderTargetTexture.prototype.isReady = function () {
  27591. if (!this.getScene().renderTargetsEnabled) {
  27592. return false;
  27593. }
  27594. return _super.prototype.isReady.call(this);
  27595. };
  27596. RenderTargetTexture.prototype.getRenderSize = function () {
  27597. return this._size;
  27598. };
  27599. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  27600. get: function () {
  27601. return true;
  27602. },
  27603. enumerable: true,
  27604. configurable: true
  27605. });
  27606. RenderTargetTexture.prototype.scale = function (ratio) {
  27607. var newSize = this._size * ratio;
  27608. this.resize(newSize);
  27609. };
  27610. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  27611. if (this.isCube) {
  27612. return this._textureMatrix;
  27613. }
  27614. return _super.prototype.getReflectionTextureMatrix.call(this);
  27615. };
  27616. RenderTargetTexture.prototype.resize = function (size) {
  27617. this.releaseInternalTexture();
  27618. if (this.isCube) {
  27619. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  27620. }
  27621. else {
  27622. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  27623. }
  27624. };
  27625. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  27626. var scene = this.getScene();
  27627. var engine = scene.getEngine();
  27628. if (this.useCameraPostProcesses !== undefined) {
  27629. useCameraPostProcess = this.useCameraPostProcesses;
  27630. }
  27631. if (this._waitingRenderList) {
  27632. this.renderList = [];
  27633. for (var index = 0; index < this._waitingRenderList.length; index++) {
  27634. var id = this._waitingRenderList[index];
  27635. this.renderList.push(scene.getMeshByID(id));
  27636. }
  27637. delete this._waitingRenderList;
  27638. }
  27639. // Is predicate defined?
  27640. if (this.renderListPredicate) {
  27641. this.renderList.splice(0); // Clear previous renderList
  27642. var sceneMeshes = this.getScene().meshes;
  27643. for (var index = 0; index < sceneMeshes.length; index++) {
  27644. var mesh = sceneMeshes[index];
  27645. if (this.renderListPredicate(mesh)) {
  27646. this.renderList.push(mesh);
  27647. }
  27648. }
  27649. }
  27650. if (this.renderList && this.renderList.length === 0) {
  27651. return;
  27652. }
  27653. // Set custom projection.
  27654. // Needs to be before binding to prevent changing the aspect ratio.
  27655. if (this.activeCamera) {
  27656. engine.setViewport(this.activeCamera.viewport);
  27657. if (this.activeCamera !== scene.activeCamera) {
  27658. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  27659. }
  27660. }
  27661. else {
  27662. engine.setViewport(scene.activeCamera.viewport);
  27663. }
  27664. // Prepare renderingManager
  27665. this._renderingManager.reset();
  27666. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  27667. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  27668. var sceneRenderId = scene.getRenderId();
  27669. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  27670. var mesh = currentRenderList[meshIndex];
  27671. if (mesh) {
  27672. if (!mesh.isReady()) {
  27673. // Reset _currentRefreshId
  27674. this.resetRefreshCounter();
  27675. continue;
  27676. }
  27677. mesh._preActivateForIntermediateRendering(sceneRenderId);
  27678. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  27679. mesh._activate(sceneRenderId);
  27680. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27681. var subMesh = mesh.subMeshes[subIndex];
  27682. scene._activeIndices.addCount(subMesh.indexCount, false);
  27683. this._renderingManager.dispatch(subMesh);
  27684. }
  27685. }
  27686. }
  27687. }
  27688. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  27689. var particleSystem = scene.particleSystems[particleIndex];
  27690. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  27691. continue;
  27692. }
  27693. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  27694. this._renderingManager.dispatchParticles(particleSystem);
  27695. }
  27696. }
  27697. if (this.isCube) {
  27698. for (var face = 0; face < 6; face++) {
  27699. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27700. scene.incrementRenderId();
  27701. scene.resetCachedMaterial();
  27702. }
  27703. }
  27704. else {
  27705. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  27706. }
  27707. this.onAfterUnbindObservable.notifyObservers(this);
  27708. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  27709. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  27710. }
  27711. engine.setViewport(scene.activeCamera.viewport);
  27712. scene.resetCachedMaterial();
  27713. };
  27714. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  27715. var _this = this;
  27716. var scene = this.getScene();
  27717. var engine = scene.getEngine();
  27718. // Bind
  27719. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  27720. if (this.isCube) {
  27721. engine.bindFramebuffer(this._texture, faceIndex);
  27722. }
  27723. else {
  27724. engine.bindFramebuffer(this._texture);
  27725. }
  27726. }
  27727. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  27728. // Clear
  27729. if (this.onClearObservable.hasObservers()) {
  27730. this.onClearObservable.notifyObservers(engine);
  27731. }
  27732. else {
  27733. engine.clear(scene.clearColor, true, true, true);
  27734. }
  27735. if (!this._doNotChangeAspectRatio) {
  27736. scene.updateTransformMatrix(true);
  27737. }
  27738. // Render
  27739. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  27740. if (useCameraPostProcess) {
  27741. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  27742. }
  27743. if (!this._doNotChangeAspectRatio) {
  27744. scene.updateTransformMatrix(true);
  27745. }
  27746. // Dump ?
  27747. if (dumpForDebug) {
  27748. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  27749. }
  27750. // Unbind
  27751. if (!this.isCube || faceIndex === 5) {
  27752. if (this.isCube) {
  27753. if (faceIndex === 5) {
  27754. engine.generateMipMapsForCubemap(this._texture);
  27755. }
  27756. }
  27757. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  27758. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  27759. });
  27760. }
  27761. else {
  27762. this.onAfterRenderObservable.notifyObservers(faceIndex);
  27763. }
  27764. };
  27765. /**
  27766. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  27767. * This allowed control for front to back rendering or reversly depending of the special needs.
  27768. *
  27769. * @param renderingGroupId The rendering group id corresponding to its index
  27770. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  27771. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  27772. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  27773. */
  27774. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  27775. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  27776. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  27777. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  27778. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  27779. };
  27780. /**
  27781. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  27782. *
  27783. * @param renderingGroupId The rendering group id corresponding to its index
  27784. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  27785. */
  27786. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  27787. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  27788. };
  27789. RenderTargetTexture.prototype.clone = function () {
  27790. var textureSize = this.getSize();
  27791. 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);
  27792. // Base texture
  27793. newTexture.hasAlpha = this.hasAlpha;
  27794. newTexture.level = this.level;
  27795. // RenderTarget Texture
  27796. newTexture.coordinatesMode = this.coordinatesMode;
  27797. newTexture.renderList = this.renderList.slice(0);
  27798. return newTexture;
  27799. };
  27800. RenderTargetTexture.prototype.serialize = function () {
  27801. if (!this.name) {
  27802. return null;
  27803. }
  27804. var serializationObject = _super.prototype.serialize.call(this);
  27805. serializationObject.renderTargetSize = this.getRenderSize();
  27806. serializationObject.renderList = [];
  27807. for (var index = 0; index < this.renderList.length; index++) {
  27808. serializationObject.renderList.push(this.renderList[index].id);
  27809. }
  27810. return serializationObject;
  27811. };
  27812. return RenderTargetTexture;
  27813. }(BABYLON.Texture));
  27814. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  27815. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  27816. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  27817. BABYLON.RenderTargetTexture = RenderTargetTexture;
  27818. })(BABYLON || (BABYLON = {}));
  27819. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  27820. var BABYLON;
  27821. (function (BABYLON) {
  27822. var ProceduralTexture = (function (_super) {
  27823. __extends(ProceduralTexture, _super);
  27824. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  27825. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27826. if (isCube === void 0) { isCube = false; }
  27827. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  27828. _this.isCube = isCube;
  27829. _this.isEnabled = true;
  27830. _this._currentRefreshId = -1;
  27831. _this._refreshRate = 1;
  27832. _this._vertexBuffers = {};
  27833. _this._uniforms = new Array();
  27834. _this._samplers = new Array();
  27835. _this._textures = new Array();
  27836. _this._floats = new Array();
  27837. _this._floatsArrays = {};
  27838. _this._colors3 = new Array();
  27839. _this._colors4 = new Array();
  27840. _this._vectors2 = new Array();
  27841. _this._vectors3 = new Array();
  27842. _this._matrices = new Array();
  27843. _this._fallbackTextureUsed = false;
  27844. scene._proceduralTextures.push(_this);
  27845. _this.name = name;
  27846. _this.isRenderTarget = true;
  27847. _this._size = size;
  27848. _this._generateMipMaps = generateMipMaps;
  27849. _this.setFragment(fragment);
  27850. _this._fallbackTexture = fallbackTexture;
  27851. var engine = scene.getEngine();
  27852. if (isCube) {
  27853. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  27854. _this.setFloat("face", 0);
  27855. }
  27856. else {
  27857. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  27858. }
  27859. // VBO
  27860. var vertices = [];
  27861. vertices.push(1, 1);
  27862. vertices.push(-1, 1);
  27863. vertices.push(-1, -1);
  27864. vertices.push(1, -1);
  27865. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27866. // Indices
  27867. var indices = [];
  27868. indices.push(0);
  27869. indices.push(1);
  27870. indices.push(2);
  27871. indices.push(0);
  27872. indices.push(2);
  27873. indices.push(3);
  27874. _this._indexBuffer = engine.createIndexBuffer(indices);
  27875. return _this;
  27876. }
  27877. ProceduralTexture.prototype.reset = function () {
  27878. if (this._effect === undefined) {
  27879. return;
  27880. }
  27881. var engine = this.getScene().getEngine();
  27882. engine._releaseEffect(this._effect);
  27883. };
  27884. ProceduralTexture.prototype.isReady = function () {
  27885. var _this = this;
  27886. var engine = this.getScene().getEngine();
  27887. var shaders;
  27888. if (!this._fragment) {
  27889. return false;
  27890. }
  27891. if (this._fallbackTextureUsed) {
  27892. return true;
  27893. }
  27894. if (this._fragment.fragmentElement !== undefined) {
  27895. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  27896. }
  27897. else {
  27898. shaders = { vertex: "procedural", fragment: this._fragment };
  27899. }
  27900. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  27901. _this.releaseInternalTexture();
  27902. if (_this._fallbackTexture) {
  27903. _this._texture = _this._fallbackTexture._texture;
  27904. _this._texture.references++;
  27905. }
  27906. _this._fallbackTextureUsed = true;
  27907. });
  27908. return this._effect.isReady();
  27909. };
  27910. ProceduralTexture.prototype.resetRefreshCounter = function () {
  27911. this._currentRefreshId = -1;
  27912. };
  27913. ProceduralTexture.prototype.setFragment = function (fragment) {
  27914. this._fragment = fragment;
  27915. };
  27916. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  27917. get: function () {
  27918. return this._refreshRate;
  27919. },
  27920. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  27921. set: function (value) {
  27922. this._refreshRate = value;
  27923. this.resetRefreshCounter();
  27924. },
  27925. enumerable: true,
  27926. configurable: true
  27927. });
  27928. ProceduralTexture.prototype._shouldRender = function () {
  27929. if (!this.isEnabled || !this.isReady() || !this._texture) {
  27930. return false;
  27931. }
  27932. if (this._fallbackTextureUsed) {
  27933. return false;
  27934. }
  27935. if (this._currentRefreshId === -1) {
  27936. this._currentRefreshId = 1;
  27937. return true;
  27938. }
  27939. if (this.refreshRate === this._currentRefreshId) {
  27940. this._currentRefreshId = 1;
  27941. return true;
  27942. }
  27943. this._currentRefreshId++;
  27944. return false;
  27945. };
  27946. ProceduralTexture.prototype.getRenderSize = function () {
  27947. return this._size;
  27948. };
  27949. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  27950. if (this._fallbackTextureUsed) {
  27951. return;
  27952. }
  27953. this.releaseInternalTexture();
  27954. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  27955. };
  27956. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  27957. if (this._uniforms.indexOf(uniformName) === -1) {
  27958. this._uniforms.push(uniformName);
  27959. }
  27960. };
  27961. ProceduralTexture.prototype.setTexture = function (name, texture) {
  27962. if (this._samplers.indexOf(name) === -1) {
  27963. this._samplers.push(name);
  27964. }
  27965. this._textures[name] = texture;
  27966. return this;
  27967. };
  27968. ProceduralTexture.prototype.setFloat = function (name, value) {
  27969. this._checkUniform(name);
  27970. this._floats[name] = value;
  27971. return this;
  27972. };
  27973. ProceduralTexture.prototype.setFloats = function (name, value) {
  27974. this._checkUniform(name);
  27975. this._floatsArrays[name] = value;
  27976. return this;
  27977. };
  27978. ProceduralTexture.prototype.setColor3 = function (name, value) {
  27979. this._checkUniform(name);
  27980. this._colors3[name] = value;
  27981. return this;
  27982. };
  27983. ProceduralTexture.prototype.setColor4 = function (name, value) {
  27984. this._checkUniform(name);
  27985. this._colors4[name] = value;
  27986. return this;
  27987. };
  27988. ProceduralTexture.prototype.setVector2 = function (name, value) {
  27989. this._checkUniform(name);
  27990. this._vectors2[name] = value;
  27991. return this;
  27992. };
  27993. ProceduralTexture.prototype.setVector3 = function (name, value) {
  27994. this._checkUniform(name);
  27995. this._vectors3[name] = value;
  27996. return this;
  27997. };
  27998. ProceduralTexture.prototype.setMatrix = function (name, value) {
  27999. this._checkUniform(name);
  28000. this._matrices[name] = value;
  28001. return this;
  28002. };
  28003. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28004. var scene = this.getScene();
  28005. var engine = scene.getEngine();
  28006. // Render
  28007. engine.enableEffect(this._effect);
  28008. engine.setState(false);
  28009. // Texture
  28010. for (var name in this._textures) {
  28011. this._effect.setTexture(name, this._textures[name]);
  28012. }
  28013. // Float
  28014. for (name in this._floats) {
  28015. this._effect.setFloat(name, this._floats[name]);
  28016. }
  28017. // Floats
  28018. for (name in this._floatsArrays) {
  28019. this._effect.setArray(name, this._floatsArrays[name]);
  28020. }
  28021. // Color3
  28022. for (name in this._colors3) {
  28023. this._effect.setColor3(name, this._colors3[name]);
  28024. }
  28025. // Color4
  28026. for (name in this._colors4) {
  28027. var color = this._colors4[name];
  28028. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28029. }
  28030. // Vector2
  28031. for (name in this._vectors2) {
  28032. this._effect.setVector2(name, this._vectors2[name]);
  28033. }
  28034. // Vector3
  28035. for (name in this._vectors3) {
  28036. this._effect.setVector3(name, this._vectors3[name]);
  28037. }
  28038. // Matrix
  28039. for (name in this._matrices) {
  28040. this._effect.setMatrix(name, this._matrices[name]);
  28041. }
  28042. if (this.isCube) {
  28043. for (var face = 0; face < 6; face++) {
  28044. engine.bindFramebuffer(this._texture, face);
  28045. // VBOs
  28046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28047. this._effect.setFloat("face", face);
  28048. // Clear
  28049. engine.clear(scene.clearColor, true, true, true);
  28050. // Draw order
  28051. engine.draw(true, 0, 6);
  28052. // Mipmaps
  28053. if (face === 5) {
  28054. engine.generateMipMapsForCubemap(this._texture);
  28055. }
  28056. }
  28057. }
  28058. else {
  28059. engine.bindFramebuffer(this._texture);
  28060. // VBOs
  28061. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  28062. // Clear
  28063. engine.clear(scene.clearColor, true, true, true);
  28064. // Draw order
  28065. engine.draw(true, 0, 6);
  28066. }
  28067. // Unbind
  28068. engine.unBindFramebuffer(this._texture, this.isCube);
  28069. if (this.onGenerated) {
  28070. this.onGenerated();
  28071. }
  28072. };
  28073. ProceduralTexture.prototype.clone = function () {
  28074. var textureSize = this.getSize();
  28075. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  28076. // Base texture
  28077. newTexture.hasAlpha = this.hasAlpha;
  28078. newTexture.level = this.level;
  28079. // RenderTarget Texture
  28080. newTexture.coordinatesMode = this.coordinatesMode;
  28081. return newTexture;
  28082. };
  28083. ProceduralTexture.prototype.dispose = function () {
  28084. var index = this.getScene()._proceduralTextures.indexOf(this);
  28085. if (index >= 0) {
  28086. this.getScene()._proceduralTextures.splice(index, 1);
  28087. }
  28088. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28089. if (vertexBuffer) {
  28090. vertexBuffer.dispose();
  28091. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28092. }
  28093. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  28094. this._indexBuffer = null;
  28095. }
  28096. _super.prototype.dispose.call(this);
  28097. };
  28098. return ProceduralTexture;
  28099. }(BABYLON.Texture));
  28100. BABYLON.ProceduralTexture = ProceduralTexture;
  28101. })(BABYLON || (BABYLON = {}));
  28102. //# sourceMappingURL=babylon.proceduralTexture.js.map
  28103. /// <reference path="babylon.renderTargetTexture.ts" />
  28104. var BABYLON;
  28105. (function (BABYLON) {
  28106. var MirrorTexture = (function (_super) {
  28107. __extends(MirrorTexture, _super);
  28108. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  28109. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  28110. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28111. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  28112. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  28113. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  28114. _this._transformMatrix = BABYLON.Matrix.Zero();
  28115. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  28116. _this.onBeforeRenderObservable.add(function () {
  28117. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  28118. _this._savedViewMatrix = scene.getViewMatrix();
  28119. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  28120. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  28121. scene.clipPlane = _this.mirrorPlane;
  28122. scene.getEngine().cullBackFaces = false;
  28123. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  28124. });
  28125. _this.onAfterRenderObservable.add(function () {
  28126. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  28127. scene.getEngine().cullBackFaces = true;
  28128. scene._mirroredCameraPosition = null;
  28129. delete scene.clipPlane;
  28130. });
  28131. return _this;
  28132. }
  28133. MirrorTexture.prototype.clone = function () {
  28134. var textureSize = this.getSize();
  28135. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  28136. // Base texture
  28137. newTexture.hasAlpha = this.hasAlpha;
  28138. newTexture.level = this.level;
  28139. // Mirror Texture
  28140. newTexture.mirrorPlane = this.mirrorPlane.clone();
  28141. newTexture.renderList = this.renderList.slice(0);
  28142. return newTexture;
  28143. };
  28144. MirrorTexture.prototype.serialize = function () {
  28145. if (!this.name) {
  28146. return null;
  28147. }
  28148. var serializationObject = _super.prototype.serialize.call(this);
  28149. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  28150. return serializationObject;
  28151. };
  28152. return MirrorTexture;
  28153. }(BABYLON.RenderTargetTexture));
  28154. BABYLON.MirrorTexture = MirrorTexture;
  28155. })(BABYLON || (BABYLON = {}));
  28156. //# sourceMappingURL=babylon.mirrorTexture.js.map
  28157. /// <reference path="babylon.renderTargetTexture.ts" />
  28158. var BABYLON;
  28159. (function (BABYLON) {
  28160. /**
  28161. * Creates a refraction texture used by refraction channel of the standard material.
  28162. * @param name the texture name
  28163. * @param size size of the underlying texture
  28164. * @param scene root scene
  28165. */
  28166. var RefractionTexture = (function (_super) {
  28167. __extends(RefractionTexture, _super);
  28168. function RefractionTexture(name, size, scene, generateMipMaps) {
  28169. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  28170. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  28171. _this.depth = 2.0;
  28172. _this.onBeforeRenderObservable.add(function () {
  28173. scene.clipPlane = _this.refractionPlane;
  28174. });
  28175. _this.onAfterRenderObservable.add(function () {
  28176. delete scene.clipPlane;
  28177. });
  28178. return _this;
  28179. }
  28180. RefractionTexture.prototype.clone = function () {
  28181. var textureSize = this.getSize();
  28182. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  28183. // Base texture
  28184. newTexture.hasAlpha = this.hasAlpha;
  28185. newTexture.level = this.level;
  28186. // Refraction Texture
  28187. newTexture.refractionPlane = this.refractionPlane.clone();
  28188. newTexture.renderList = this.renderList.slice(0);
  28189. newTexture.depth = this.depth;
  28190. return newTexture;
  28191. };
  28192. RefractionTexture.prototype.serialize = function () {
  28193. if (!this.name) {
  28194. return null;
  28195. }
  28196. var serializationObject = _super.prototype.serialize.call(this);
  28197. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  28198. serializationObject.depth = this.depth;
  28199. return serializationObject;
  28200. };
  28201. return RefractionTexture;
  28202. }(BABYLON.RenderTargetTexture));
  28203. BABYLON.RefractionTexture = RefractionTexture;
  28204. })(BABYLON || (BABYLON = {}));
  28205. //# sourceMappingURL=babylon.refractionTexture.js.map
  28206. /// <reference path="babylon.texture.ts" />
  28207. var BABYLON;
  28208. (function (BABYLON) {
  28209. var DynamicTexture = (function (_super) {
  28210. __extends(DynamicTexture, _super);
  28211. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  28212. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28213. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28214. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  28215. _this.name = name;
  28216. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28217. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28218. _this._generateMipMaps = generateMipMaps;
  28219. if (options.getContext) {
  28220. _this._canvas = options;
  28221. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28222. }
  28223. else {
  28224. _this._canvas = document.createElement("canvas");
  28225. if (options.width) {
  28226. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  28227. }
  28228. else {
  28229. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  28230. }
  28231. }
  28232. var textureSize = _this.getSize();
  28233. _this._canvas.width = textureSize.width;
  28234. _this._canvas.height = textureSize.height;
  28235. _this._context = _this._canvas.getContext("2d");
  28236. return _this;
  28237. }
  28238. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  28239. get: function () {
  28240. return true;
  28241. },
  28242. enumerable: true,
  28243. configurable: true
  28244. });
  28245. DynamicTexture.prototype.scale = function (ratio) {
  28246. var textureSize = this.getSize();
  28247. textureSize.width *= ratio;
  28248. textureSize.height *= ratio;
  28249. this._canvas.width = textureSize.width;
  28250. this._canvas.height = textureSize.height;
  28251. this.releaseInternalTexture();
  28252. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  28253. };
  28254. DynamicTexture.prototype.getContext = function () {
  28255. return this._context;
  28256. };
  28257. DynamicTexture.prototype.clear = function () {
  28258. var size = this.getSize();
  28259. this._context.fillRect(0, 0, size.width, size.height);
  28260. };
  28261. DynamicTexture.prototype.update = function (invertY) {
  28262. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  28263. };
  28264. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  28265. if (update === void 0) { update = true; }
  28266. var size = this.getSize();
  28267. if (clearColor) {
  28268. this._context.fillStyle = clearColor;
  28269. this._context.fillRect(0, 0, size.width, size.height);
  28270. }
  28271. this._context.font = font;
  28272. if (x === null || x === undefined) {
  28273. var textSize = this._context.measureText(text);
  28274. x = (size.width - textSize.width) / 2;
  28275. }
  28276. if (y === null || y === undefined) {
  28277. var fontSize = parseInt((font.replace(/\D/g, '')));
  28278. ;
  28279. y = (size.height / 2) + (fontSize / 3.65);
  28280. }
  28281. this._context.fillStyle = color;
  28282. this._context.fillText(text, x, y);
  28283. if (update) {
  28284. this.update(invertY);
  28285. }
  28286. };
  28287. DynamicTexture.prototype.clone = function () {
  28288. var textureSize = this.getSize();
  28289. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  28290. // Base texture
  28291. newTexture.hasAlpha = this.hasAlpha;
  28292. newTexture.level = this.level;
  28293. // Dynamic Texture
  28294. newTexture.wrapU = this.wrapU;
  28295. newTexture.wrapV = this.wrapV;
  28296. return newTexture;
  28297. };
  28298. return DynamicTexture;
  28299. }(BABYLON.Texture));
  28300. BABYLON.DynamicTexture = DynamicTexture;
  28301. })(BABYLON || (BABYLON = {}));
  28302. //# sourceMappingURL=babylon.dynamicTexture.js.map
  28303. var BABYLON;
  28304. (function (BABYLON) {
  28305. var VideoTexture = (function (_super) {
  28306. __extends(VideoTexture, _super);
  28307. /**
  28308. * Creates a video texture.
  28309. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  28310. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  28311. * @param {BABYLON.Scene} scene is obviously the current scene.
  28312. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  28313. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  28314. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  28315. */
  28316. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  28317. if (generateMipMaps === void 0) { generateMipMaps = false; }
  28318. if (invertY === void 0) { invertY = false; }
  28319. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28320. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  28321. _this._autoLaunch = true;
  28322. var urls;
  28323. _this.name = name;
  28324. if (urlsOrVideo instanceof HTMLVideoElement) {
  28325. _this.video = urlsOrVideo;
  28326. }
  28327. else {
  28328. urls = urlsOrVideo;
  28329. _this.video = document.createElement("video");
  28330. _this.video.autoplay = false;
  28331. _this.video.loop = true;
  28332. }
  28333. _this._generateMipMaps = generateMipMaps;
  28334. _this._samplingMode = samplingMode;
  28335. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  28336. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28337. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28338. }
  28339. else {
  28340. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28341. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28342. _this._generateMipMaps = false;
  28343. }
  28344. if (urls) {
  28345. _this.video.addEventListener("canplaythrough", function () {
  28346. _this._createTexture();
  28347. });
  28348. urls.forEach(function (url) {
  28349. var source = document.createElement("source");
  28350. source.src = url;
  28351. _this.video.appendChild(source);
  28352. });
  28353. }
  28354. else {
  28355. _this._createTexture();
  28356. }
  28357. _this._lastUpdate = BABYLON.Tools.Now;
  28358. return _this;
  28359. }
  28360. VideoTexture.prototype._createTexture = function () {
  28361. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  28362. this._texture.isReady = true;
  28363. };
  28364. VideoTexture.prototype.update = function () {
  28365. if (this._autoLaunch) {
  28366. this._autoLaunch = false;
  28367. this.video.play();
  28368. }
  28369. var now = BABYLON.Tools.Now;
  28370. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  28371. return false;
  28372. }
  28373. this._lastUpdate = now;
  28374. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  28375. return true;
  28376. };
  28377. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  28378. var video = document.createElement("video");
  28379. var constraintsDeviceId;
  28380. if (constraints && constraints.deviceId) {
  28381. constraintsDeviceId = {
  28382. exact: constraints.deviceId
  28383. };
  28384. }
  28385. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  28386. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  28387. if (navigator.getUserMedia) {
  28388. navigator.getUserMedia({
  28389. video: {
  28390. deviceId: constraintsDeviceId,
  28391. width: {
  28392. min: (constraints && constraints.minWidth) || 256,
  28393. max: (constraints && constraints.maxWidth) || 640
  28394. },
  28395. height: {
  28396. min: (constraints && constraints.minHeight) || 256,
  28397. max: (constraints && constraints.maxHeight) || 480
  28398. }
  28399. }
  28400. }, function (stream) {
  28401. if (video.mozSrcObject !== undefined) {
  28402. video.mozSrcObject = stream;
  28403. }
  28404. else {
  28405. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  28406. }
  28407. video.play();
  28408. if (onReady) {
  28409. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  28410. }
  28411. }, function (e) {
  28412. BABYLON.Tools.Error(e.name);
  28413. });
  28414. }
  28415. };
  28416. return VideoTexture;
  28417. }(BABYLON.Texture));
  28418. BABYLON.VideoTexture = VideoTexture;
  28419. })(BABYLON || (BABYLON = {}));
  28420. //# sourceMappingURL=babylon.videoTexture.js.map
  28421. /// <reference path="babylon.proceduralTexture.ts" />
  28422. var BABYLON;
  28423. (function (BABYLON) {
  28424. var CustomProceduralTexture = (function (_super) {
  28425. __extends(CustomProceduralTexture, _super);
  28426. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  28427. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  28428. _this._animate = true;
  28429. _this._time = 0;
  28430. _this._texturePath = texturePath;
  28431. //Try to load json
  28432. _this.loadJson(texturePath);
  28433. _this.refreshRate = 1;
  28434. return _this;
  28435. }
  28436. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  28437. var _this = this;
  28438. var that = this;
  28439. function noConfigFile() {
  28440. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  28441. try {
  28442. that.setFragment(that._texturePath);
  28443. }
  28444. catch (ex) {
  28445. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  28446. }
  28447. }
  28448. var configFileUrl = jsonUrl + "/config.json";
  28449. var xhr = new XMLHttpRequest();
  28450. xhr.open("GET", configFileUrl, true);
  28451. xhr.addEventListener("load", function () {
  28452. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  28453. try {
  28454. _this._config = JSON.parse(xhr.response);
  28455. _this.updateShaderUniforms();
  28456. _this.updateTextures();
  28457. _this.setFragment(_this._texturePath + "/custom");
  28458. _this._animate = _this._config.animate;
  28459. _this.refreshRate = _this._config.refreshrate;
  28460. }
  28461. catch (ex) {
  28462. noConfigFile();
  28463. }
  28464. }
  28465. else {
  28466. noConfigFile();
  28467. }
  28468. }, false);
  28469. xhr.addEventListener("error", function () {
  28470. noConfigFile();
  28471. }, false);
  28472. try {
  28473. xhr.send();
  28474. }
  28475. catch (ex) {
  28476. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  28477. }
  28478. };
  28479. CustomProceduralTexture.prototype.isReady = function () {
  28480. if (!_super.prototype.isReady.call(this)) {
  28481. return false;
  28482. }
  28483. for (var name in this._textures) {
  28484. var texture = this._textures[name];
  28485. if (!texture.isReady()) {
  28486. return false;
  28487. }
  28488. }
  28489. return true;
  28490. };
  28491. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  28492. if (this._animate) {
  28493. this._time += this.getScene().getAnimationRatio() * 0.03;
  28494. this.updateShaderUniforms();
  28495. }
  28496. _super.prototype.render.call(this, useCameraPostProcess);
  28497. };
  28498. CustomProceduralTexture.prototype.updateTextures = function () {
  28499. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  28500. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  28501. }
  28502. };
  28503. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  28504. if (this._config) {
  28505. for (var j = 0; j < this._config.uniforms.length; j++) {
  28506. var uniform = this._config.uniforms[j];
  28507. switch (uniform.type) {
  28508. case "float":
  28509. this.setFloat(uniform.name, uniform.value);
  28510. break;
  28511. case "color3":
  28512. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  28513. break;
  28514. case "color4":
  28515. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  28516. break;
  28517. case "vector2":
  28518. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  28519. break;
  28520. case "vector3":
  28521. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  28522. break;
  28523. }
  28524. }
  28525. }
  28526. this.setFloat("time", this._time);
  28527. };
  28528. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  28529. get: function () {
  28530. return this._animate;
  28531. },
  28532. set: function (value) {
  28533. this._animate = value;
  28534. },
  28535. enumerable: true,
  28536. configurable: true
  28537. });
  28538. return CustomProceduralTexture;
  28539. }(BABYLON.ProceduralTexture));
  28540. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  28541. })(BABYLON || (BABYLON = {}));
  28542. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  28543. var BABYLON;
  28544. (function (BABYLON) {
  28545. var EffectFallbacks = (function () {
  28546. function EffectFallbacks() {
  28547. this._defines = {};
  28548. this._currentRank = 32;
  28549. this._maxRank = -1;
  28550. }
  28551. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28552. if (!this._defines[rank]) {
  28553. if (rank < this._currentRank) {
  28554. this._currentRank = rank;
  28555. }
  28556. if (rank > this._maxRank) {
  28557. this._maxRank = rank;
  28558. }
  28559. this._defines[rank] = new Array();
  28560. }
  28561. this._defines[rank].push(define);
  28562. };
  28563. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  28564. this._meshRank = rank;
  28565. this._mesh = mesh;
  28566. if (rank < this._currentRank) {
  28567. this._currentRank = rank;
  28568. }
  28569. if (rank > this._maxRank) {
  28570. this._maxRank = rank;
  28571. }
  28572. };
  28573. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  28574. get: function () {
  28575. return this._currentRank <= this._maxRank;
  28576. },
  28577. enumerable: true,
  28578. configurable: true
  28579. });
  28580. EffectFallbacks.prototype.reduce = function (currentDefines) {
  28581. // First we try to switch to CPU skinning
  28582. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  28583. this._mesh.computeBonesUsingShaders = false;
  28584. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  28585. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  28586. var scene = this._mesh.getScene();
  28587. for (var index = 0; index < scene.meshes.length; index++) {
  28588. var otherMesh = scene.meshes[index];
  28589. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  28590. otherMesh.computeBonesUsingShaders = false;
  28591. }
  28592. }
  28593. }
  28594. else {
  28595. var currentFallbacks = this._defines[this._currentRank];
  28596. if (currentFallbacks) {
  28597. for (var index = 0; index < currentFallbacks.length; index++) {
  28598. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  28599. }
  28600. }
  28601. this._currentRank++;
  28602. }
  28603. return currentDefines;
  28604. };
  28605. return EffectFallbacks;
  28606. }());
  28607. BABYLON.EffectFallbacks = EffectFallbacks;
  28608. var Effect = (function () {
  28609. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  28610. var _this = this;
  28611. this.uniqueId = 0;
  28612. this._isReady = false;
  28613. this._compilationError = "";
  28614. this._valueCache = {};
  28615. this._engine = engine;
  28616. this.name = baseName;
  28617. this.defines = defines;
  28618. this._uniformsNames = uniformsNames.concat(samplers);
  28619. this._samplers = samplers;
  28620. this._attributesNames = attributesNames;
  28621. this.onError = onError;
  28622. this.onCompiled = onCompiled;
  28623. this._indexParameters = indexParameters;
  28624. this.uniqueId = Effect._uniqueIdSeed++;
  28625. var vertexSource;
  28626. var fragmentSource;
  28627. if (baseName.vertexElement) {
  28628. vertexSource = document.getElementById(baseName.vertexElement);
  28629. if (!vertexSource) {
  28630. vertexSource = baseName.vertexElement;
  28631. }
  28632. }
  28633. else {
  28634. vertexSource = baseName.vertex || baseName;
  28635. }
  28636. if (baseName.fragmentElement) {
  28637. fragmentSource = document.getElementById(baseName.fragmentElement);
  28638. if (!fragmentSource) {
  28639. fragmentSource = baseName.fragmentElement;
  28640. }
  28641. }
  28642. else {
  28643. fragmentSource = baseName.fragment || baseName;
  28644. }
  28645. this._loadVertexShader(vertexSource, function (vertexCode) {
  28646. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  28647. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  28648. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  28649. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  28650. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  28651. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  28652. });
  28653. });
  28654. });
  28655. });
  28656. });
  28657. });
  28658. }
  28659. Object.defineProperty(Effect.prototype, "key", {
  28660. get: function () {
  28661. return this._key;
  28662. },
  28663. enumerable: true,
  28664. configurable: true
  28665. });
  28666. // Properties
  28667. Effect.prototype.isReady = function () {
  28668. return this._isReady;
  28669. };
  28670. Effect.prototype.getProgram = function () {
  28671. return this._program;
  28672. };
  28673. Effect.prototype.getAttributesNames = function () {
  28674. return this._attributesNames;
  28675. };
  28676. Effect.prototype.getAttributeLocation = function (index) {
  28677. return this._attributes[index];
  28678. };
  28679. Effect.prototype.getAttributeLocationByName = function (name) {
  28680. var index = this._attributesNames.indexOf(name);
  28681. return this._attributes[index];
  28682. };
  28683. Effect.prototype.getAttributesCount = function () {
  28684. return this._attributes.length;
  28685. };
  28686. Effect.prototype.getUniformIndex = function (uniformName) {
  28687. return this._uniformsNames.indexOf(uniformName);
  28688. };
  28689. Effect.prototype.getUniform = function (uniformName) {
  28690. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  28691. };
  28692. Effect.prototype.getSamplers = function () {
  28693. return this._samplers;
  28694. };
  28695. Effect.prototype.getCompilationError = function () {
  28696. return this._compilationError;
  28697. };
  28698. Effect.prototype.getVertexShaderSource = function () {
  28699. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  28700. };
  28701. Effect.prototype.getFragmentShaderSource = function () {
  28702. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  28703. };
  28704. // Methods
  28705. Effect.prototype._loadVertexShader = function (vertex, callback) {
  28706. // DOM element ?
  28707. if (vertex instanceof HTMLElement) {
  28708. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  28709. callback(vertexCode);
  28710. return;
  28711. }
  28712. // Base64 encoded ?
  28713. if (vertex.substr(0, 7) === "base64:") {
  28714. var vertexBinary = window.atob(vertex.substr(7));
  28715. callback(vertexBinary);
  28716. return;
  28717. }
  28718. // Is in local store ?
  28719. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  28720. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  28721. return;
  28722. }
  28723. var vertexShaderUrl;
  28724. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  28725. vertexShaderUrl = vertex;
  28726. }
  28727. else {
  28728. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  28729. }
  28730. // Vertex shader
  28731. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  28732. };
  28733. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  28734. // DOM element ?
  28735. if (fragment instanceof HTMLElement) {
  28736. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  28737. callback(fragmentCode);
  28738. return;
  28739. }
  28740. // Base64 encoded ?
  28741. if (fragment.substr(0, 7) === "base64:") {
  28742. var fragmentBinary = window.atob(fragment.substr(7));
  28743. callback(fragmentBinary);
  28744. return;
  28745. }
  28746. // Is in local store ?
  28747. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  28748. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  28749. return;
  28750. }
  28751. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  28752. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  28753. return;
  28754. }
  28755. var fragmentShaderUrl;
  28756. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  28757. fragmentShaderUrl = fragment;
  28758. }
  28759. else {
  28760. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  28761. }
  28762. // Fragment shader
  28763. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  28764. };
  28765. Effect.prototype._dumpShadersName = function () {
  28766. if (this.name.vertexElement) {
  28767. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  28768. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  28769. }
  28770. else if (this.name.vertex) {
  28771. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  28772. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  28773. }
  28774. else {
  28775. BABYLON.Tools.Error("Vertex shader:" + this.name);
  28776. BABYLON.Tools.Error("Fragment shader:" + this.name);
  28777. }
  28778. };
  28779. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  28780. var preparedSourceCode = this._processPrecision(sourceCode);
  28781. if (this._engine.webGLVersion == 1) {
  28782. callback(preparedSourceCode);
  28783. return;
  28784. }
  28785. // Already converted
  28786. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  28787. callback(preparedSourceCode);
  28788. return;
  28789. }
  28790. // Remove extensions
  28791. // #extension GL_OES_standard_derivatives : enable
  28792. // #extension GL_EXT_shader_texture_lod : enable
  28793. // #extension GL_EXT_frag_depth : enable
  28794. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  28795. var result = preparedSourceCode.replace(regex, "");
  28796. // Migrate to GLSL v300
  28797. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  28798. result = result.replace(/attribute[ \t]/g, "in ");
  28799. result = result.replace(/[ \t]attribute/g, " in");
  28800. if (isFragment) {
  28801. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  28802. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  28803. result = result.replace(/texture2D\(/g, "texture(");
  28804. result = result.replace(/textureCube\(/g, "texture(");
  28805. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  28806. result = result.replace(/gl_FragColor/g, "glFragColor");
  28807. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  28808. }
  28809. callback(result);
  28810. };
  28811. Effect.prototype._processIncludes = function (sourceCode, callback) {
  28812. var _this = this;
  28813. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  28814. var match = regex.exec(sourceCode);
  28815. var returnValue = new String(sourceCode);
  28816. while (match != null) {
  28817. var includeFile = match[1];
  28818. if (Effect.IncludesShadersStore[includeFile]) {
  28819. // Substitution
  28820. var includeContent = Effect.IncludesShadersStore[includeFile];
  28821. if (match[2]) {
  28822. var splits = match[3].split(",");
  28823. for (var index = 0; index < splits.length; index += 2) {
  28824. var source = new RegExp(splits[index], "g");
  28825. var dest = splits[index + 1];
  28826. includeContent = includeContent.replace(source, dest);
  28827. }
  28828. }
  28829. if (match[4]) {
  28830. var indexString = match[5];
  28831. if (indexString.indexOf("..") !== -1) {
  28832. var indexSplits = indexString.split("..");
  28833. var minIndex = parseInt(indexSplits[0]);
  28834. var maxIndex = parseInt(indexSplits[1]);
  28835. var sourceIncludeContent = includeContent.slice(0);
  28836. includeContent = "";
  28837. if (isNaN(maxIndex)) {
  28838. maxIndex = this._indexParameters[indexSplits[1]];
  28839. }
  28840. for (var i = minIndex; i <= maxIndex; i++) {
  28841. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  28842. }
  28843. }
  28844. else {
  28845. includeContent = includeContent.replace(/\{X\}/g, indexString);
  28846. }
  28847. }
  28848. // Replace
  28849. returnValue = returnValue.replace(match[0], includeContent);
  28850. }
  28851. else {
  28852. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  28853. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  28854. Effect.IncludesShadersStore[includeFile] = fileContent;
  28855. _this._processIncludes(returnValue, callback);
  28856. });
  28857. return;
  28858. }
  28859. match = regex.exec(sourceCode);
  28860. }
  28861. callback(returnValue);
  28862. };
  28863. Effect.prototype._processPrecision = function (source) {
  28864. if (source.indexOf("precision highp float") === -1) {
  28865. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28866. source = "precision mediump float;\n" + source;
  28867. }
  28868. else {
  28869. source = "precision highp float;\n" + source;
  28870. }
  28871. }
  28872. else {
  28873. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  28874. source = source.replace("precision highp float", "precision mediump float");
  28875. }
  28876. }
  28877. return source;
  28878. };
  28879. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  28880. try {
  28881. var engine = this._engine;
  28882. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  28883. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  28884. this._attributes = engine.getAttributes(this._program, attributesNames);
  28885. var index;
  28886. for (index = 0; index < this._samplers.length; index++) {
  28887. var sampler = this.getUniform(this._samplers[index]);
  28888. if (sampler == null) {
  28889. this._samplers.splice(index, 1);
  28890. index--;
  28891. }
  28892. }
  28893. engine.bindSamplers(this);
  28894. this._compilationError = "";
  28895. this._isReady = true;
  28896. if (this.onCompiled) {
  28897. this.onCompiled(this);
  28898. }
  28899. }
  28900. catch (e) {
  28901. this._compilationError = e.message;
  28902. // Let's go through fallbacks then
  28903. BABYLON.Tools.Error("Unable to compile effect: ");
  28904. BABYLON.Tools.Error("Defines: " + defines);
  28905. BABYLON.Tools.Error("Error: " + this._compilationError);
  28906. this._dumpShadersName();
  28907. if (fallbacks && fallbacks.isMoreFallbacks) {
  28908. BABYLON.Tools.Error("Trying next fallback.");
  28909. defines = fallbacks.reduce(defines);
  28910. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  28911. }
  28912. else {
  28913. if (this.onError) {
  28914. this.onError(this, this._compilationError);
  28915. }
  28916. }
  28917. }
  28918. };
  28919. Object.defineProperty(Effect.prototype, "isSupported", {
  28920. get: function () {
  28921. return this._compilationError === "";
  28922. },
  28923. enumerable: true,
  28924. configurable: true
  28925. });
  28926. Effect.prototype._bindTexture = function (channel, texture) {
  28927. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  28928. };
  28929. Effect.prototype.setTexture = function (channel, texture) {
  28930. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  28931. };
  28932. Effect.prototype.setTextureArray = function (channel, textures) {
  28933. if (this._samplers.indexOf(channel + "Ex") === -1) {
  28934. var initialPos = this._samplers.indexOf(channel);
  28935. for (var index = 1; index < textures.length; index++) {
  28936. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  28937. }
  28938. }
  28939. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  28940. };
  28941. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  28942. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  28943. };
  28944. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  28945. var changed = false;
  28946. var cache = this._valueCache[uniformName];
  28947. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  28948. changed = true;
  28949. cache = new BABYLON.Matrix();
  28950. }
  28951. var tm = cache.m;
  28952. var om = matrix.m;
  28953. for (var index = 0; index < 16; index++) {
  28954. if (tm[index] !== om[index]) {
  28955. tm[index] = om[index];
  28956. changed = true;
  28957. }
  28958. }
  28959. this._valueCache[uniformName] = cache;
  28960. return changed;
  28961. };
  28962. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  28963. var cache = this._valueCache[uniformName];
  28964. if (!cache) {
  28965. cache = [x, y];
  28966. this._valueCache[uniformName] = cache;
  28967. return true;
  28968. }
  28969. var changed = false;
  28970. if (cache[0] !== x) {
  28971. cache[0] = x;
  28972. changed = true;
  28973. }
  28974. if (cache[1] !== y) {
  28975. cache[1] = y;
  28976. changed = true;
  28977. }
  28978. return changed;
  28979. };
  28980. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  28981. var cache = this._valueCache[uniformName];
  28982. if (!cache) {
  28983. cache = [x, y, z];
  28984. this._valueCache[uniformName] = cache;
  28985. return true;
  28986. }
  28987. var changed = false;
  28988. if (cache[0] !== x) {
  28989. cache[0] = x;
  28990. changed = true;
  28991. }
  28992. if (cache[1] !== y) {
  28993. cache[1] = y;
  28994. changed = true;
  28995. }
  28996. if (cache[2] !== z) {
  28997. cache[2] = z;
  28998. changed = true;
  28999. }
  29000. return changed;
  29001. };
  29002. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  29003. var cache = this._valueCache[uniformName];
  29004. if (!cache) {
  29005. cache = [x, y, z, w];
  29006. this._valueCache[uniformName] = cache;
  29007. return true;
  29008. }
  29009. var changed = false;
  29010. if (cache[0] !== x) {
  29011. cache[0] = x;
  29012. changed = true;
  29013. }
  29014. if (cache[1] !== y) {
  29015. cache[1] = y;
  29016. changed = true;
  29017. }
  29018. if (cache[2] !== z) {
  29019. cache[2] = z;
  29020. changed = true;
  29021. }
  29022. if (cache[3] !== w) {
  29023. cache[3] = w;
  29024. changed = true;
  29025. }
  29026. return changed;
  29027. };
  29028. Effect.prototype.setIntArray = function (uniformName, array) {
  29029. this._valueCache[uniformName] = null;
  29030. this._engine.setIntArray(this.getUniform(uniformName), array);
  29031. return this;
  29032. };
  29033. Effect.prototype.setIntArray2 = function (uniformName, array) {
  29034. this._valueCache[uniformName] = null;
  29035. this._engine.setIntArray2(this.getUniform(uniformName), array);
  29036. return this;
  29037. };
  29038. Effect.prototype.setIntArray3 = function (uniformName, array) {
  29039. this._valueCache[uniformName] = null;
  29040. this._engine.setIntArray3(this.getUniform(uniformName), array);
  29041. return this;
  29042. };
  29043. Effect.prototype.setIntArray4 = function (uniformName, array) {
  29044. this._valueCache[uniformName] = null;
  29045. this._engine.setIntArray4(this.getUniform(uniformName), array);
  29046. return this;
  29047. };
  29048. Effect.prototype.setFloatArray = function (uniformName, array) {
  29049. this._valueCache[uniformName] = null;
  29050. this._engine.setFloatArray(this.getUniform(uniformName), array);
  29051. return this;
  29052. };
  29053. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  29054. this._valueCache[uniformName] = null;
  29055. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  29056. return this;
  29057. };
  29058. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  29059. this._valueCache[uniformName] = null;
  29060. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  29061. return this;
  29062. };
  29063. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  29064. this._valueCache[uniformName] = null;
  29065. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  29066. return this;
  29067. };
  29068. Effect.prototype.setArray = function (uniformName, array) {
  29069. this._valueCache[uniformName] = null;
  29070. this._engine.setArray(this.getUniform(uniformName), array);
  29071. return this;
  29072. };
  29073. Effect.prototype.setArray2 = function (uniformName, array) {
  29074. this._valueCache[uniformName] = null;
  29075. this._engine.setArray2(this.getUniform(uniformName), array);
  29076. return this;
  29077. };
  29078. Effect.prototype.setArray3 = function (uniformName, array) {
  29079. this._valueCache[uniformName] = null;
  29080. this._engine.setArray3(this.getUniform(uniformName), array);
  29081. return this;
  29082. };
  29083. Effect.prototype.setArray4 = function (uniformName, array) {
  29084. this._valueCache[uniformName] = null;
  29085. this._engine.setArray4(this.getUniform(uniformName), array);
  29086. return this;
  29087. };
  29088. Effect.prototype.setMatrices = function (uniformName, matrices) {
  29089. this._valueCache[uniformName] = null;
  29090. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  29091. return this;
  29092. };
  29093. Effect.prototype.setMatrix = function (uniformName, matrix) {
  29094. if (this._cacheMatrix(uniformName, matrix)) {
  29095. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  29096. }
  29097. return this;
  29098. };
  29099. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  29100. this._valueCache[uniformName] = null;
  29101. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  29102. return this;
  29103. };
  29104. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  29105. this._valueCache[uniformName] = null;
  29106. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  29107. return this;
  29108. };
  29109. Effect.prototype.setFloat = function (uniformName, value) {
  29110. var cache = this._valueCache[uniformName];
  29111. if (cache !== undefined && cache === value)
  29112. return this;
  29113. this._valueCache[uniformName] = value;
  29114. this._engine.setFloat(this.getUniform(uniformName), value);
  29115. return this;
  29116. };
  29117. Effect.prototype.setBool = function (uniformName, bool) {
  29118. var cache = this._valueCache[uniformName];
  29119. if (cache !== undefined && cache === bool)
  29120. return this;
  29121. this._valueCache[uniformName] = bool;
  29122. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  29123. return this;
  29124. };
  29125. Effect.prototype.setVector2 = function (uniformName, vector2) {
  29126. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  29127. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  29128. }
  29129. return this;
  29130. };
  29131. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  29132. if (this._cacheFloat2(uniformName, x, y)) {
  29133. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  29134. }
  29135. return this;
  29136. };
  29137. Effect.prototype.setVector3 = function (uniformName, vector3) {
  29138. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  29139. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  29140. }
  29141. return this;
  29142. };
  29143. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  29144. if (this._cacheFloat3(uniformName, x, y, z)) {
  29145. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  29146. }
  29147. return this;
  29148. };
  29149. Effect.prototype.setVector4 = function (uniformName, vector4) {
  29150. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  29151. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  29152. }
  29153. return this;
  29154. };
  29155. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  29156. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  29157. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  29158. }
  29159. return this;
  29160. };
  29161. Effect.prototype.setColor3 = function (uniformName, color3) {
  29162. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  29163. this._engine.setColor3(this.getUniform(uniformName), color3);
  29164. }
  29165. return this;
  29166. };
  29167. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  29168. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  29169. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  29170. }
  29171. return this;
  29172. };
  29173. Effect.prototype._recombineShader = function (node) {
  29174. if (node.define) {
  29175. if (node.condition) {
  29176. var defineIndex = this.defines.indexOf("#define " + node.define);
  29177. if (defineIndex === -1) {
  29178. return null;
  29179. }
  29180. var nextComma = this.defines.indexOf("\n", defineIndex);
  29181. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  29182. var condition = defineValue + node.condition;
  29183. if (!eval(condition)) {
  29184. return null;
  29185. }
  29186. }
  29187. else if (node.ndef) {
  29188. if (this.defines.indexOf("#define " + node.define) !== -1) {
  29189. return null;
  29190. }
  29191. }
  29192. else if (this.defines.indexOf("#define " + node.define) === -1) {
  29193. return null;
  29194. }
  29195. }
  29196. var result = "";
  29197. for (var index = 0; index < node.children.length; index++) {
  29198. var line = node.children[index];
  29199. if (line.children) {
  29200. var combined = this._recombineShader(line);
  29201. if (combined !== null) {
  29202. result += combined + "\r\n";
  29203. }
  29204. continue;
  29205. }
  29206. if (line.length > 0) {
  29207. result += line + "\r\n";
  29208. }
  29209. }
  29210. return result;
  29211. };
  29212. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  29213. var root = {
  29214. children: []
  29215. };
  29216. var currentNode = root;
  29217. var lines = shaderString.split("\n");
  29218. for (var index = 0; index < lines.length; index++) {
  29219. var line = lines[index].trim();
  29220. // #ifdef
  29221. var pos = line.indexOf("#ifdef ");
  29222. if (pos !== -1) {
  29223. var define = line.substr(pos + 7);
  29224. var newNode = {
  29225. condition: null,
  29226. ndef: false,
  29227. define: define,
  29228. children: [],
  29229. parent: currentNode
  29230. };
  29231. currentNode.children.push(newNode);
  29232. currentNode = newNode;
  29233. continue;
  29234. }
  29235. // #ifndef
  29236. var pos = line.indexOf("#ifndef ");
  29237. if (pos !== -1) {
  29238. var define = line.substr(pos + 8);
  29239. newNode = {
  29240. condition: null,
  29241. define: define,
  29242. ndef: true,
  29243. children: [],
  29244. parent: currentNode
  29245. };
  29246. currentNode.children.push(newNode);
  29247. currentNode = newNode;
  29248. continue;
  29249. }
  29250. // #if
  29251. var pos = line.indexOf("#if ");
  29252. if (pos !== -1) {
  29253. var define = line.substr(pos + 4).trim();
  29254. var conditionPos = define.indexOf(" ");
  29255. newNode = {
  29256. condition: define.substr(conditionPos + 1),
  29257. define: define.substr(0, conditionPos),
  29258. ndef: false,
  29259. children: [],
  29260. parent: currentNode
  29261. };
  29262. currentNode.children.push(newNode);
  29263. currentNode = newNode;
  29264. continue;
  29265. }
  29266. // #endif
  29267. pos = line.indexOf("#endif");
  29268. if (pos !== -1) {
  29269. currentNode = currentNode.parent;
  29270. continue;
  29271. }
  29272. currentNode.children.push(line);
  29273. }
  29274. // Recombine
  29275. return this._recombineShader(root);
  29276. };
  29277. return Effect;
  29278. }());
  29279. Effect._uniqueIdSeed = 0;
  29280. // Statics
  29281. Effect.ShadersStore = {};
  29282. Effect.IncludesShadersStore = {};
  29283. BABYLON.Effect = Effect;
  29284. })(BABYLON || (BABYLON = {}));
  29285. //# sourceMappingURL=babylon.effect.js.map
  29286. var BABYLON;
  29287. (function (BABYLON) {
  29288. var MaterialHelper = (function () {
  29289. function MaterialHelper() {
  29290. }
  29291. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  29292. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29293. var lightIndex = 0;
  29294. var needNormals = false;
  29295. var needRebuild = false;
  29296. var needShadows = false;
  29297. var lightmapMode = false;
  29298. for (var index = 0; index < scene.lights.length; index++) {
  29299. var light = scene.lights[index];
  29300. if (!light.isEnabled()) {
  29301. continue;
  29302. }
  29303. // Excluded check
  29304. if (light._excludedMeshesIds.length > 0) {
  29305. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  29306. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  29307. if (excludedMesh) {
  29308. light.excludedMeshes.push(excludedMesh);
  29309. }
  29310. }
  29311. light._excludedMeshesIds = [];
  29312. }
  29313. // Included check
  29314. if (light._includedOnlyMeshesIds.length > 0) {
  29315. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  29316. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  29317. if (includedOnlyMesh) {
  29318. light.includedOnlyMeshes.push(includedOnlyMesh);
  29319. }
  29320. }
  29321. light._includedOnlyMeshesIds = [];
  29322. }
  29323. if (!light.canAffectMesh(mesh)) {
  29324. continue;
  29325. }
  29326. needNormals = true;
  29327. if (defines["LIGHT" + lightIndex] === undefined) {
  29328. needRebuild = true;
  29329. }
  29330. defines["LIGHT" + lightIndex] = true;
  29331. var type;
  29332. if (light instanceof BABYLON.SpotLight) {
  29333. type = "SPOTLIGHT" + lightIndex;
  29334. }
  29335. else if (light instanceof BABYLON.HemisphericLight) {
  29336. type = "HEMILIGHT" + lightIndex;
  29337. }
  29338. else if (light instanceof BABYLON.PointLight) {
  29339. type = "POINTLIGHT" + lightIndex;
  29340. }
  29341. else {
  29342. type = "DIRLIGHT" + lightIndex;
  29343. }
  29344. if (defines[type] === undefined) {
  29345. needRebuild = true;
  29346. }
  29347. defines[type] = true;
  29348. // Specular
  29349. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  29350. defines["SPECULARTERM"] = true;
  29351. }
  29352. // Shadows
  29353. if (scene.shadowsEnabled) {
  29354. var shadowGenerator = light.getShadowGenerator();
  29355. if (mesh && mesh.receiveShadows && shadowGenerator) {
  29356. if (defines["SHADOW" + lightIndex] === undefined) {
  29357. needRebuild = true;
  29358. }
  29359. defines["SHADOW" + lightIndex] = true;
  29360. defines["SHADOWS"] = true;
  29361. if (shadowGenerator.usePoissonSampling) {
  29362. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  29363. needRebuild = true;
  29364. }
  29365. defines["SHADOWPCF" + lightIndex] = true;
  29366. }
  29367. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  29368. if (defines["SHADOWESM" + lightIndex] === undefined) {
  29369. needRebuild = true;
  29370. }
  29371. defines["SHADOWESM" + lightIndex] = true;
  29372. }
  29373. needShadows = true;
  29374. }
  29375. }
  29376. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  29377. lightmapMode = true;
  29378. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  29379. needRebuild = true;
  29380. }
  29381. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  29382. needRebuild = true;
  29383. }
  29384. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  29385. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  29386. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  29387. }
  29388. }
  29389. lightIndex++;
  29390. if (lightIndex === maxSimultaneousLights)
  29391. break;
  29392. }
  29393. var caps = scene.getEngine().getCaps();
  29394. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  29395. if (defines["SHADOWFULLFLOAT"] === undefined) {
  29396. needRebuild = true;
  29397. }
  29398. defines["SHADOWFULLFLOAT"] = true;
  29399. }
  29400. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  29401. needRebuild = true;
  29402. }
  29403. if (lightmapMode) {
  29404. defines["LIGHTMAPEXCLUDED"] = true;
  29405. }
  29406. if (needRebuild) {
  29407. defines.rebuild();
  29408. }
  29409. return needNormals;
  29410. };
  29411. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  29412. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29413. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29414. if (!defines["LIGHT" + lightIndex]) {
  29415. break;
  29416. }
  29417. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  29418. samplersList.push("shadowSampler" + lightIndex);
  29419. }
  29420. };
  29421. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  29422. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29423. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  29424. if (!defines["LIGHT" + lightIndex]) {
  29425. break;
  29426. }
  29427. if (lightIndex > 0) {
  29428. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  29429. }
  29430. if (defines["SHADOW" + lightIndex]) {
  29431. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  29432. }
  29433. if (defines["SHADOWPCF" + lightIndex]) {
  29434. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  29435. }
  29436. if (defines["SHADOWESM" + lightIndex]) {
  29437. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  29438. }
  29439. }
  29440. };
  29441. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  29442. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  29443. fallbacks.addCPUSkinningFallback(0, mesh);
  29444. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29445. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29446. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  29447. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  29448. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  29449. }
  29450. }
  29451. };
  29452. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  29453. if (defines["INSTANCES"]) {
  29454. attribs.push("world0");
  29455. attribs.push("world1");
  29456. attribs.push("world2");
  29457. attribs.push("world3");
  29458. }
  29459. };
  29460. // Bindings
  29461. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  29462. var shadowGenerator = light.getShadowGenerator();
  29463. if (mesh.receiveShadows && shadowGenerator) {
  29464. if (!light.needCube()) {
  29465. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  29466. }
  29467. else {
  29468. if (!depthValuesAlreadySet) {
  29469. depthValuesAlreadySet = true;
  29470. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  29471. }
  29472. }
  29473. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  29474. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale);
  29475. }
  29476. return depthValuesAlreadySet;
  29477. };
  29478. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  29479. if (light instanceof BABYLON.PointLight) {
  29480. // Point Light
  29481. light.transferToEffect(effect, "vLightData" + lightIndex);
  29482. }
  29483. else if (light instanceof BABYLON.DirectionalLight) {
  29484. // Directional Light
  29485. light.transferToEffect(effect, "vLightData" + lightIndex);
  29486. }
  29487. else if (light instanceof BABYLON.SpotLight) {
  29488. // Spot Light
  29489. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  29490. }
  29491. else if (light instanceof BABYLON.HemisphericLight) {
  29492. // Hemispheric Light
  29493. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  29494. }
  29495. };
  29496. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  29497. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  29498. var lightIndex = 0;
  29499. var depthValuesAlreadySet = false;
  29500. for (var index = 0; index < scene.lights.length; index++) {
  29501. var light = scene.lights[index];
  29502. if (!light.isEnabled()) {
  29503. continue;
  29504. }
  29505. if (!light.canAffectMesh(mesh)) {
  29506. continue;
  29507. }
  29508. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  29509. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  29510. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  29511. if (defines["SPECULARTERM"]) {
  29512. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  29513. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  29514. }
  29515. // Shadows
  29516. if (scene.shadowsEnabled) {
  29517. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  29518. }
  29519. lightIndex++;
  29520. if (lightIndex === maxSimultaneousLights)
  29521. break;
  29522. }
  29523. };
  29524. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  29525. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  29526. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  29527. effect.setColor3("vFogColor", scene.fogColor);
  29528. }
  29529. };
  29530. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  29531. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  29532. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  29533. if (matrices) {
  29534. effect.setMatrices("mBones", matrices);
  29535. }
  29536. }
  29537. };
  29538. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  29539. if (defines["LOGARITHMICDEPTH"]) {
  29540. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  29541. }
  29542. };
  29543. MaterialHelper.BindClipPlane = function (effect, scene) {
  29544. if (scene.clipPlane) {
  29545. var clipPlane = scene.clipPlane;
  29546. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29547. }
  29548. };
  29549. return MaterialHelper;
  29550. }());
  29551. BABYLON.MaterialHelper = MaterialHelper;
  29552. })(BABYLON || (BABYLON = {}));
  29553. //# sourceMappingURL=babylon.materialHelper.js.map
  29554. var BABYLON;
  29555. (function (BABYLON) {
  29556. var FresnelParameters = (function () {
  29557. function FresnelParameters() {
  29558. this.isEnabled = true;
  29559. this.leftColor = BABYLON.Color3.White();
  29560. this.rightColor = BABYLON.Color3.Black();
  29561. this.bias = 0;
  29562. this.power = 1;
  29563. }
  29564. FresnelParameters.prototype.clone = function () {
  29565. var newFresnelParameters = new FresnelParameters();
  29566. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  29567. return newFresnelParameters;
  29568. };
  29569. FresnelParameters.prototype.serialize = function () {
  29570. var serializationObject = {};
  29571. serializationObject.isEnabled = this.isEnabled;
  29572. serializationObject.leftColor = this.leftColor;
  29573. serializationObject.rightColor = this.rightColor;
  29574. serializationObject.bias = this.bias;
  29575. serializationObject.power = this.power;
  29576. return serializationObject;
  29577. };
  29578. FresnelParameters.Parse = function (parsedFresnelParameters) {
  29579. var fresnelParameters = new FresnelParameters();
  29580. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  29581. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  29582. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  29583. fresnelParameters.bias = parsedFresnelParameters.bias;
  29584. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  29585. return fresnelParameters;
  29586. };
  29587. return FresnelParameters;
  29588. }());
  29589. BABYLON.FresnelParameters = FresnelParameters;
  29590. })(BABYLON || (BABYLON = {}));
  29591. //# sourceMappingURL=babylon.fresnelParameters.js.map
  29592. var BABYLON;
  29593. (function (BABYLON) {
  29594. var MaterialDefines = (function () {
  29595. function MaterialDefines() {
  29596. }
  29597. MaterialDefines.prototype.rebuild = function () {
  29598. if (this._keys) {
  29599. delete this._keys;
  29600. }
  29601. this._keys = Object.keys(this);
  29602. };
  29603. MaterialDefines.prototype.isEqual = function (other) {
  29604. if (this._keys.length !== other._keys.length) {
  29605. return false;
  29606. }
  29607. for (var index = 0; index < this._keys.length; index++) {
  29608. var prop = this._keys[index];
  29609. if (this[prop] !== other[prop]) {
  29610. return false;
  29611. }
  29612. }
  29613. return true;
  29614. };
  29615. MaterialDefines.prototype.cloneTo = function (other) {
  29616. if (this._keys.length !== other._keys.length) {
  29617. other._keys = this._keys.slice(0);
  29618. }
  29619. for (var index = 0; index < this._keys.length; index++) {
  29620. var prop = this._keys[index];
  29621. other[prop] = this[prop];
  29622. }
  29623. };
  29624. MaterialDefines.prototype.reset = function () {
  29625. for (var index = 0; index < this._keys.length; index++) {
  29626. var prop = this._keys[index];
  29627. if (typeof (this[prop]) === "number") {
  29628. this[prop] = 0;
  29629. }
  29630. else {
  29631. this[prop] = false;
  29632. }
  29633. }
  29634. };
  29635. MaterialDefines.prototype.toString = function () {
  29636. var result = "";
  29637. for (var index = 0; index < this._keys.length; index++) {
  29638. var prop = this._keys[index];
  29639. if (typeof (this[prop]) === "number") {
  29640. result += "#define " + prop + " " + this[prop] + "\n";
  29641. }
  29642. else if (this[prop]) {
  29643. result += "#define " + prop + "\n";
  29644. }
  29645. }
  29646. return result;
  29647. };
  29648. return MaterialDefines;
  29649. }());
  29650. BABYLON.MaterialDefines = MaterialDefines;
  29651. var Material = (function () {
  29652. function Material(name, scene, doNotAdd) {
  29653. this.checkReadyOnEveryCall = false;
  29654. this.checkReadyOnlyOnce = false;
  29655. this.state = "";
  29656. this.alpha = 1.0;
  29657. this.backFaceCulling = true;
  29658. this.doNotSerialize = false;
  29659. /**
  29660. * An event triggered when the material is disposed.
  29661. * @type {BABYLON.Observable}
  29662. */
  29663. this.onDisposeObservable = new BABYLON.Observable();
  29664. /**
  29665. * An event triggered when the material is bound.
  29666. * @type {BABYLON.Observable}
  29667. */
  29668. this.onBindObservable = new BABYLON.Observable();
  29669. /**
  29670. * An event triggered when the material is unbound.
  29671. * @type {BABYLON.Observable}
  29672. */
  29673. this.onUnBindObservable = new BABYLON.Observable();
  29674. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  29675. this.disableDepthWrite = false;
  29676. this.fogEnabled = true;
  29677. this.pointSize = 1.0;
  29678. this.zOffset = 0;
  29679. this._wasPreviouslyReady = false;
  29680. this._fillMode = Material.TriangleFillMode;
  29681. this.name = name;
  29682. this.id = name;
  29683. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29684. if (this._scene.useRightHandedSystem) {
  29685. this.sideOrientation = Material.ClockWiseSideOrientation;
  29686. }
  29687. else {
  29688. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  29689. }
  29690. if (!doNotAdd) {
  29691. this._scene.materials.push(this);
  29692. }
  29693. }
  29694. Object.defineProperty(Material, "TriangleFillMode", {
  29695. get: function () {
  29696. return Material._TriangleFillMode;
  29697. },
  29698. enumerable: true,
  29699. configurable: true
  29700. });
  29701. Object.defineProperty(Material, "WireFrameFillMode", {
  29702. get: function () {
  29703. return Material._WireFrameFillMode;
  29704. },
  29705. enumerable: true,
  29706. configurable: true
  29707. });
  29708. Object.defineProperty(Material, "PointFillMode", {
  29709. get: function () {
  29710. return Material._PointFillMode;
  29711. },
  29712. enumerable: true,
  29713. configurable: true
  29714. });
  29715. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  29716. get: function () {
  29717. return Material._ClockWiseSideOrientation;
  29718. },
  29719. enumerable: true,
  29720. configurable: true
  29721. });
  29722. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  29723. get: function () {
  29724. return Material._CounterClockWiseSideOrientation;
  29725. },
  29726. enumerable: true,
  29727. configurable: true
  29728. });
  29729. Object.defineProperty(Material.prototype, "onDispose", {
  29730. set: function (callback) {
  29731. if (this._onDisposeObserver) {
  29732. this.onDisposeObservable.remove(this._onDisposeObserver);
  29733. }
  29734. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29735. },
  29736. enumerable: true,
  29737. configurable: true
  29738. });
  29739. Object.defineProperty(Material.prototype, "onBind", {
  29740. set: function (callback) {
  29741. if (this._onBindObserver) {
  29742. this.onBindObservable.remove(this._onBindObserver);
  29743. }
  29744. this._onBindObserver = this.onBindObservable.add(callback);
  29745. },
  29746. enumerable: true,
  29747. configurable: true
  29748. });
  29749. Object.defineProperty(Material.prototype, "wireframe", {
  29750. get: function () {
  29751. return this._fillMode === Material.WireFrameFillMode;
  29752. },
  29753. set: function (value) {
  29754. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29755. },
  29756. enumerable: true,
  29757. configurable: true
  29758. });
  29759. Object.defineProperty(Material.prototype, "pointsCloud", {
  29760. get: function () {
  29761. return this._fillMode === Material.PointFillMode;
  29762. },
  29763. set: function (value) {
  29764. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29765. },
  29766. enumerable: true,
  29767. configurable: true
  29768. });
  29769. Object.defineProperty(Material.prototype, "fillMode", {
  29770. get: function () {
  29771. return this._fillMode;
  29772. },
  29773. set: function (value) {
  29774. this._fillMode = value;
  29775. },
  29776. enumerable: true,
  29777. configurable: true
  29778. });
  29779. /**
  29780. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29781. * subclasses should override adding information pertainent to themselves
  29782. */
  29783. Material.prototype.toString = function (fullDetails) {
  29784. var ret = "Name: " + this.name;
  29785. if (fullDetails) {
  29786. }
  29787. return ret;
  29788. };
  29789. Material.prototype.getClassName = function () {
  29790. return "Material";
  29791. };
  29792. Object.defineProperty(Material.prototype, "isFrozen", {
  29793. get: function () {
  29794. return this.checkReadyOnlyOnce;
  29795. },
  29796. enumerable: true,
  29797. configurable: true
  29798. });
  29799. Material.prototype.freeze = function () {
  29800. this.checkReadyOnlyOnce = true;
  29801. };
  29802. Material.prototype.unfreeze = function () {
  29803. this.checkReadyOnlyOnce = false;
  29804. };
  29805. Material.prototype.isReady = function (mesh, useInstances) {
  29806. return true;
  29807. };
  29808. Material.prototype.getEffect = function () {
  29809. return this._effect;
  29810. };
  29811. Material.prototype.getScene = function () {
  29812. return this._scene;
  29813. };
  29814. Material.prototype.needAlphaBlending = function () {
  29815. return (this.alpha < 1.0);
  29816. };
  29817. Material.prototype.needAlphaTesting = function () {
  29818. return false;
  29819. };
  29820. Material.prototype.getAlphaTestTexture = function () {
  29821. return null;
  29822. };
  29823. Material.prototype.markDirty = function () {
  29824. this._wasPreviouslyReady = false;
  29825. };
  29826. Material.prototype._preBind = function () {
  29827. var engine = this._scene.getEngine();
  29828. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  29829. engine.enableEffect(this._effect);
  29830. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29831. };
  29832. Material.prototype.bind = function (world, mesh) {
  29833. this._scene._cachedMaterial = this;
  29834. this.onBindObservable.notifyObservers(mesh);
  29835. if (this.disableDepthWrite) {
  29836. var engine = this._scene.getEngine();
  29837. this._cachedDepthWriteState = engine.getDepthWrite();
  29838. engine.setDepthWrite(false);
  29839. }
  29840. };
  29841. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29842. };
  29843. Material.prototype.unbind = function () {
  29844. this.onUnBindObservable.notifyObservers(this);
  29845. if (this.disableDepthWrite) {
  29846. var engine = this._scene.getEngine();
  29847. engine.setDepthWrite(this._cachedDepthWriteState);
  29848. }
  29849. };
  29850. Material.prototype.clone = function (name) {
  29851. return null;
  29852. };
  29853. Material.prototype.getBindedMeshes = function () {
  29854. var result = new Array();
  29855. for (var index = 0; index < this._scene.meshes.length; index++) {
  29856. var mesh = this._scene.meshes[index];
  29857. if (mesh.material === this) {
  29858. result.push(mesh);
  29859. }
  29860. }
  29861. return result;
  29862. };
  29863. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29864. // Animations
  29865. this.getScene().stopAnimation(this);
  29866. // Remove from scene
  29867. var index = this._scene.materials.indexOf(this);
  29868. if (index >= 0) {
  29869. this._scene.materials.splice(index, 1);
  29870. }
  29871. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29872. if (forceDisposeEffect && this._effect) {
  29873. this._scene.getEngine()._releaseEffect(this._effect);
  29874. this._effect = null;
  29875. }
  29876. // Remove from meshes
  29877. for (index = 0; index < this._scene.meshes.length; index++) {
  29878. var mesh = this._scene.meshes[index];
  29879. if (mesh.material === this) {
  29880. mesh.material = null;
  29881. }
  29882. }
  29883. // Callback
  29884. this.onDisposeObservable.notifyObservers(this);
  29885. this.onDisposeObservable.clear();
  29886. this.onBindObservable.clear();
  29887. this.onUnBindObservable.clear();
  29888. };
  29889. Material.prototype.serialize = function () {
  29890. return BABYLON.SerializationHelper.Serialize(this);
  29891. };
  29892. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29893. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29894. multiMaterial.id = parsedMultiMaterial.id;
  29895. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29896. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29897. var subMatId = parsedMultiMaterial.materials[matIndex];
  29898. if (subMatId) {
  29899. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29900. }
  29901. else {
  29902. multiMaterial.subMaterials.push(null);
  29903. }
  29904. }
  29905. return multiMaterial;
  29906. };
  29907. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29908. if (!parsedMaterial.customType) {
  29909. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29910. }
  29911. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29912. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29913. ;
  29914. };
  29915. return Material;
  29916. }());
  29917. Material._TriangleFillMode = 0;
  29918. Material._WireFrameFillMode = 1;
  29919. Material._PointFillMode = 2;
  29920. Material._ClockWiseSideOrientation = 0;
  29921. Material._CounterClockWiseSideOrientation = 1;
  29922. __decorate([
  29923. BABYLON.serialize()
  29924. ], Material.prototype, "id", void 0);
  29925. __decorate([
  29926. BABYLON.serialize()
  29927. ], Material.prototype, "name", void 0);
  29928. __decorate([
  29929. BABYLON.serialize()
  29930. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29931. __decorate([
  29932. BABYLON.serialize()
  29933. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29934. __decorate([
  29935. BABYLON.serialize()
  29936. ], Material.prototype, "state", void 0);
  29937. __decorate([
  29938. BABYLON.serialize()
  29939. ], Material.prototype, "alpha", void 0);
  29940. __decorate([
  29941. BABYLON.serialize()
  29942. ], Material.prototype, "backFaceCulling", void 0);
  29943. __decorate([
  29944. BABYLON.serialize()
  29945. ], Material.prototype, "sideOrientation", void 0);
  29946. __decorate([
  29947. BABYLON.serialize()
  29948. ], Material.prototype, "alphaMode", void 0);
  29949. __decorate([
  29950. BABYLON.serialize()
  29951. ], Material.prototype, "disableDepthWrite", void 0);
  29952. __decorate([
  29953. BABYLON.serialize()
  29954. ], Material.prototype, "fogEnabled", void 0);
  29955. __decorate([
  29956. BABYLON.serialize()
  29957. ], Material.prototype, "pointSize", void 0);
  29958. __decorate([
  29959. BABYLON.serialize()
  29960. ], Material.prototype, "zOffset", void 0);
  29961. __decorate([
  29962. BABYLON.serialize()
  29963. ], Material.prototype, "wireframe", null);
  29964. __decorate([
  29965. BABYLON.serialize()
  29966. ], Material.prototype, "pointsCloud", null);
  29967. __decorate([
  29968. BABYLON.serialize()
  29969. ], Material.prototype, "fillMode", null);
  29970. BABYLON.Material = Material;
  29971. })(BABYLON || (BABYLON = {}));
  29972. //# sourceMappingURL=babylon.material.js.map
  29973. var BABYLON;
  29974. (function (BABYLON) {
  29975. var StandardMaterialDefines = (function (_super) {
  29976. __extends(StandardMaterialDefines, _super);
  29977. function StandardMaterialDefines() {
  29978. var _this = _super.call(this) || this;
  29979. _this.DIFFUSE = false;
  29980. _this.AMBIENT = false;
  29981. _this.OPACITY = false;
  29982. _this.OPACITYRGB = false;
  29983. _this.REFLECTION = false;
  29984. _this.EMISSIVE = false;
  29985. _this.SPECULAR = false;
  29986. _this.BUMP = false;
  29987. _this.PARALLAX = false;
  29988. _this.PARALLAXOCCLUSION = false;
  29989. _this.SPECULAROVERALPHA = false;
  29990. _this.CLIPPLANE = false;
  29991. _this.ALPHATEST = false;
  29992. _this.ALPHAFROMDIFFUSE = false;
  29993. _this.POINTSIZE = false;
  29994. _this.FOG = false;
  29995. _this.SPECULARTERM = false;
  29996. _this.DIFFUSEFRESNEL = false;
  29997. _this.OPACITYFRESNEL = false;
  29998. _this.REFLECTIONFRESNEL = false;
  29999. _this.REFRACTIONFRESNEL = false;
  30000. _this.EMISSIVEFRESNEL = false;
  30001. _this.FRESNEL = false;
  30002. _this.NORMAL = false;
  30003. _this.UV1 = false;
  30004. _this.UV2 = false;
  30005. _this.VERTEXCOLOR = false;
  30006. _this.VERTEXALPHA = false;
  30007. _this.NUM_BONE_INFLUENCERS = 0;
  30008. _this.BonesPerMesh = 0;
  30009. _this.INSTANCES = false;
  30010. _this.GLOSSINESS = false;
  30011. _this.ROUGHNESS = false;
  30012. _this.EMISSIVEASILLUMINATION = false;
  30013. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30014. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30015. _this.LIGHTMAP = false;
  30016. _this.USELIGHTMAPASSHADOWMAP = false;
  30017. _this.REFLECTIONMAP_3D = false;
  30018. _this.REFLECTIONMAP_SPHERICAL = false;
  30019. _this.REFLECTIONMAP_PLANAR = false;
  30020. _this.REFLECTIONMAP_CUBIC = false;
  30021. _this.REFLECTIONMAP_PROJECTION = false;
  30022. _this.REFLECTIONMAP_SKYBOX = false;
  30023. _this.REFLECTIONMAP_EXPLICIT = false;
  30024. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30025. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30026. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30027. _this.INVERTCUBICMAP = false;
  30028. _this.LOGARITHMICDEPTH = false;
  30029. _this.REFRACTION = false;
  30030. _this.REFRACTIONMAP_3D = false;
  30031. _this.REFLECTIONOVERALPHA = false;
  30032. _this.INVERTNORMALMAPX = false;
  30033. _this.INVERTNORMALMAPY = false;
  30034. _this.TWOSIDEDLIGHTING = false;
  30035. _this.SHADOWFULLFLOAT = false;
  30036. _this.CAMERACOLORGRADING = false;
  30037. _this.CAMERACOLORCURVES = false;
  30038. _this.rebuild();
  30039. return _this;
  30040. }
  30041. return StandardMaterialDefines;
  30042. }(BABYLON.MaterialDefines));
  30043. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30044. var StandardMaterial = (function (_super) {
  30045. __extends(StandardMaterial, _super);
  30046. function StandardMaterial(name, scene) {
  30047. var _this = _super.call(this, name, scene) || this;
  30048. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30049. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30050. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30051. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30052. _this.specularPower = 64;
  30053. _this.useAlphaFromDiffuseTexture = false;
  30054. _this.useEmissiveAsIllumination = false;
  30055. _this.linkEmissiveWithDiffuse = false;
  30056. _this.useReflectionFresnelFromSpecular = false;
  30057. _this.useSpecularOverAlpha = false;
  30058. _this.useReflectionOverAlpha = false;
  30059. _this.disableLighting = false;
  30060. _this.useParallax = false;
  30061. _this.useParallaxOcclusion = false;
  30062. _this.parallaxScaleBias = 0.05;
  30063. _this.roughness = 0;
  30064. _this.indexOfRefraction = 0.98;
  30065. _this.invertRefractionY = true;
  30066. _this.useLightmapAsShadowmap = false;
  30067. _this.useGlossinessFromSpecularMapAlpha = false;
  30068. _this.maxSimultaneousLights = 4;
  30069. /**
  30070. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30071. */
  30072. _this.invertNormalMapX = false;
  30073. /**
  30074. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30075. */
  30076. _this.invertNormalMapY = false;
  30077. /**
  30078. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30079. */
  30080. _this.twoSidedLighting = false;
  30081. /**
  30082. * Color Grading 2D Lookup Texture.
  30083. * This allows special effects like sepia, black and white to sixties rendering style.
  30084. */
  30085. _this.cameraColorGradingTexture = null;
  30086. /**
  30087. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  30088. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  30089. * 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;
  30090. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  30091. */
  30092. _this.cameraColorCurves = null;
  30093. _this._renderTargets = new BABYLON.SmartArray(16);
  30094. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30095. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30096. _this._defines = new StandardMaterialDefines();
  30097. _this._cachedDefines = new StandardMaterialDefines();
  30098. _this._cachedDefines.BonesPerMesh = -1;
  30099. _this.getRenderTargetTextures = function () {
  30100. _this._renderTargets.reset();
  30101. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  30102. _this._renderTargets.push(_this.reflectionTexture);
  30103. }
  30104. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  30105. _this._renderTargets.push(_this.refractionTexture);
  30106. }
  30107. return _this._renderTargets;
  30108. };
  30109. return _this;
  30110. }
  30111. StandardMaterial.prototype.getClassName = function () {
  30112. return "StandardMaterial";
  30113. };
  30114. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30115. get: function () {
  30116. return this._useLogarithmicDepth;
  30117. },
  30118. set: function (value) {
  30119. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30120. },
  30121. enumerable: true,
  30122. configurable: true
  30123. });
  30124. StandardMaterial.prototype.needAlphaBlending = function () {
  30125. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  30126. };
  30127. StandardMaterial.prototype.needAlphaTesting = function () {
  30128. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  30129. };
  30130. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30131. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  30132. };
  30133. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30134. return this.diffuseTexture;
  30135. };
  30136. // Methods
  30137. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  30138. if (!mesh) {
  30139. return true;
  30140. }
  30141. if (this._defines.INSTANCES !== useInstances) {
  30142. return false;
  30143. }
  30144. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  30145. return true;
  30146. }
  30147. return false;
  30148. };
  30149. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  30150. if (this.isFrozen) {
  30151. if (this._wasPreviouslyReady) {
  30152. return true;
  30153. }
  30154. }
  30155. var scene = this.getScene();
  30156. var engine = scene.getEngine();
  30157. var needUVs = false;
  30158. var needNormals = false;
  30159. this._defines.reset();
  30160. // Lights
  30161. if (scene.lightsEnabled && !this.disableLighting) {
  30162. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  30163. }
  30164. if (!this.checkReadyOnEveryCall) {
  30165. if (this._renderId === scene.getRenderId()) {
  30166. if (this._checkCache(scene, mesh, useInstances)) {
  30167. return true;
  30168. }
  30169. }
  30170. }
  30171. // Textures
  30172. if (scene.texturesEnabled) {
  30173. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30174. if (!this.diffuseTexture.isReady()) {
  30175. return false;
  30176. }
  30177. else {
  30178. needUVs = true;
  30179. this._defines.DIFFUSE = true;
  30180. }
  30181. }
  30182. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30183. if (!this.ambientTexture.isReady()) {
  30184. return false;
  30185. }
  30186. else {
  30187. needUVs = true;
  30188. this._defines.AMBIENT = true;
  30189. }
  30190. }
  30191. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30192. if (!this.opacityTexture.isReady()) {
  30193. return false;
  30194. }
  30195. else {
  30196. needUVs = true;
  30197. this._defines.OPACITY = true;
  30198. if (this.opacityTexture.getAlphaFromRGB) {
  30199. this._defines.OPACITYRGB = true;
  30200. }
  30201. }
  30202. }
  30203. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30204. if (!this.reflectionTexture.isReady()) {
  30205. return false;
  30206. }
  30207. else {
  30208. needNormals = true;
  30209. this._defines.REFLECTION = true;
  30210. if (this.roughness > 0) {
  30211. this._defines.ROUGHNESS = true;
  30212. }
  30213. if (this.useReflectionOverAlpha) {
  30214. this._defines.REFLECTIONOVERALPHA = true;
  30215. }
  30216. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  30217. this._defines.INVERTCUBICMAP = true;
  30218. }
  30219. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  30220. switch (this.reflectionTexture.coordinatesMode) {
  30221. case BABYLON.Texture.CUBIC_MODE:
  30222. case BABYLON.Texture.INVCUBIC_MODE:
  30223. this._defines.REFLECTIONMAP_CUBIC = true;
  30224. break;
  30225. case BABYLON.Texture.EXPLICIT_MODE:
  30226. this._defines.REFLECTIONMAP_EXPLICIT = true;
  30227. break;
  30228. case BABYLON.Texture.PLANAR_MODE:
  30229. this._defines.REFLECTIONMAP_PLANAR = true;
  30230. break;
  30231. case BABYLON.Texture.PROJECTION_MODE:
  30232. this._defines.REFLECTIONMAP_PROJECTION = true;
  30233. break;
  30234. case BABYLON.Texture.SKYBOX_MODE:
  30235. this._defines.REFLECTIONMAP_SKYBOX = true;
  30236. break;
  30237. case BABYLON.Texture.SPHERICAL_MODE:
  30238. this._defines.REFLECTIONMAP_SPHERICAL = true;
  30239. break;
  30240. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30241. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  30242. break;
  30243. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30244. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  30245. break;
  30246. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30247. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  30248. break;
  30249. }
  30250. }
  30251. }
  30252. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30253. if (!this.emissiveTexture.isReady()) {
  30254. return false;
  30255. }
  30256. else {
  30257. needUVs = true;
  30258. this._defines.EMISSIVE = true;
  30259. }
  30260. }
  30261. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30262. if (!this.lightmapTexture.isReady()) {
  30263. return false;
  30264. }
  30265. else {
  30266. needUVs = true;
  30267. this._defines.LIGHTMAP = true;
  30268. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  30269. }
  30270. }
  30271. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30272. if (!this.specularTexture.isReady()) {
  30273. return false;
  30274. }
  30275. else {
  30276. needUVs = true;
  30277. this._defines.SPECULAR = true;
  30278. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  30279. }
  30280. }
  30281. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30282. if (!this.bumpTexture.isReady()) {
  30283. return false;
  30284. }
  30285. else {
  30286. needUVs = true;
  30287. this._defines.BUMP = true;
  30288. if (this.useParallax) {
  30289. this._defines.PARALLAX = true;
  30290. if (this.useParallaxOcclusion) {
  30291. this._defines.PARALLAXOCCLUSION = true;
  30292. }
  30293. }
  30294. if (this.invertNormalMapX) {
  30295. this._defines.INVERTNORMALMAPX = true;
  30296. }
  30297. if (this.invertNormalMapY) {
  30298. this._defines.INVERTNORMALMAPY = true;
  30299. }
  30300. if (scene._mirroredCameraPosition) {
  30301. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  30302. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  30303. }
  30304. }
  30305. }
  30306. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30307. if (!this.refractionTexture.isReady()) {
  30308. return false;
  30309. }
  30310. else {
  30311. needUVs = true;
  30312. this._defines.REFRACTION = true;
  30313. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  30314. }
  30315. }
  30316. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30317. if (!this.cameraColorGradingTexture.isReady()) {
  30318. return false;
  30319. }
  30320. else {
  30321. this._defines.CAMERACOLORGRADING = true;
  30322. }
  30323. }
  30324. if (!this.backFaceCulling && this.twoSidedLighting) {
  30325. this._defines.TWOSIDEDLIGHTING = true;
  30326. }
  30327. }
  30328. // Effect
  30329. if (scene.clipPlane) {
  30330. this._defines.CLIPPLANE = true;
  30331. }
  30332. if (engine.getAlphaTesting()) {
  30333. this._defines.ALPHATEST = true;
  30334. }
  30335. if (this._shouldUseAlphaFromDiffuseTexture()) {
  30336. this._defines.ALPHAFROMDIFFUSE = true;
  30337. }
  30338. if (this.useEmissiveAsIllumination) {
  30339. this._defines.EMISSIVEASILLUMINATION = true;
  30340. }
  30341. if (this.linkEmissiveWithDiffuse) {
  30342. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  30343. }
  30344. if (this.useLogarithmicDepth) {
  30345. this._defines.LOGARITHMICDEPTH = true;
  30346. }
  30347. if (this.cameraColorCurves) {
  30348. this._defines.CAMERACOLORCURVES = true;
  30349. }
  30350. // Point size
  30351. if (this.pointsCloud || scene.forcePointsCloud) {
  30352. this._defines.POINTSIZE = true;
  30353. }
  30354. // Fog
  30355. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  30356. this._defines.FOG = true;
  30357. }
  30358. if (StandardMaterial.FresnelEnabled) {
  30359. // Fresnel
  30360. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  30361. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  30362. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  30363. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  30364. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30365. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30366. this._defines.DIFFUSEFRESNEL = true;
  30367. }
  30368. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30369. this._defines.OPACITYFRESNEL = true;
  30370. }
  30371. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30372. this._defines.REFLECTIONFRESNEL = true;
  30373. if (this.useReflectionFresnelFromSpecular) {
  30374. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  30375. }
  30376. }
  30377. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30378. this._defines.REFRACTIONFRESNEL = true;
  30379. }
  30380. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30381. this._defines.EMISSIVEFRESNEL = true;
  30382. }
  30383. needNormals = true;
  30384. this._defines.FRESNEL = true;
  30385. }
  30386. }
  30387. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  30388. this._defines.SPECULAROVERALPHA = true;
  30389. }
  30390. // Attribs
  30391. if (mesh) {
  30392. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30393. this._defines.NORMAL = true;
  30394. }
  30395. if (needUVs) {
  30396. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30397. this._defines.UV1 = true;
  30398. }
  30399. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30400. this._defines.UV2 = true;
  30401. }
  30402. }
  30403. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30404. this._defines.VERTEXCOLOR = true;
  30405. if (mesh.hasVertexAlpha) {
  30406. this._defines.VERTEXALPHA = true;
  30407. }
  30408. }
  30409. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  30410. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  30411. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  30412. }
  30413. // Instances
  30414. if (useInstances) {
  30415. this._defines.INSTANCES = true;
  30416. }
  30417. }
  30418. // Get correct effect
  30419. if (!this._defines.isEqual(this._cachedDefines)) {
  30420. this._defines.cloneTo(this._cachedDefines);
  30421. scene.resetCachedMaterial();
  30422. // Fallbacks
  30423. var fallbacks = new BABYLON.EffectFallbacks();
  30424. if (this._defines.REFLECTION) {
  30425. fallbacks.addFallback(0, "REFLECTION");
  30426. }
  30427. if (this._defines.SPECULAR) {
  30428. fallbacks.addFallback(0, "SPECULAR");
  30429. }
  30430. if (this._defines.BUMP) {
  30431. fallbacks.addFallback(0, "BUMP");
  30432. }
  30433. if (this._defines.PARALLAX) {
  30434. fallbacks.addFallback(1, "PARALLAX");
  30435. }
  30436. if (this._defines.PARALLAXOCCLUSION) {
  30437. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30438. }
  30439. if (this._defines.SPECULAROVERALPHA) {
  30440. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30441. }
  30442. if (this._defines.FOG) {
  30443. fallbacks.addFallback(1, "FOG");
  30444. }
  30445. if (this._defines.POINTSIZE) {
  30446. fallbacks.addFallback(0, "POINTSIZE");
  30447. }
  30448. if (this._defines.LOGARITHMICDEPTH) {
  30449. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30450. }
  30451. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  30452. if (this._defines.SPECULARTERM) {
  30453. fallbacks.addFallback(0, "SPECULARTERM");
  30454. }
  30455. if (this._defines.DIFFUSEFRESNEL) {
  30456. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30457. }
  30458. if (this._defines.OPACITYFRESNEL) {
  30459. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30460. }
  30461. if (this._defines.REFLECTIONFRESNEL) {
  30462. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30463. }
  30464. if (this._defines.EMISSIVEFRESNEL) {
  30465. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30466. }
  30467. if (this._defines.FRESNEL) {
  30468. fallbacks.addFallback(4, "FRESNEL");
  30469. }
  30470. //Attributes
  30471. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30472. if (this._defines.NORMAL) {
  30473. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30474. }
  30475. if (this._defines.UV1) {
  30476. attribs.push(BABYLON.VertexBuffer.UVKind);
  30477. }
  30478. if (this._defines.UV2) {
  30479. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30480. }
  30481. if (this._defines.VERTEXCOLOR) {
  30482. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30483. }
  30484. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  30485. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  30486. var shaderName = "default";
  30487. var join = this._defines.toString();
  30488. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30489. "vFogInfos", "vFogColor", "pointSize",
  30490. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30491. "mBones",
  30492. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30493. "depthValues",
  30494. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30495. "logarithmicDepthConstant"
  30496. ];
  30497. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30498. if (this._defines.CAMERACOLORCURVES) {
  30499. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  30500. }
  30501. if (this._defines.CAMERACOLORGRADING) {
  30502. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  30503. }
  30504. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  30505. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  30506. }
  30507. if (!this._effect.isReady()) {
  30508. return false;
  30509. }
  30510. this._renderId = scene.getRenderId();
  30511. this._wasPreviouslyReady = true;
  30512. if (mesh) {
  30513. if (!mesh._materialDefines) {
  30514. mesh._materialDefines = new StandardMaterialDefines();
  30515. }
  30516. this._defines.cloneTo(mesh._materialDefines);
  30517. }
  30518. return true;
  30519. };
  30520. StandardMaterial.prototype.unbind = function () {
  30521. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  30522. this._effect.setTexture("reflection2DSampler", null);
  30523. }
  30524. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  30525. this._effect.setTexture("refraction2DSampler", null);
  30526. }
  30527. _super.prototype.unbind.call(this);
  30528. };
  30529. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  30530. this._effect.setMatrix("world", world);
  30531. };
  30532. StandardMaterial.prototype.bind = function (world, mesh) {
  30533. var scene = this.getScene();
  30534. // Matrices
  30535. this.bindOnlyWorldMatrix(world);
  30536. // Bones
  30537. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  30538. if (scene.getCachedMaterial() !== this) {
  30539. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30540. if (StandardMaterial.FresnelEnabled) {
  30541. // Fresnel
  30542. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30543. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30544. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30545. }
  30546. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30547. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30548. }
  30549. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30550. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30551. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30552. }
  30553. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30554. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30555. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30556. }
  30557. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30558. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30559. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30560. }
  30561. }
  30562. // Textures
  30563. if (scene.texturesEnabled) {
  30564. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30565. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  30566. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  30567. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  30568. }
  30569. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30570. this._effect.setTexture("ambientSampler", this.ambientTexture);
  30571. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  30572. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  30573. }
  30574. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30575. this._effect.setTexture("opacitySampler", this.opacityTexture);
  30576. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  30577. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  30578. }
  30579. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30580. if (this.reflectionTexture.isCube) {
  30581. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  30582. }
  30583. else {
  30584. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  30585. }
  30586. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  30587. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  30588. }
  30589. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30590. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  30591. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  30592. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  30593. }
  30594. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30595. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  30596. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  30597. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  30598. }
  30599. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30600. this._effect.setTexture("specularSampler", this.specularTexture);
  30601. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  30602. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  30603. }
  30604. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30605. this._effect.setTexture("bumpSampler", this.bumpTexture);
  30606. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  30607. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  30608. }
  30609. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30610. var depth = 1.0;
  30611. if (this.refractionTexture.isCube) {
  30612. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  30613. }
  30614. else {
  30615. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  30616. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  30617. if (this.refractionTexture.depth) {
  30618. depth = this.refractionTexture.depth;
  30619. }
  30620. }
  30621. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30622. }
  30623. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  30624. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  30625. }
  30626. }
  30627. // Clip plane
  30628. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  30629. // Point size
  30630. if (this.pointsCloud) {
  30631. this._effect.setFloat("pointSize", this.pointSize);
  30632. }
  30633. // Colors
  30634. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30635. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  30636. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30637. if (this._defines.SPECULARTERM) {
  30638. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  30639. }
  30640. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  30641. }
  30642. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  30643. // Diffuse
  30644. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30645. // Lights
  30646. if (scene.lightsEnabled && !this.disableLighting) {
  30647. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  30648. }
  30649. // View
  30650. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  30651. this._effect.setMatrix("view", scene.getViewMatrix());
  30652. }
  30653. // Fog
  30654. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  30655. // Log. depth
  30656. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  30657. // Color Curves
  30658. if (this.cameraColorCurves) {
  30659. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  30660. }
  30661. }
  30662. _super.prototype.bind.call(this, world, mesh);
  30663. };
  30664. StandardMaterial.prototype.getAnimatables = function () {
  30665. var results = [];
  30666. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  30667. results.push(this.diffuseTexture);
  30668. }
  30669. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  30670. results.push(this.ambientTexture);
  30671. }
  30672. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  30673. results.push(this.opacityTexture);
  30674. }
  30675. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  30676. results.push(this.reflectionTexture);
  30677. }
  30678. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  30679. results.push(this.emissiveTexture);
  30680. }
  30681. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  30682. results.push(this.specularTexture);
  30683. }
  30684. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  30685. results.push(this.bumpTexture);
  30686. }
  30687. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  30688. results.push(this.lightmapTexture);
  30689. }
  30690. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  30691. results.push(this.refractionTexture);
  30692. }
  30693. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  30694. results.push(this.cameraColorGradingTexture);
  30695. }
  30696. return results;
  30697. };
  30698. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30699. if (forceDisposeTextures) {
  30700. if (this.diffuseTexture) {
  30701. this.diffuseTexture.dispose();
  30702. }
  30703. if (this.ambientTexture) {
  30704. this.ambientTexture.dispose();
  30705. }
  30706. if (this.opacityTexture) {
  30707. this.opacityTexture.dispose();
  30708. }
  30709. if (this.reflectionTexture) {
  30710. this.reflectionTexture.dispose();
  30711. }
  30712. if (this.emissiveTexture) {
  30713. this.emissiveTexture.dispose();
  30714. }
  30715. if (this.specularTexture) {
  30716. this.specularTexture.dispose();
  30717. }
  30718. if (this.bumpTexture) {
  30719. this.bumpTexture.dispose();
  30720. }
  30721. if (this.lightmapTexture) {
  30722. this.lightmapTexture.dispose();
  30723. }
  30724. if (this.refractionTexture) {
  30725. this.refractionTexture.dispose();
  30726. }
  30727. if (this.cameraColorGradingTexture) {
  30728. this.cameraColorGradingTexture.dispose();
  30729. }
  30730. }
  30731. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  30732. };
  30733. StandardMaterial.prototype.clone = function (name) {
  30734. var _this = this;
  30735. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  30736. };
  30737. StandardMaterial.prototype.serialize = function () {
  30738. return BABYLON.SerializationHelper.Serialize(this);
  30739. };
  30740. // Statics
  30741. StandardMaterial.Parse = function (source, scene, rootUrl) {
  30742. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  30743. };
  30744. return StandardMaterial;
  30745. }(BABYLON.Material));
  30746. // Flags used to enable or disable a type of texture for all Standard Materials
  30747. StandardMaterial.DiffuseTextureEnabled = true;
  30748. StandardMaterial.AmbientTextureEnabled = true;
  30749. StandardMaterial.OpacityTextureEnabled = true;
  30750. StandardMaterial.ReflectionTextureEnabled = true;
  30751. StandardMaterial.EmissiveTextureEnabled = true;
  30752. StandardMaterial.SpecularTextureEnabled = true;
  30753. StandardMaterial.BumpTextureEnabled = true;
  30754. StandardMaterial.FresnelEnabled = true;
  30755. StandardMaterial.LightmapTextureEnabled = true;
  30756. StandardMaterial.RefractionTextureEnabled = true;
  30757. StandardMaterial.ColorGradingTextureEnabled = true;
  30758. __decorate([
  30759. BABYLON.serializeAsTexture()
  30760. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  30761. __decorate([
  30762. BABYLON.serializeAsTexture()
  30763. ], StandardMaterial.prototype, "ambientTexture", void 0);
  30764. __decorate([
  30765. BABYLON.serializeAsTexture()
  30766. ], StandardMaterial.prototype, "opacityTexture", void 0);
  30767. __decorate([
  30768. BABYLON.serializeAsTexture()
  30769. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  30770. __decorate([
  30771. BABYLON.serializeAsTexture()
  30772. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  30773. __decorate([
  30774. BABYLON.serializeAsTexture()
  30775. ], StandardMaterial.prototype, "specularTexture", void 0);
  30776. __decorate([
  30777. BABYLON.serializeAsTexture()
  30778. ], StandardMaterial.prototype, "bumpTexture", void 0);
  30779. __decorate([
  30780. BABYLON.serializeAsTexture()
  30781. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  30782. __decorate([
  30783. BABYLON.serializeAsTexture()
  30784. ], StandardMaterial.prototype, "refractionTexture", void 0);
  30785. __decorate([
  30786. BABYLON.serializeAsColor3("ambient")
  30787. ], StandardMaterial.prototype, "ambientColor", void 0);
  30788. __decorate([
  30789. BABYLON.serializeAsColor3("diffuse")
  30790. ], StandardMaterial.prototype, "diffuseColor", void 0);
  30791. __decorate([
  30792. BABYLON.serializeAsColor3("specular")
  30793. ], StandardMaterial.prototype, "specularColor", void 0);
  30794. __decorate([
  30795. BABYLON.serializeAsColor3("emissive")
  30796. ], StandardMaterial.prototype, "emissiveColor", void 0);
  30797. __decorate([
  30798. BABYLON.serialize()
  30799. ], StandardMaterial.prototype, "specularPower", void 0);
  30800. __decorate([
  30801. BABYLON.serialize()
  30802. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  30803. __decorate([
  30804. BABYLON.serialize()
  30805. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  30806. __decorate([
  30807. BABYLON.serialize()
  30808. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  30809. __decorate([
  30810. BABYLON.serialize()
  30811. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  30812. __decorate([
  30813. BABYLON.serialize()
  30814. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  30815. __decorate([
  30816. BABYLON.serialize()
  30817. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  30818. __decorate([
  30819. BABYLON.serialize()
  30820. ], StandardMaterial.prototype, "disableLighting", void 0);
  30821. __decorate([
  30822. BABYLON.serialize()
  30823. ], StandardMaterial.prototype, "useParallax", void 0);
  30824. __decorate([
  30825. BABYLON.serialize()
  30826. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  30827. __decorate([
  30828. BABYLON.serialize()
  30829. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  30830. __decorate([
  30831. BABYLON.serialize()
  30832. ], StandardMaterial.prototype, "roughness", void 0);
  30833. __decorate([
  30834. BABYLON.serialize()
  30835. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  30836. __decorate([
  30837. BABYLON.serialize()
  30838. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  30839. __decorate([
  30840. BABYLON.serialize()
  30841. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  30842. __decorate([
  30843. BABYLON.serializeAsFresnelParameters()
  30844. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  30845. __decorate([
  30846. BABYLON.serializeAsFresnelParameters()
  30847. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  30848. __decorate([
  30849. BABYLON.serializeAsFresnelParameters()
  30850. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  30851. __decorate([
  30852. BABYLON.serializeAsFresnelParameters()
  30853. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  30854. __decorate([
  30855. BABYLON.serializeAsFresnelParameters()
  30856. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  30857. __decorate([
  30858. BABYLON.serialize()
  30859. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  30860. __decorate([
  30861. BABYLON.serialize()
  30862. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  30863. __decorate([
  30864. BABYLON.serialize()
  30865. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  30866. __decorate([
  30867. BABYLON.serialize()
  30868. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  30869. __decorate([
  30870. BABYLON.serialize()
  30871. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  30872. __decorate([
  30873. BABYLON.serializeAsTexture()
  30874. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  30875. __decorate([
  30876. BABYLON.serializeAsColorCurves()
  30877. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  30878. __decorate([
  30879. BABYLON.serialize()
  30880. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  30881. BABYLON.StandardMaterial = StandardMaterial;
  30882. })(BABYLON || (BABYLON = {}));
  30883. //# sourceMappingURL=babylon.standardMaterial.js.map
  30884. var BABYLON;
  30885. (function (BABYLON) {
  30886. var MultiMaterial = (function (_super) {
  30887. __extends(MultiMaterial, _super);
  30888. function MultiMaterial(name, scene) {
  30889. var _this = _super.call(this, name, scene, true) || this;
  30890. _this.subMaterials = new Array();
  30891. scene.multiMaterials.push(_this);
  30892. return _this;
  30893. }
  30894. // Properties
  30895. MultiMaterial.prototype.getSubMaterial = function (index) {
  30896. if (index < 0 || index >= this.subMaterials.length) {
  30897. return this.getScene().defaultMaterial;
  30898. }
  30899. return this.subMaterials[index];
  30900. };
  30901. // Methods
  30902. MultiMaterial.prototype.getClassName = function () {
  30903. return "MultiMaterial";
  30904. };
  30905. MultiMaterial.prototype.isReady = function (mesh) {
  30906. for (var index = 0; index < this.subMaterials.length; index++) {
  30907. var subMaterial = this.subMaterials[index];
  30908. if (subMaterial) {
  30909. if (!this.subMaterials[index].isReady(mesh)) {
  30910. return false;
  30911. }
  30912. }
  30913. }
  30914. return true;
  30915. };
  30916. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  30917. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  30918. for (var index = 0; index < this.subMaterials.length; index++) {
  30919. var subMaterial = null;
  30920. if (cloneChildren) {
  30921. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  30922. }
  30923. else {
  30924. subMaterial = this.subMaterials[index];
  30925. }
  30926. newMultiMaterial.subMaterials.push(subMaterial);
  30927. }
  30928. return newMultiMaterial;
  30929. };
  30930. MultiMaterial.prototype.serialize = function () {
  30931. var serializationObject = {};
  30932. serializationObject.name = this.name;
  30933. serializationObject.id = this.id;
  30934. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30935. serializationObject.materials = [];
  30936. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  30937. var subMat = this.subMaterials[matIndex];
  30938. if (subMat) {
  30939. serializationObject.materials.push(subMat.id);
  30940. }
  30941. else {
  30942. serializationObject.materials.push(null);
  30943. }
  30944. }
  30945. return serializationObject;
  30946. };
  30947. return MultiMaterial;
  30948. }(BABYLON.Material));
  30949. BABYLON.MultiMaterial = MultiMaterial;
  30950. })(BABYLON || (BABYLON = {}));
  30951. //# sourceMappingURL=babylon.multiMaterial.js.map
  30952. var BABYLON;
  30953. (function (BABYLON) {
  30954. var SceneLoader = (function () {
  30955. function SceneLoader() {
  30956. }
  30957. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  30958. get: function () {
  30959. return 0;
  30960. },
  30961. enumerable: true,
  30962. configurable: true
  30963. });
  30964. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  30965. get: function () {
  30966. return 1;
  30967. },
  30968. enumerable: true,
  30969. configurable: true
  30970. });
  30971. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  30972. get: function () {
  30973. return 2;
  30974. },
  30975. enumerable: true,
  30976. configurable: true
  30977. });
  30978. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  30979. get: function () {
  30980. return 3;
  30981. },
  30982. enumerable: true,
  30983. configurable: true
  30984. });
  30985. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  30986. get: function () {
  30987. return SceneLoader._ForceFullSceneLoadingForIncremental;
  30988. },
  30989. set: function (value) {
  30990. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  30991. },
  30992. enumerable: true,
  30993. configurable: true
  30994. });
  30995. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  30996. get: function () {
  30997. return SceneLoader._ShowLoadingScreen;
  30998. },
  30999. set: function (value) {
  31000. SceneLoader._ShowLoadingScreen = value;
  31001. },
  31002. enumerable: true,
  31003. configurable: true
  31004. });
  31005. Object.defineProperty(SceneLoader, "loggingLevel", {
  31006. get: function () {
  31007. return SceneLoader._loggingLevel;
  31008. },
  31009. set: function (value) {
  31010. SceneLoader._loggingLevel = value;
  31011. },
  31012. enumerable: true,
  31013. configurable: true
  31014. });
  31015. SceneLoader._getDefaultPlugin = function () {
  31016. return SceneLoader._registeredPlugins[".babylon"];
  31017. };
  31018. SceneLoader._getPluginForExtension = function (extension) {
  31019. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  31020. if (registeredPlugin) {
  31021. return registeredPlugin;
  31022. }
  31023. return SceneLoader._getDefaultPlugin();
  31024. };
  31025. SceneLoader._getPluginForFilename = function (sceneFilename) {
  31026. if (sceneFilename.name) {
  31027. sceneFilename = sceneFilename.name;
  31028. }
  31029. var dotPosition = sceneFilename.lastIndexOf(".");
  31030. var queryStringPosition = sceneFilename.indexOf("?");
  31031. if (queryStringPosition === -1) {
  31032. queryStringPosition = sceneFilename.length;
  31033. }
  31034. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  31035. return SceneLoader._getPluginForExtension(extension);
  31036. };
  31037. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  31038. SceneLoader._getDirectLoad = function (sceneFilename) {
  31039. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  31040. return sceneFilename.substr(5);
  31041. }
  31042. return null;
  31043. };
  31044. // Public functions
  31045. SceneLoader.GetPluginForExtension = function (extension) {
  31046. return SceneLoader._getPluginForExtension(extension).plugin;
  31047. };
  31048. SceneLoader.RegisterPlugin = function (plugin) {
  31049. if (typeof plugin.extensions === "string") {
  31050. var extension = plugin.extensions;
  31051. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  31052. plugin: plugin,
  31053. isBinary: false
  31054. };
  31055. }
  31056. else {
  31057. var extensions = plugin.extensions;
  31058. Object.keys(extensions).forEach(function (extension) {
  31059. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  31060. plugin: plugin,
  31061. isBinary: extensions[extension].isBinary
  31062. };
  31063. });
  31064. }
  31065. };
  31066. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  31067. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31068. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31069. return;
  31070. }
  31071. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31072. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31073. return;
  31074. }
  31075. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  31076. var loadingToken = {};
  31077. scene._addPendingData(loadingToken);
  31078. var manifestChecked = function (success) {
  31079. scene.database = database;
  31080. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  31081. var plugin = registeredPlugin.plugin;
  31082. var useArrayBuffer = registeredPlugin.isBinary;
  31083. var importMeshFromData = function (data) {
  31084. var meshes = [];
  31085. var particleSystems = [];
  31086. var skeletons = [];
  31087. if (scene.isDisposed) {
  31088. if (onerror) {
  31089. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  31090. }
  31091. return;
  31092. }
  31093. try {
  31094. if (plugin.importMesh) {
  31095. var syncedPlugin = plugin;
  31096. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  31097. if (onerror) {
  31098. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31099. }
  31100. scene._removePendingData(loadingToken);
  31101. return;
  31102. }
  31103. if (onsuccess) {
  31104. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31105. onsuccess(meshes, particleSystems, skeletons);
  31106. scene._removePendingData(loadingToken);
  31107. }
  31108. }
  31109. else {
  31110. var asyncedPlugin = plugin;
  31111. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  31112. if (onsuccess) {
  31113. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  31114. onsuccess(meshes, particleSystems, skeletons);
  31115. scene._removePendingData(loadingToken);
  31116. }
  31117. }, function () {
  31118. if (onerror) {
  31119. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  31120. }
  31121. scene._removePendingData(loadingToken);
  31122. });
  31123. }
  31124. }
  31125. catch (e) {
  31126. if (onerror) {
  31127. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  31128. }
  31129. scene._removePendingData(loadingToken);
  31130. }
  31131. };
  31132. if (directLoad) {
  31133. importMeshFromData(directLoad);
  31134. return;
  31135. }
  31136. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  31137. importMeshFromData(data);
  31138. }, progressCallBack, database, useArrayBuffer, function () {
  31139. if (onerror) {
  31140. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  31141. }
  31142. });
  31143. };
  31144. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  31145. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31146. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31147. }
  31148. else {
  31149. // If the scene is a data stream or offline support is not enabled, it's a direct load
  31150. manifestChecked(true);
  31151. }
  31152. };
  31153. /**
  31154. * Load a scene
  31155. * @param rootUrl a string that defines the root url for scene and resources
  31156. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31157. * @param engine is the instance of BABYLON.Engine to use to create the scene
  31158. */
  31159. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  31160. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  31161. };
  31162. /**
  31163. * Append a scene
  31164. * @param rootUrl a string that defines the root url for scene and resources
  31165. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  31166. * @param scene is the instance of BABYLON.Scene to append to
  31167. */
  31168. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  31169. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  31170. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  31171. return;
  31172. }
  31173. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  31174. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  31175. var plugin = registeredPlugin.plugin;
  31176. var useArrayBuffer = registeredPlugin.isBinary;
  31177. var database;
  31178. var loadingToken = {};
  31179. scene._addPendingData(loadingToken);
  31180. if (SceneLoader.ShowLoadingScreen) {
  31181. scene.getEngine().displayLoadingUI();
  31182. }
  31183. var loadSceneFromData = function (data) {
  31184. scene.database = database;
  31185. if (plugin.load) {
  31186. var syncedPlugin = plugin;
  31187. if (!syncedPlugin.load(scene, data, rootUrl)) {
  31188. if (onerror) {
  31189. onerror(scene);
  31190. }
  31191. scene._removePendingData(loadingToken);
  31192. scene.getEngine().hideLoadingUI();
  31193. return;
  31194. }
  31195. if (onsuccess) {
  31196. onsuccess(scene);
  31197. }
  31198. scene._removePendingData(loadingToken);
  31199. }
  31200. else {
  31201. var asyncedPlugin = plugin;
  31202. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  31203. if (onsuccess) {
  31204. onsuccess(scene);
  31205. }
  31206. scene._removePendingData(loadingToken);
  31207. }, function () {
  31208. if (onerror) {
  31209. onerror(scene);
  31210. }
  31211. scene._removePendingData(loadingToken);
  31212. scene.getEngine().hideLoadingUI();
  31213. });
  31214. }
  31215. if (SceneLoader.ShowLoadingScreen) {
  31216. scene.executeWhenReady(function () {
  31217. scene.getEngine().hideLoadingUI();
  31218. });
  31219. }
  31220. };
  31221. var manifestChecked = function (success) {
  31222. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  31223. };
  31224. if (directLoad) {
  31225. loadSceneFromData(directLoad);
  31226. return;
  31227. }
  31228. if (rootUrl.indexOf("file:") === -1) {
  31229. if (scene.getEngine().enableOfflineSupport) {
  31230. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  31231. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  31232. }
  31233. else {
  31234. manifestChecked(true);
  31235. }
  31236. }
  31237. else {
  31238. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  31239. }
  31240. };
  31241. return SceneLoader;
  31242. }());
  31243. // Flags
  31244. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  31245. SceneLoader._ShowLoadingScreen = true;
  31246. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  31247. // Members
  31248. SceneLoader._registeredPlugins = {};
  31249. BABYLON.SceneLoader = SceneLoader;
  31250. ;
  31251. })(BABYLON || (BABYLON = {}));
  31252. //# sourceMappingURL=babylon.sceneLoader.js.map
  31253. var BABYLON;
  31254. (function (BABYLON) {
  31255. var Internals;
  31256. (function (Internals) {
  31257. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  31258. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31259. var parsedMaterial = parsedData.materials[index];
  31260. if (parsedMaterial.id === id) {
  31261. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31262. }
  31263. }
  31264. return null;
  31265. };
  31266. var isDescendantOf = function (mesh, names, hierarchyIds) {
  31267. names = (names instanceof Array) ? names : [names];
  31268. for (var i in names) {
  31269. if (mesh.name === names[i]) {
  31270. hierarchyIds.push(mesh.id);
  31271. return true;
  31272. }
  31273. }
  31274. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  31275. hierarchyIds.push(mesh.id);
  31276. return true;
  31277. }
  31278. return false;
  31279. };
  31280. var logOperation = function (operation, producer) {
  31281. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  31282. };
  31283. BABYLON.SceneLoader.RegisterPlugin({
  31284. extensions: ".babylon",
  31285. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  31286. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31287. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31288. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31289. // and avoid problems with multiple concurrent .babylon loads.
  31290. var log = "importMesh has failed JSON parse";
  31291. try {
  31292. var parsedData = JSON.parse(data);
  31293. log = "";
  31294. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31295. var loadedSkeletonsIds = [];
  31296. var loadedMaterialsIds = [];
  31297. var hierarchyIds = [];
  31298. var index;
  31299. var cache;
  31300. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31301. var parsedMesh = parsedData.meshes[index];
  31302. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  31303. if (meshesNames instanceof Array) {
  31304. // Remove found mesh name from list.
  31305. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  31306. }
  31307. //Geometry?
  31308. if (parsedMesh.geometryId) {
  31309. //does the file contain geometries?
  31310. if (parsedData.geometries) {
  31311. //find the correct geometry and add it to the scene
  31312. var found = false;
  31313. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  31314. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  31315. return;
  31316. }
  31317. else {
  31318. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  31319. if (parsedGeometryData.id === parsedMesh.geometryId) {
  31320. switch (geometryType) {
  31321. case "boxes":
  31322. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  31323. break;
  31324. case "spheres":
  31325. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  31326. break;
  31327. case "cylinders":
  31328. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  31329. break;
  31330. case "toruses":
  31331. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  31332. break;
  31333. case "grounds":
  31334. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  31335. break;
  31336. case "planes":
  31337. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  31338. break;
  31339. case "torusKnots":
  31340. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  31341. break;
  31342. case "vertexData":
  31343. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  31344. break;
  31345. }
  31346. found = true;
  31347. }
  31348. });
  31349. }
  31350. });
  31351. if (!found) {
  31352. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  31353. }
  31354. }
  31355. }
  31356. // Material ?
  31357. if (parsedMesh.materialId) {
  31358. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  31359. if (!materialFound && parsedData.multiMaterials) {
  31360. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  31361. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  31362. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  31363. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  31364. var subMatId = parsedMultiMaterial.materials[matIndex];
  31365. loadedMaterialsIds.push(subMatId);
  31366. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  31367. log += "\n\tMaterial " + mat.toString(fullDetails);
  31368. }
  31369. loadedMaterialsIds.push(parsedMultiMaterial.id);
  31370. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31371. materialFound = true;
  31372. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  31373. break;
  31374. }
  31375. }
  31376. }
  31377. if (!materialFound) {
  31378. loadedMaterialsIds.push(parsedMesh.materialId);
  31379. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  31380. if (!mat) {
  31381. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  31382. }
  31383. else {
  31384. log += "\n\tMaterial " + mat.toString(fullDetails);
  31385. }
  31386. }
  31387. }
  31388. // Skeleton ?
  31389. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  31390. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  31391. if (!skeletonAlreadyLoaded) {
  31392. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  31393. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  31394. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  31395. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31396. skeletons.push(skeleton);
  31397. loadedSkeletonsIds.push(parsedSkeleton.id);
  31398. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  31399. }
  31400. }
  31401. }
  31402. }
  31403. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31404. meshes.push(mesh);
  31405. log += "\n\tMesh " + mesh.toString(fullDetails);
  31406. }
  31407. }
  31408. // Connecting parents
  31409. var currentMesh;
  31410. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31411. currentMesh = scene.meshes[index];
  31412. if (currentMesh._waitingParentId) {
  31413. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  31414. currentMesh._waitingParentId = undefined;
  31415. }
  31416. }
  31417. // freeze and compute world matrix application
  31418. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31419. currentMesh = scene.meshes[index];
  31420. if (currentMesh._waitingFreezeWorldMatrix) {
  31421. currentMesh.freezeWorldMatrix();
  31422. currentMesh._waitingFreezeWorldMatrix = undefined;
  31423. }
  31424. else {
  31425. currentMesh.computeWorldMatrix(true);
  31426. }
  31427. }
  31428. // Particles
  31429. if (parsedData.particleSystems) {
  31430. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31431. var parsedParticleSystem = parsedData.particleSystems[index];
  31432. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  31433. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  31434. }
  31435. }
  31436. }
  31437. return true;
  31438. }
  31439. catch (err) {
  31440. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  31441. log = null;
  31442. throw err;
  31443. }
  31444. finally {
  31445. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31446. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31447. }
  31448. }
  31449. },
  31450. load: function (scene, data, rootUrl) {
  31451. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  31452. // when SceneLoader.debugLogging = true (default), or exception encountered.
  31453. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  31454. // and avoid problems with multiple concurrent .babylon loads.
  31455. var log = "importScene has failed JSON parse";
  31456. try {
  31457. var parsedData = JSON.parse(data);
  31458. log = "";
  31459. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  31460. // Scene
  31461. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  31462. scene.autoClear = parsedData.autoClear;
  31463. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  31464. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  31465. if (parsedData.gravity) {
  31466. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  31467. }
  31468. // Fog
  31469. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  31470. scene.fogMode = parsedData.fogMode;
  31471. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  31472. scene.fogStart = parsedData.fogStart;
  31473. scene.fogEnd = parsedData.fogEnd;
  31474. scene.fogDensity = parsedData.fogDensity;
  31475. log += "\tFog mode for scene: ";
  31476. switch (scene.fogMode) {
  31477. // getters not compiling, so using hardcoded
  31478. case 1:
  31479. log += "exp\n";
  31480. break;
  31481. case 2:
  31482. log += "exp2\n";
  31483. break;
  31484. case 3:
  31485. log += "linear\n";
  31486. break;
  31487. }
  31488. }
  31489. //Physics
  31490. if (parsedData.physicsEnabled) {
  31491. var physicsPlugin;
  31492. if (parsedData.physicsEngine === "cannon") {
  31493. physicsPlugin = new BABYLON.CannonJSPlugin();
  31494. }
  31495. else if (parsedData.physicsEngine === "oimo") {
  31496. physicsPlugin = new BABYLON.OimoJSPlugin();
  31497. }
  31498. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  31499. //else - default engine, which is currently oimo
  31500. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  31501. scene.enablePhysics(physicsGravity, physicsPlugin);
  31502. }
  31503. // Metadata
  31504. if (parsedData.metadata !== undefined) {
  31505. scene.metadata = parsedData.metadata;
  31506. }
  31507. //collisions, if defined. otherwise, default is true
  31508. if (parsedData.collisionsEnabled != undefined) {
  31509. scene.collisionsEnabled = parsedData.collisionsEnabled;
  31510. }
  31511. scene.workerCollisions = !!parsedData.workerCollisions;
  31512. var index;
  31513. var cache;
  31514. // Lights
  31515. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  31516. var parsedLight = parsedData.lights[index];
  31517. var light = BABYLON.Light.Parse(parsedLight, scene);
  31518. log += (index === 0 ? "\n\tLights:" : "");
  31519. log += "\n\t\t" + light.toString(fullDetails);
  31520. }
  31521. // Animations
  31522. if (parsedData.animations) {
  31523. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  31524. var parsedAnimation = parsedData.animations[index];
  31525. var animation = BABYLON.Animation.Parse(parsedAnimation);
  31526. scene.animations.push(animation);
  31527. log += (index === 0 ? "\n\tAnimations:" : "");
  31528. log += "\n\t\t" + animation.toString(fullDetails);
  31529. }
  31530. }
  31531. if (parsedData.autoAnimate) {
  31532. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  31533. }
  31534. // Materials
  31535. if (parsedData.materials) {
  31536. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  31537. var parsedMaterial = parsedData.materials[index];
  31538. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  31539. log += (index === 0 ? "\n\tMaterials:" : "");
  31540. log += "\n\t\t" + mat.toString(fullDetails);
  31541. }
  31542. }
  31543. if (parsedData.multiMaterials) {
  31544. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  31545. var parsedMultiMaterial = parsedData.multiMaterials[index];
  31546. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  31547. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  31548. log += "\n\t\t" + mmat.toString(fullDetails);
  31549. }
  31550. }
  31551. // Skeletons
  31552. if (parsedData.skeletons) {
  31553. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  31554. var parsedSkeleton = parsedData.skeletons[index];
  31555. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  31556. log += (index === 0 ? "\n\tSkeletons:" : "");
  31557. log += "\n\t\t" + skeleton.toString(fullDetails);
  31558. }
  31559. }
  31560. // Geometries
  31561. var geometries = parsedData.geometries;
  31562. if (geometries) {
  31563. // Boxes
  31564. var boxes = geometries.boxes;
  31565. if (boxes) {
  31566. for (index = 0, cache = boxes.length; index < cache; index++) {
  31567. var parsedBox = boxes[index];
  31568. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  31569. }
  31570. }
  31571. // Spheres
  31572. var spheres = geometries.spheres;
  31573. if (spheres) {
  31574. for (index = 0, cache = spheres.length; index < cache; index++) {
  31575. var parsedSphere = spheres[index];
  31576. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  31577. }
  31578. }
  31579. // Cylinders
  31580. var cylinders = geometries.cylinders;
  31581. if (cylinders) {
  31582. for (index = 0, cache = cylinders.length; index < cache; index++) {
  31583. var parsedCylinder = cylinders[index];
  31584. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  31585. }
  31586. }
  31587. // Toruses
  31588. var toruses = geometries.toruses;
  31589. if (toruses) {
  31590. for (index = 0, cache = toruses.length; index < cache; index++) {
  31591. var parsedTorus = toruses[index];
  31592. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  31593. }
  31594. }
  31595. // Grounds
  31596. var grounds = geometries.grounds;
  31597. if (grounds) {
  31598. for (index = 0, cache = grounds.length; index < cache; index++) {
  31599. var parsedGround = grounds[index];
  31600. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  31601. }
  31602. }
  31603. // Planes
  31604. var planes = geometries.planes;
  31605. if (planes) {
  31606. for (index = 0, cache = planes.length; index < cache; index++) {
  31607. var parsedPlane = planes[index];
  31608. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  31609. }
  31610. }
  31611. // TorusKnots
  31612. var torusKnots = geometries.torusKnots;
  31613. if (torusKnots) {
  31614. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  31615. var parsedTorusKnot = torusKnots[index];
  31616. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  31617. }
  31618. }
  31619. // VertexData
  31620. var vertexData = geometries.vertexData;
  31621. if (vertexData) {
  31622. for (index = 0, cache = vertexData.length; index < cache; index++) {
  31623. var parsedVertexData = vertexData[index];
  31624. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  31625. }
  31626. }
  31627. }
  31628. // Meshes
  31629. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  31630. var parsedMesh = parsedData.meshes[index];
  31631. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  31632. log += (index === 0 ? "\n\tMeshes:" : "");
  31633. log += "\n\t\t" + mesh.toString(fullDetails);
  31634. }
  31635. // Cameras
  31636. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  31637. var parsedCamera = parsedData.cameras[index];
  31638. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  31639. log += (index === 0 ? "\n\tCameras:" : "");
  31640. log += "\n\t\t" + camera.toString(fullDetails);
  31641. }
  31642. if (parsedData.activeCameraID) {
  31643. scene.setActiveCameraByID(parsedData.activeCameraID);
  31644. }
  31645. // Browsing all the graph to connect the dots
  31646. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  31647. var camera = scene.cameras[index];
  31648. if (camera._waitingParentId) {
  31649. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  31650. camera._waitingParentId = undefined;
  31651. }
  31652. }
  31653. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  31654. var light = scene.lights[index];
  31655. if (light._waitingParentId) {
  31656. light.parent = scene.getLastEntryByID(light._waitingParentId);
  31657. light._waitingParentId = undefined;
  31658. }
  31659. }
  31660. // Sounds
  31661. var loadedSounds = [];
  31662. var loadedSound;
  31663. if (BABYLON.AudioEngine && parsedData.sounds) {
  31664. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  31665. var parsedSound = parsedData.sounds[index];
  31666. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  31667. if (!parsedSound.url)
  31668. parsedSound.url = parsedSound.name;
  31669. if (!loadedSounds[parsedSound.url]) {
  31670. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  31671. loadedSounds[parsedSound.url] = loadedSound;
  31672. }
  31673. else {
  31674. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  31675. }
  31676. }
  31677. else {
  31678. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  31679. }
  31680. }
  31681. }
  31682. loadedSounds = [];
  31683. // Connect parents & children and parse actions
  31684. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31685. var mesh = scene.meshes[index];
  31686. if (mesh._waitingParentId) {
  31687. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  31688. mesh._waitingParentId = undefined;
  31689. }
  31690. if (mesh._waitingActions) {
  31691. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  31692. mesh._waitingActions = undefined;
  31693. }
  31694. }
  31695. // freeze world matrix application
  31696. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  31697. var currentMesh = scene.meshes[index];
  31698. if (currentMesh._waitingFreezeWorldMatrix) {
  31699. currentMesh.freezeWorldMatrix();
  31700. currentMesh._waitingFreezeWorldMatrix = undefined;
  31701. }
  31702. else {
  31703. currentMesh.computeWorldMatrix(true);
  31704. }
  31705. }
  31706. // Particles Systems
  31707. if (parsedData.particleSystems) {
  31708. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  31709. var parsedParticleSystem = parsedData.particleSystems[index];
  31710. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  31711. }
  31712. }
  31713. // Lens flares
  31714. if (parsedData.lensFlareSystems) {
  31715. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  31716. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  31717. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  31718. }
  31719. }
  31720. // Shadows
  31721. if (parsedData.shadowGenerators) {
  31722. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  31723. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  31724. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  31725. }
  31726. }
  31727. // Actions (scene)
  31728. if (parsedData.actions) {
  31729. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  31730. }
  31731. // Finish
  31732. return true;
  31733. }
  31734. catch (err) {
  31735. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  31736. log = null;
  31737. throw err;
  31738. }
  31739. finally {
  31740. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  31741. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  31742. }
  31743. }
  31744. }
  31745. });
  31746. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  31747. })(BABYLON || (BABYLON = {}));
  31748. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  31749. var BABYLON;
  31750. (function (BABYLON) {
  31751. var SpriteManager = (function () {
  31752. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  31753. if (epsilon === void 0) { epsilon = 0.01; }
  31754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31755. this.name = name;
  31756. this.sprites = new Array();
  31757. this.renderingGroupId = 0;
  31758. this.layerMask = 0x0FFFFFFF;
  31759. this.fogEnabled = true;
  31760. this.isPickable = false;
  31761. /**
  31762. * An event triggered when the manager is disposed.
  31763. * @type {BABYLON.Observable}
  31764. */
  31765. this.onDisposeObservable = new BABYLON.Observable();
  31766. this._vertexBuffers = {};
  31767. this._capacity = capacity;
  31768. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  31769. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31770. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31771. if (cellSize.width && cellSize.height) {
  31772. this.cellWidth = cellSize.width;
  31773. this.cellHeight = cellSize.height;
  31774. }
  31775. else if (cellSize !== undefined) {
  31776. this.cellWidth = cellSize;
  31777. this.cellHeight = cellSize;
  31778. }
  31779. else {
  31780. return;
  31781. }
  31782. this._epsilon = epsilon;
  31783. this._scene = scene;
  31784. this._scene.spriteManagers.push(this);
  31785. var indices = [];
  31786. var index = 0;
  31787. for (var count = 0; count < capacity; count++) {
  31788. indices.push(index);
  31789. indices.push(index + 1);
  31790. indices.push(index + 2);
  31791. indices.push(index);
  31792. indices.push(index + 2);
  31793. indices.push(index + 3);
  31794. index += 4;
  31795. }
  31796. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  31797. // VBO
  31798. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  31799. this._vertexData = new Float32Array(capacity * 16 * 4);
  31800. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  31801. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  31802. var options = this._buffer.createVertexBuffer("options", 4, 4);
  31803. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  31804. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  31805. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  31806. this._vertexBuffers["options"] = options;
  31807. this._vertexBuffers["cellInfo"] = cellInfo;
  31808. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  31809. // Effects
  31810. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  31811. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  31812. }
  31813. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  31814. set: function (callback) {
  31815. if (this._onDisposeObserver) {
  31816. this.onDisposeObservable.remove(this._onDisposeObserver);
  31817. }
  31818. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31819. },
  31820. enumerable: true,
  31821. configurable: true
  31822. });
  31823. Object.defineProperty(SpriteManager.prototype, "texture", {
  31824. get: function () {
  31825. return this._spriteTexture;
  31826. },
  31827. set: function (value) {
  31828. this._spriteTexture = value;
  31829. },
  31830. enumerable: true,
  31831. configurable: true
  31832. });
  31833. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  31834. var arrayOffset = index * 16;
  31835. if (offsetX === 0)
  31836. offsetX = this._epsilon;
  31837. else if (offsetX === 1)
  31838. offsetX = 1 - this._epsilon;
  31839. if (offsetY === 0)
  31840. offsetY = this._epsilon;
  31841. else if (offsetY === 1)
  31842. offsetY = 1 - this._epsilon;
  31843. this._vertexData[arrayOffset] = sprite.position.x;
  31844. this._vertexData[arrayOffset + 1] = sprite.position.y;
  31845. this._vertexData[arrayOffset + 2] = sprite.position.z;
  31846. this._vertexData[arrayOffset + 3] = sprite.angle;
  31847. this._vertexData[arrayOffset + 4] = sprite.width;
  31848. this._vertexData[arrayOffset + 5] = sprite.height;
  31849. this._vertexData[arrayOffset + 6] = offsetX;
  31850. this._vertexData[arrayOffset + 7] = offsetY;
  31851. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  31852. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  31853. var offset = (sprite.cellIndex / rowSize) >> 0;
  31854. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  31855. this._vertexData[arrayOffset + 11] = offset;
  31856. // Color
  31857. this._vertexData[arrayOffset + 12] = sprite.color.r;
  31858. this._vertexData[arrayOffset + 13] = sprite.color.g;
  31859. this._vertexData[arrayOffset + 14] = sprite.color.b;
  31860. this._vertexData[arrayOffset + 15] = sprite.color.a;
  31861. };
  31862. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  31863. var count = Math.min(this._capacity, this.sprites.length);
  31864. var min = BABYLON.Vector3.Zero();
  31865. var max = BABYLON.Vector3.Zero();
  31866. var distance = Number.MAX_VALUE;
  31867. var currentSprite;
  31868. var cameraSpacePosition = BABYLON.Vector3.Zero();
  31869. var cameraView = camera.getViewMatrix();
  31870. for (var index = 0; index < count; index++) {
  31871. var sprite = this.sprites[index];
  31872. if (!sprite) {
  31873. continue;
  31874. }
  31875. if (predicate) {
  31876. if (!predicate(sprite)) {
  31877. continue;
  31878. }
  31879. }
  31880. else if (!sprite.isPickable) {
  31881. continue;
  31882. }
  31883. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  31884. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  31885. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  31886. if (ray.intersectsBoxMinMax(min, max)) {
  31887. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  31888. if (distance > currentDistance) {
  31889. distance = currentDistance;
  31890. currentSprite = sprite;
  31891. if (fastCheck) {
  31892. break;
  31893. }
  31894. }
  31895. }
  31896. }
  31897. if (currentSprite) {
  31898. var result = new BABYLON.PickingInfo();
  31899. result.hit = true;
  31900. result.pickedSprite = currentSprite;
  31901. result.distance = distance;
  31902. return result;
  31903. }
  31904. return null;
  31905. };
  31906. SpriteManager.prototype.render = function () {
  31907. // Check
  31908. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  31909. return;
  31910. var engine = this._scene.getEngine();
  31911. var baseSize = this._spriteTexture.getBaseSize();
  31912. // Sprites
  31913. var deltaTime = engine.getDeltaTime();
  31914. var max = Math.min(this._capacity, this.sprites.length);
  31915. var rowSize = baseSize.width / this.cellWidth;
  31916. var offset = 0;
  31917. for (var index = 0; index < max; index++) {
  31918. var sprite = this.sprites[index];
  31919. if (!sprite) {
  31920. continue;
  31921. }
  31922. sprite._animate(deltaTime);
  31923. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  31924. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  31925. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  31926. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  31927. }
  31928. this._buffer.update(this._vertexData);
  31929. // Render
  31930. var effect = this._effectBase;
  31931. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31932. effect = this._effectFog;
  31933. }
  31934. engine.enableEffect(effect);
  31935. var viewMatrix = this._scene.getViewMatrix();
  31936. effect.setTexture("diffuseSampler", this._spriteTexture);
  31937. effect.setMatrix("view", viewMatrix);
  31938. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  31939. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  31940. // Fog
  31941. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  31942. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  31943. effect.setColor3("vFogColor", this._scene.fogColor);
  31944. }
  31945. // VBOs
  31946. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31947. // Draw order
  31948. engine.setDepthFunctionToLessOrEqual();
  31949. effect.setBool("alphaTest", true);
  31950. engine.setColorWrite(false);
  31951. engine.draw(true, 0, max * 6);
  31952. engine.setColorWrite(true);
  31953. effect.setBool("alphaTest", false);
  31954. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31955. engine.draw(true, 0, max * 6);
  31956. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31957. };
  31958. SpriteManager.prototype.dispose = function () {
  31959. if (this._buffer) {
  31960. this._buffer.dispose();
  31961. this._buffer = null;
  31962. }
  31963. if (this._indexBuffer) {
  31964. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31965. this._indexBuffer = null;
  31966. }
  31967. if (this._spriteTexture) {
  31968. this._spriteTexture.dispose();
  31969. this._spriteTexture = null;
  31970. }
  31971. // Remove from scene
  31972. var index = this._scene.spriteManagers.indexOf(this);
  31973. this._scene.spriteManagers.splice(index, 1);
  31974. // Callback
  31975. this.onDisposeObservable.notifyObservers(this);
  31976. this.onDisposeObservable.clear();
  31977. };
  31978. return SpriteManager;
  31979. }());
  31980. BABYLON.SpriteManager = SpriteManager;
  31981. })(BABYLON || (BABYLON = {}));
  31982. //# sourceMappingURL=babylon.spriteManager.js.map
  31983. var BABYLON;
  31984. (function (BABYLON) {
  31985. var Sprite = (function () {
  31986. function Sprite(name, manager) {
  31987. this.name = name;
  31988. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  31989. this.width = 1.0;
  31990. this.height = 1.0;
  31991. this.angle = 0;
  31992. this.cellIndex = 0;
  31993. this.invertU = 0;
  31994. this.invertV = 0;
  31995. this.animations = new Array();
  31996. this.isPickable = false;
  31997. this._animationStarted = false;
  31998. this._loopAnimation = false;
  31999. this._fromIndex = 0;
  32000. this._toIndex = 0;
  32001. this._delay = 0;
  32002. this._direction = 1;
  32003. this._frameCount = 0;
  32004. this._time = 0;
  32005. this._manager = manager;
  32006. this._manager.sprites.push(this);
  32007. this.position = BABYLON.Vector3.Zero();
  32008. }
  32009. Object.defineProperty(Sprite.prototype, "size", {
  32010. get: function () {
  32011. return this.width;
  32012. },
  32013. set: function (value) {
  32014. this.width = value;
  32015. this.height = value;
  32016. },
  32017. enumerable: true,
  32018. configurable: true
  32019. });
  32020. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  32021. this._fromIndex = from;
  32022. this._toIndex = to;
  32023. this._loopAnimation = loop;
  32024. this._delay = delay;
  32025. this._animationStarted = true;
  32026. this._direction = from < to ? 1 : -1;
  32027. this.cellIndex = from;
  32028. this._time = 0;
  32029. this._onAnimationEnd = onAnimationEnd;
  32030. };
  32031. Sprite.prototype.stopAnimation = function () {
  32032. this._animationStarted = false;
  32033. };
  32034. Sprite.prototype._animate = function (deltaTime) {
  32035. if (!this._animationStarted)
  32036. return;
  32037. this._time += deltaTime;
  32038. if (this._time > this._delay) {
  32039. this._time = this._time % this._delay;
  32040. this.cellIndex += this._direction;
  32041. if (this.cellIndex === this._toIndex) {
  32042. if (this._loopAnimation) {
  32043. this.cellIndex = this._fromIndex;
  32044. }
  32045. else {
  32046. this._animationStarted = false;
  32047. if (this._onAnimationEnd) {
  32048. this._onAnimationEnd();
  32049. }
  32050. if (this.disposeWhenFinishedAnimating) {
  32051. this.dispose();
  32052. }
  32053. }
  32054. }
  32055. }
  32056. };
  32057. Sprite.prototype.dispose = function () {
  32058. for (var i = 0; i < this._manager.sprites.length; i++) {
  32059. if (this._manager.sprites[i] == this) {
  32060. this._manager.sprites.splice(i, 1);
  32061. }
  32062. }
  32063. };
  32064. return Sprite;
  32065. }());
  32066. BABYLON.Sprite = Sprite;
  32067. })(BABYLON || (BABYLON = {}));
  32068. //# sourceMappingURL=babylon.sprite.js.map
  32069. var BABYLON;
  32070. (function (BABYLON) {
  32071. var Layer = (function () {
  32072. function Layer(name, imgUrl, scene, isBackground, color) {
  32073. this.name = name;
  32074. this.scale = new BABYLON.Vector2(1, 1);
  32075. this.offset = new BABYLON.Vector2(0, 0);
  32076. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  32077. this._vertexBuffers = {};
  32078. // Events
  32079. /**
  32080. * An event triggered when the layer is disposed.
  32081. * @type {BABYLON.Observable}
  32082. */
  32083. this.onDisposeObservable = new BABYLON.Observable();
  32084. /**
  32085. * An event triggered before rendering the scene
  32086. * @type {BABYLON.Observable}
  32087. */
  32088. this.onBeforeRenderObservable = new BABYLON.Observable();
  32089. /**
  32090. * An event triggered after rendering the scene
  32091. * @type {BABYLON.Observable}
  32092. */
  32093. this.onAfterRenderObservable = new BABYLON.Observable();
  32094. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  32095. this.isBackground = isBackground === undefined ? true : isBackground;
  32096. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  32097. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32098. this._scene.layers.push(this);
  32099. var engine = scene.getEngine();
  32100. // VBO
  32101. var vertices = [];
  32102. vertices.push(1, 1);
  32103. vertices.push(-1, 1);
  32104. vertices.push(-1, -1);
  32105. vertices.push(1, -1);
  32106. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32107. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  32108. // Indices
  32109. var indices = [];
  32110. indices.push(0);
  32111. indices.push(1);
  32112. indices.push(2);
  32113. indices.push(0);
  32114. indices.push(2);
  32115. indices.push(3);
  32116. this._indexBuffer = engine.createIndexBuffer(indices);
  32117. // Effects
  32118. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  32119. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  32120. }
  32121. Object.defineProperty(Layer.prototype, "onDispose", {
  32122. set: function (callback) {
  32123. if (this._onDisposeObserver) {
  32124. this.onDisposeObservable.remove(this._onDisposeObserver);
  32125. }
  32126. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32127. },
  32128. enumerable: true,
  32129. configurable: true
  32130. });
  32131. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  32132. set: function (callback) {
  32133. if (this._onBeforeRenderObserver) {
  32134. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32135. }
  32136. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32137. },
  32138. enumerable: true,
  32139. configurable: true
  32140. });
  32141. Object.defineProperty(Layer.prototype, "onAfterRender", {
  32142. set: function (callback) {
  32143. if (this._onAfterRenderObserver) {
  32144. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32145. }
  32146. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32147. },
  32148. enumerable: true,
  32149. configurable: true
  32150. });
  32151. Layer.prototype.render = function () {
  32152. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  32153. // Check
  32154. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  32155. return;
  32156. var engine = this._scene.getEngine();
  32157. this.onBeforeRenderObservable.notifyObservers(this);
  32158. // Render
  32159. engine.enableEffect(currentEffect);
  32160. engine.setState(false);
  32161. // Texture
  32162. currentEffect.setTexture("textureSampler", this.texture);
  32163. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  32164. // Color
  32165. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  32166. // Scale / offset
  32167. currentEffect.setVector2("offset", this.offset);
  32168. currentEffect.setVector2("scale", this.scale);
  32169. // VBOs
  32170. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  32171. // Draw order
  32172. if (!this.alphaTest) {
  32173. engine.setAlphaMode(this.alphaBlendingMode);
  32174. engine.draw(true, 0, 6);
  32175. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32176. }
  32177. else {
  32178. engine.draw(true, 0, 6);
  32179. }
  32180. this.onAfterRenderObservable.notifyObservers(this);
  32181. };
  32182. Layer.prototype.dispose = function () {
  32183. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32184. if (vertexBuffer) {
  32185. vertexBuffer.dispose();
  32186. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32187. }
  32188. if (this._indexBuffer) {
  32189. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32190. this._indexBuffer = null;
  32191. }
  32192. if (this.texture) {
  32193. this.texture.dispose();
  32194. this.texture = null;
  32195. }
  32196. // Remove from scene
  32197. var index = this._scene.layers.indexOf(this);
  32198. this._scene.layers.splice(index, 1);
  32199. // Callback
  32200. this.onDisposeObservable.notifyObservers(this);
  32201. this.onDisposeObservable.clear();
  32202. this.onAfterRenderObservable.clear();
  32203. this.onBeforeRenderObservable.clear();
  32204. };
  32205. return Layer;
  32206. }());
  32207. BABYLON.Layer = Layer;
  32208. })(BABYLON || (BABYLON = {}));
  32209. //# sourceMappingURL=babylon.layer.js.map
  32210. var BABYLON;
  32211. (function (BABYLON) {
  32212. var Particle = (function () {
  32213. function Particle() {
  32214. this.position = BABYLON.Vector3.Zero();
  32215. this.direction = BABYLON.Vector3.Zero();
  32216. this.color = new BABYLON.Color4(0, 0, 0, 0);
  32217. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  32218. this.lifeTime = 1.0;
  32219. this.age = 0;
  32220. this.size = 0;
  32221. this.angle = 0;
  32222. this.angularSpeed = 0;
  32223. }
  32224. Particle.prototype.copyTo = function (other) {
  32225. other.position.copyFrom(this.position);
  32226. other.direction.copyFrom(this.direction);
  32227. other.color.copyFrom(this.color);
  32228. other.colorStep.copyFrom(this.colorStep);
  32229. other.lifeTime = this.lifeTime;
  32230. other.age = this.age;
  32231. other.size = this.size;
  32232. other.angle = this.angle;
  32233. other.angularSpeed = this.angularSpeed;
  32234. };
  32235. return Particle;
  32236. }());
  32237. BABYLON.Particle = Particle;
  32238. })(BABYLON || (BABYLON = {}));
  32239. //# sourceMappingURL=babylon.particle.js.map
  32240. var BABYLON;
  32241. (function (BABYLON) {
  32242. var randomNumber = function (min, max) {
  32243. if (min === max) {
  32244. return (min);
  32245. }
  32246. var random = Math.random();
  32247. return ((random * (max - min)) + min);
  32248. };
  32249. var ParticleSystem = (function () {
  32250. function ParticleSystem(name, capacity, scene, customEffect) {
  32251. var _this = this;
  32252. this.name = name;
  32253. // Members
  32254. this.animations = [];
  32255. this.renderingGroupId = 0;
  32256. this.emitter = null;
  32257. this.emitRate = 10;
  32258. this.manualEmitCount = -1;
  32259. this.updateSpeed = 0.01;
  32260. this.targetStopDuration = 0;
  32261. this.disposeOnStop = false;
  32262. this.minEmitPower = 1;
  32263. this.maxEmitPower = 1;
  32264. this.minLifeTime = 1;
  32265. this.maxLifeTime = 1;
  32266. this.minSize = 1;
  32267. this.maxSize = 1;
  32268. this.minAngularSpeed = 0;
  32269. this.maxAngularSpeed = 0;
  32270. this.layerMask = 0x0FFFFFFF;
  32271. this.customShader = null;
  32272. this.preventAutoStart = false;
  32273. /**
  32274. * An event triggered when the system is disposed.
  32275. * @type {BABYLON.Observable}
  32276. */
  32277. this.onDisposeObservable = new BABYLON.Observable();
  32278. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  32279. this.forceDepthWrite = false;
  32280. this.gravity = BABYLON.Vector3.Zero();
  32281. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  32282. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  32283. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  32284. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  32285. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32286. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32287. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  32288. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  32289. this.particles = new Array();
  32290. this._stockParticles = new Array();
  32291. this._newPartsExcess = 0;
  32292. this._vertexBuffers = {};
  32293. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  32294. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  32295. this._scaledDirection = BABYLON.Vector3.Zero();
  32296. this._scaledGravity = BABYLON.Vector3.Zero();
  32297. this._currentRenderId = -1;
  32298. this._started = false;
  32299. this._stopped = false;
  32300. this._actualFrame = 0;
  32301. this.id = name;
  32302. this._capacity = capacity;
  32303. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32304. this._customEffect = customEffect;
  32305. scene.particleSystems.push(this);
  32306. var indices = [];
  32307. var index = 0;
  32308. for (var count = 0; count < capacity; count++) {
  32309. indices.push(index);
  32310. indices.push(index + 1);
  32311. indices.push(index + 2);
  32312. indices.push(index);
  32313. indices.push(index + 2);
  32314. indices.push(index + 3);
  32315. index += 4;
  32316. }
  32317. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  32318. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  32319. this._vertexData = new Float32Array(capacity * 11 * 4);
  32320. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  32321. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  32322. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  32323. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  32324. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  32325. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  32326. this._vertexBuffers["options"] = options;
  32327. // Default behaviors
  32328. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  32329. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  32330. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  32331. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  32332. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  32333. };
  32334. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  32335. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  32336. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  32337. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  32338. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  32339. };
  32340. this.updateFunction = function (particles) {
  32341. for (var index = 0; index < particles.length; index++) {
  32342. var particle = particles[index];
  32343. particle.age += _this._scaledUpdateSpeed;
  32344. if (particle.age >= particle.lifeTime) {
  32345. _this.recycleParticle(particle);
  32346. index--;
  32347. continue;
  32348. }
  32349. else {
  32350. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  32351. particle.color.addInPlace(_this._scaledColorStep);
  32352. if (particle.color.a < 0)
  32353. particle.color.a = 0;
  32354. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  32355. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  32356. particle.position.addInPlace(_this._scaledDirection);
  32357. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  32358. particle.direction.addInPlace(_this._scaledGravity);
  32359. }
  32360. }
  32361. };
  32362. }
  32363. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  32364. set: function (callback) {
  32365. if (this._onDisposeObserver) {
  32366. this.onDisposeObservable.remove(this._onDisposeObserver);
  32367. }
  32368. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32369. },
  32370. enumerable: true,
  32371. configurable: true
  32372. });
  32373. ParticleSystem.prototype.recycleParticle = function (particle) {
  32374. var lastParticle = this.particles.pop();
  32375. if (lastParticle !== particle) {
  32376. lastParticle.copyTo(particle);
  32377. this._stockParticles.push(lastParticle);
  32378. }
  32379. };
  32380. ParticleSystem.prototype.getCapacity = function () {
  32381. return this._capacity;
  32382. };
  32383. ParticleSystem.prototype.isAlive = function () {
  32384. return this._alive;
  32385. };
  32386. ParticleSystem.prototype.isStarted = function () {
  32387. return this._started;
  32388. };
  32389. ParticleSystem.prototype.start = function () {
  32390. this._started = true;
  32391. this._stopped = false;
  32392. this._actualFrame = 0;
  32393. };
  32394. ParticleSystem.prototype.stop = function () {
  32395. this._stopped = true;
  32396. };
  32397. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  32398. var offset = index * 11;
  32399. this._vertexData[offset] = particle.position.x;
  32400. this._vertexData[offset + 1] = particle.position.y;
  32401. this._vertexData[offset + 2] = particle.position.z;
  32402. this._vertexData[offset + 3] = particle.color.r;
  32403. this._vertexData[offset + 4] = particle.color.g;
  32404. this._vertexData[offset + 5] = particle.color.b;
  32405. this._vertexData[offset + 6] = particle.color.a;
  32406. this._vertexData[offset + 7] = particle.angle;
  32407. this._vertexData[offset + 8] = particle.size;
  32408. this._vertexData[offset + 9] = offsetX;
  32409. this._vertexData[offset + 10] = offsetY;
  32410. };
  32411. ParticleSystem.prototype._update = function (newParticles) {
  32412. // Update current
  32413. this._alive = this.particles.length > 0;
  32414. this.updateFunction(this.particles);
  32415. // Add new ones
  32416. var worldMatrix;
  32417. if (this.emitter.position) {
  32418. worldMatrix = this.emitter.getWorldMatrix();
  32419. }
  32420. else {
  32421. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  32422. }
  32423. var particle;
  32424. for (var index = 0; index < newParticles; index++) {
  32425. if (this.particles.length === this._capacity) {
  32426. break;
  32427. }
  32428. if (this._stockParticles.length !== 0) {
  32429. particle = this._stockParticles.pop();
  32430. particle.age = 0;
  32431. }
  32432. else {
  32433. particle = new BABYLON.Particle();
  32434. }
  32435. this.particles.push(particle);
  32436. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  32437. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  32438. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  32439. particle.size = randomNumber(this.minSize, this.maxSize);
  32440. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  32441. this.startPositionFunction(worldMatrix, particle.position, particle);
  32442. var step = randomNumber(0, 1.0);
  32443. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  32444. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  32445. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  32446. }
  32447. };
  32448. ParticleSystem.prototype._getEffect = function () {
  32449. if (this._customEffect) {
  32450. return this._customEffect;
  32451. }
  32452. ;
  32453. var defines = [];
  32454. if (this._scene.clipPlane) {
  32455. defines.push("#define CLIPPLANE");
  32456. }
  32457. // Effect
  32458. var join = defines.join("\n");
  32459. if (this._cachedDefines !== join) {
  32460. this._cachedDefines = join;
  32461. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  32462. }
  32463. return this._effect;
  32464. };
  32465. ParticleSystem.prototype.animate = function () {
  32466. if (!this._started)
  32467. return;
  32468. var effect = this._getEffect();
  32469. // Check
  32470. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  32471. return;
  32472. if (this._currentRenderId === this._scene.getRenderId()) {
  32473. return;
  32474. }
  32475. this._currentRenderId = this._scene.getRenderId();
  32476. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  32477. // determine the number of particles we need to create
  32478. var newParticles;
  32479. if (this.manualEmitCount > -1) {
  32480. newParticles = this.manualEmitCount;
  32481. this._newPartsExcess = 0;
  32482. this.manualEmitCount = 0;
  32483. }
  32484. else {
  32485. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  32486. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  32487. }
  32488. if (this._newPartsExcess > 1.0) {
  32489. newParticles += this._newPartsExcess >> 0;
  32490. this._newPartsExcess -= this._newPartsExcess >> 0;
  32491. }
  32492. this._alive = false;
  32493. if (!this._stopped) {
  32494. this._actualFrame += this._scaledUpdateSpeed;
  32495. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  32496. this.stop();
  32497. }
  32498. else {
  32499. newParticles = 0;
  32500. }
  32501. this._update(newParticles);
  32502. // Stopped?
  32503. if (this._stopped) {
  32504. if (!this._alive) {
  32505. this._started = false;
  32506. if (this.disposeOnStop) {
  32507. this._scene._toBeDisposed.push(this);
  32508. }
  32509. }
  32510. }
  32511. // Update VBO
  32512. var offset = 0;
  32513. for (var index = 0; index < this.particles.length; index++) {
  32514. var particle = this.particles[index];
  32515. this._appendParticleVertex(offset++, particle, 0, 0);
  32516. this._appendParticleVertex(offset++, particle, 1, 0);
  32517. this._appendParticleVertex(offset++, particle, 1, 1);
  32518. this._appendParticleVertex(offset++, particle, 0, 1);
  32519. }
  32520. this._vertexBuffer.update(this._vertexData);
  32521. };
  32522. ParticleSystem.prototype.render = function () {
  32523. var effect = this._getEffect();
  32524. // Check
  32525. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  32526. return 0;
  32527. var engine = this._scene.getEngine();
  32528. // Render
  32529. engine.enableEffect(effect);
  32530. engine.setState(false);
  32531. var viewMatrix = this._scene.getViewMatrix();
  32532. effect.setTexture("diffuseSampler", this.particleTexture);
  32533. effect.setMatrix("view", viewMatrix);
  32534. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  32535. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  32536. if (this._scene.clipPlane) {
  32537. var clipPlane = this._scene.clipPlane;
  32538. var invView = viewMatrix.clone();
  32539. invView.invert();
  32540. effect.setMatrix("invView", invView);
  32541. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  32542. }
  32543. // VBOs
  32544. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32545. // Draw order
  32546. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  32547. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  32548. }
  32549. else {
  32550. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32551. }
  32552. if (this.forceDepthWrite) {
  32553. engine.setDepthWrite(true);
  32554. }
  32555. engine.draw(true, 0, this.particles.length * 6);
  32556. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32557. return this.particles.length;
  32558. };
  32559. ParticleSystem.prototype.dispose = function () {
  32560. if (this._vertexBuffer) {
  32561. this._vertexBuffer.dispose();
  32562. this._vertexBuffer = null;
  32563. }
  32564. if (this._indexBuffer) {
  32565. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32566. this._indexBuffer = null;
  32567. }
  32568. if (this.particleTexture) {
  32569. this.particleTexture.dispose();
  32570. this.particleTexture = null;
  32571. }
  32572. // Remove from scene
  32573. var index = this._scene.particleSystems.indexOf(this);
  32574. this._scene.particleSystems.splice(index, 1);
  32575. // Callback
  32576. this.onDisposeObservable.notifyObservers(this);
  32577. this.onDisposeObservable.clear();
  32578. };
  32579. // Clone
  32580. ParticleSystem.prototype.clone = function (name, newEmitter) {
  32581. var custom = null;
  32582. var program = null;
  32583. if (this.customShader != null) {
  32584. program = this.customShader;
  32585. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32586. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32587. }
  32588. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  32589. result.customShader = program;
  32590. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  32591. if (newEmitter === undefined) {
  32592. newEmitter = this.emitter;
  32593. }
  32594. result.emitter = newEmitter;
  32595. if (this.particleTexture) {
  32596. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  32597. }
  32598. if (!this.preventAutoStart) {
  32599. result.start();
  32600. }
  32601. return result;
  32602. };
  32603. ParticleSystem.prototype.serialize = function () {
  32604. var serializationObject = {};
  32605. serializationObject.name = this.name;
  32606. serializationObject.id = this.id;
  32607. // Emitter
  32608. if (this.emitter.position) {
  32609. serializationObject.emitterId = this.emitter.id;
  32610. }
  32611. else {
  32612. serializationObject.emitter = this.emitter.asArray();
  32613. }
  32614. serializationObject.capacity = this.getCapacity();
  32615. if (this.particleTexture) {
  32616. serializationObject.textureName = this.particleTexture.name;
  32617. }
  32618. // Animations
  32619. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32620. // Particle system
  32621. serializationObject.minAngularSpeed = this.minAngularSpeed;
  32622. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  32623. serializationObject.minSize = this.minSize;
  32624. serializationObject.maxSize = this.maxSize;
  32625. serializationObject.minEmitPower = this.minEmitPower;
  32626. serializationObject.maxEmitPower = this.maxEmitPower;
  32627. serializationObject.minLifeTime = this.minLifeTime;
  32628. serializationObject.maxLifeTime = this.maxLifeTime;
  32629. serializationObject.emitRate = this.emitRate;
  32630. serializationObject.minEmitBox = this.minEmitBox.asArray();
  32631. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  32632. serializationObject.gravity = this.gravity.asArray();
  32633. serializationObject.direction1 = this.direction1.asArray();
  32634. serializationObject.direction2 = this.direction2.asArray();
  32635. serializationObject.color1 = this.color1.asArray();
  32636. serializationObject.color2 = this.color2.asArray();
  32637. serializationObject.colorDead = this.colorDead.asArray();
  32638. serializationObject.updateSpeed = this.updateSpeed;
  32639. serializationObject.targetStopDuration = this.targetStopDuration;
  32640. serializationObject.textureMask = this.textureMask.asArray();
  32641. serializationObject.blendMode = this.blendMode;
  32642. serializationObject.customShader = this.customShader;
  32643. serializationObject.preventAutoStart = this.preventAutoStart;
  32644. return serializationObject;
  32645. };
  32646. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  32647. var name = parsedParticleSystem.name;
  32648. var custom = null;
  32649. var program = null;
  32650. if (parsedParticleSystem.customShader) {
  32651. program = parsedParticleSystem.customShader;
  32652. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  32653. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  32654. }
  32655. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  32656. particleSystem.customShader = program;
  32657. if (parsedParticleSystem.id) {
  32658. particleSystem.id = parsedParticleSystem.id;
  32659. }
  32660. // Auto start
  32661. if (parsedParticleSystem.preventAutoStart) {
  32662. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  32663. }
  32664. // Texture
  32665. if (parsedParticleSystem.textureName) {
  32666. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  32667. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  32668. }
  32669. // Emitter
  32670. if (parsedParticleSystem.emitterId) {
  32671. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  32672. }
  32673. else {
  32674. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  32675. }
  32676. // Animations
  32677. if (parsedParticleSystem.animations) {
  32678. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  32679. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  32680. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32681. }
  32682. }
  32683. if (parsedParticleSystem.autoAnimate) {
  32684. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  32685. }
  32686. // Particle system
  32687. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  32688. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  32689. particleSystem.minSize = parsedParticleSystem.minSize;
  32690. particleSystem.maxSize = parsedParticleSystem.maxSize;
  32691. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  32692. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  32693. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  32694. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  32695. particleSystem.emitRate = parsedParticleSystem.emitRate;
  32696. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  32697. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  32698. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  32699. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  32700. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  32701. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  32702. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  32703. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  32704. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  32705. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  32706. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  32707. particleSystem.blendMode = parsedParticleSystem.blendMode;
  32708. if (!particleSystem.preventAutoStart) {
  32709. particleSystem.start();
  32710. }
  32711. return particleSystem;
  32712. };
  32713. return ParticleSystem;
  32714. }());
  32715. // Statics
  32716. ParticleSystem.BLENDMODE_ONEONE = 0;
  32717. ParticleSystem.BLENDMODE_STANDARD = 1;
  32718. BABYLON.ParticleSystem = ParticleSystem;
  32719. })(BABYLON || (BABYLON = {}));
  32720. //# sourceMappingURL=babylon.particleSystem.js.map
  32721. var BABYLON;
  32722. (function (BABYLON) {
  32723. var AnimationRange = (function () {
  32724. function AnimationRange(name, from, to) {
  32725. this.name = name;
  32726. this.from = from;
  32727. this.to = to;
  32728. }
  32729. AnimationRange.prototype.clone = function () {
  32730. return new AnimationRange(this.name, this.from, this.to);
  32731. };
  32732. return AnimationRange;
  32733. }());
  32734. BABYLON.AnimationRange = AnimationRange;
  32735. /**
  32736. * Composed of a frame, and an action function
  32737. */
  32738. var AnimationEvent = (function () {
  32739. function AnimationEvent(frame, action, onlyOnce) {
  32740. this.frame = frame;
  32741. this.action = action;
  32742. this.onlyOnce = onlyOnce;
  32743. this.isDone = false;
  32744. }
  32745. return AnimationEvent;
  32746. }());
  32747. BABYLON.AnimationEvent = AnimationEvent;
  32748. var PathCursor = (function () {
  32749. function PathCursor(path) {
  32750. this.path = path;
  32751. this._onchange = new Array();
  32752. this.value = 0;
  32753. this.animations = new Array();
  32754. }
  32755. PathCursor.prototype.getPoint = function () {
  32756. var point = this.path.getPointAtLengthPosition(this.value);
  32757. return new BABYLON.Vector3(point.x, 0, point.y);
  32758. };
  32759. PathCursor.prototype.moveAhead = function (step) {
  32760. if (step === void 0) { step = 0.002; }
  32761. this.move(step);
  32762. return this;
  32763. };
  32764. PathCursor.prototype.moveBack = function (step) {
  32765. if (step === void 0) { step = 0.002; }
  32766. this.move(-step);
  32767. return this;
  32768. };
  32769. PathCursor.prototype.move = function (step) {
  32770. if (Math.abs(step) > 1) {
  32771. throw "step size should be less than 1.";
  32772. }
  32773. this.value += step;
  32774. this.ensureLimits();
  32775. this.raiseOnChange();
  32776. return this;
  32777. };
  32778. PathCursor.prototype.ensureLimits = function () {
  32779. while (this.value > 1) {
  32780. this.value -= 1;
  32781. }
  32782. while (this.value < 0) {
  32783. this.value += 1;
  32784. }
  32785. return this;
  32786. };
  32787. // used by animation engine
  32788. PathCursor.prototype.markAsDirty = function (propertyName) {
  32789. this.ensureLimits();
  32790. this.raiseOnChange();
  32791. return this;
  32792. };
  32793. PathCursor.prototype.raiseOnChange = function () {
  32794. var _this = this;
  32795. this._onchange.forEach(function (f) { return f(_this); });
  32796. return this;
  32797. };
  32798. PathCursor.prototype.onchange = function (f) {
  32799. this._onchange.push(f);
  32800. return this;
  32801. };
  32802. return PathCursor;
  32803. }());
  32804. BABYLON.PathCursor = PathCursor;
  32805. var Animation = (function () {
  32806. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32807. this.name = name;
  32808. this.targetProperty = targetProperty;
  32809. this.framePerSecond = framePerSecond;
  32810. this.dataType = dataType;
  32811. this.loopMode = loopMode;
  32812. this.enableBlending = enableBlending;
  32813. this._offsetsCache = {};
  32814. this._highLimitsCache = {};
  32815. this._stopped = false;
  32816. this._blendingFactor = 0;
  32817. // The set of event that will be linked to this animation
  32818. this._events = new Array();
  32819. this.allowMatricesInterpolation = false;
  32820. this.blendingSpeed = 0.01;
  32821. this._ranges = {};
  32822. this.targetPropertyPath = targetProperty.split(".");
  32823. this.dataType = dataType;
  32824. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32825. }
  32826. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32827. var dataType = undefined;
  32828. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32829. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32830. }
  32831. else if (from instanceof BABYLON.Quaternion) {
  32832. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32833. }
  32834. else if (from instanceof BABYLON.Vector3) {
  32835. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32836. }
  32837. else if (from instanceof BABYLON.Vector2) {
  32838. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32839. }
  32840. else if (from instanceof BABYLON.Color3) {
  32841. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32842. }
  32843. else if (from instanceof BABYLON.Size) {
  32844. dataType = Animation.ANIMATIONTYPE_SIZE;
  32845. }
  32846. if (dataType == undefined) {
  32847. return null;
  32848. }
  32849. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32850. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32851. animation.setKeys(keys);
  32852. if (easingFunction !== undefined) {
  32853. animation.setEasingFunction(easingFunction);
  32854. }
  32855. return animation;
  32856. };
  32857. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32858. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32859. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32860. };
  32861. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32862. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32863. node.animations.push(animation);
  32864. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32865. };
  32866. // Methods
  32867. /**
  32868. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32869. */
  32870. Animation.prototype.toString = function (fullDetails) {
  32871. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32872. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32873. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32874. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32875. if (fullDetails) {
  32876. ret += ", Ranges: {";
  32877. var first = true;
  32878. for (var name in this._ranges) {
  32879. if (first) {
  32880. ret += ", ";
  32881. first = false;
  32882. }
  32883. ret += name;
  32884. }
  32885. ret += "}";
  32886. }
  32887. return ret;
  32888. };
  32889. /**
  32890. * Add an event to this animation.
  32891. */
  32892. Animation.prototype.addEvent = function (event) {
  32893. this._events.push(event);
  32894. };
  32895. /**
  32896. * Remove all events found at the given frame
  32897. * @param frame
  32898. */
  32899. Animation.prototype.removeEvents = function (frame) {
  32900. for (var index = 0; index < this._events.length; index++) {
  32901. if (this._events[index].frame === frame) {
  32902. this._events.splice(index, 1);
  32903. index--;
  32904. }
  32905. }
  32906. };
  32907. Animation.prototype.createRange = function (name, from, to) {
  32908. // check name not already in use; could happen for bones after serialized
  32909. if (!this._ranges[name]) {
  32910. this._ranges[name] = new AnimationRange(name, from, to);
  32911. }
  32912. };
  32913. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32914. if (deleteFrames === void 0) { deleteFrames = true; }
  32915. if (this._ranges[name]) {
  32916. if (deleteFrames) {
  32917. var from = this._ranges[name].from;
  32918. var to = this._ranges[name].to;
  32919. // this loop MUST go high to low for multiple splices to work
  32920. for (var key = this._keys.length - 1; key >= 0; key--) {
  32921. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32922. this._keys.splice(key, 1);
  32923. }
  32924. }
  32925. }
  32926. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32927. }
  32928. };
  32929. Animation.prototype.getRange = function (name) {
  32930. return this._ranges[name];
  32931. };
  32932. Animation.prototype.reset = function () {
  32933. this._offsetsCache = {};
  32934. this._highLimitsCache = {};
  32935. this.currentFrame = 0;
  32936. this._blendingFactor = 0;
  32937. this._originalBlendValue = null;
  32938. };
  32939. Animation.prototype.isStopped = function () {
  32940. return this._stopped;
  32941. };
  32942. Animation.prototype.getKeys = function () {
  32943. return this._keys;
  32944. };
  32945. Animation.prototype.getHighestFrame = function () {
  32946. var ret = 0;
  32947. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32948. if (ret < this._keys[key].frame) {
  32949. ret = this._keys[key].frame;
  32950. }
  32951. }
  32952. return ret;
  32953. };
  32954. Animation.prototype.getEasingFunction = function () {
  32955. return this._easingFunction;
  32956. };
  32957. Animation.prototype.setEasingFunction = function (easingFunction) {
  32958. this._easingFunction = easingFunction;
  32959. };
  32960. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32961. return startValue + (endValue - startValue) * gradient;
  32962. };
  32963. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32964. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32965. };
  32966. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32967. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32968. };
  32969. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32970. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32971. };
  32972. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32973. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32974. };
  32975. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32976. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32977. };
  32978. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32979. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32980. };
  32981. Animation.prototype.clone = function () {
  32982. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32983. clone.enableBlending = this.enableBlending;
  32984. clone.blendingSpeed = this.blendingSpeed;
  32985. if (this._keys) {
  32986. clone.setKeys(this._keys);
  32987. }
  32988. if (this._ranges) {
  32989. clone._ranges = {};
  32990. for (var name in this._ranges) {
  32991. clone._ranges[name] = this._ranges[name].clone();
  32992. }
  32993. }
  32994. return clone;
  32995. };
  32996. Animation.prototype.setKeys = function (values) {
  32997. this._keys = values.slice(0);
  32998. this._offsetsCache = {};
  32999. this._highLimitsCache = {};
  33000. };
  33001. Animation.prototype._getKeyValue = function (value) {
  33002. if (typeof value === "function") {
  33003. return value();
  33004. }
  33005. return value;
  33006. };
  33007. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  33008. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  33009. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  33010. }
  33011. this.currentFrame = currentFrame;
  33012. // Try to get a hash to find the right key
  33013. 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));
  33014. if (this._keys[startKey].frame >= currentFrame) {
  33015. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  33016. startKey--;
  33017. }
  33018. }
  33019. for (var key = startKey; key < this._keys.length; key++) {
  33020. if (this._keys[key + 1].frame >= currentFrame) {
  33021. var startValue = this._getKeyValue(this._keys[key].value);
  33022. var endValue = this._getKeyValue(this._keys[key + 1].value);
  33023. // gradient : percent of currentFrame between the frame inf and the frame sup
  33024. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  33025. // check for easingFunction and correction of gradient
  33026. if (this._easingFunction != null) {
  33027. gradient = this._easingFunction.ease(gradient);
  33028. }
  33029. switch (this.dataType) {
  33030. // Float
  33031. case Animation.ANIMATIONTYPE_FLOAT:
  33032. switch (loopMode) {
  33033. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33034. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33035. return this.floatInterpolateFunction(startValue, endValue, gradient);
  33036. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33037. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  33038. }
  33039. break;
  33040. // Quaternion
  33041. case Animation.ANIMATIONTYPE_QUATERNION:
  33042. var quaternion = null;
  33043. switch (loopMode) {
  33044. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33045. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33046. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  33047. break;
  33048. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33049. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33050. break;
  33051. }
  33052. return quaternion;
  33053. // Vector3
  33054. case Animation.ANIMATIONTYPE_VECTOR3:
  33055. switch (loopMode) {
  33056. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33057. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33058. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  33059. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33060. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33061. }
  33062. // Vector2
  33063. case Animation.ANIMATIONTYPE_VECTOR2:
  33064. switch (loopMode) {
  33065. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33066. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33067. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  33068. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33069. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33070. }
  33071. // Size
  33072. case Animation.ANIMATIONTYPE_SIZE:
  33073. switch (loopMode) {
  33074. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33075. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33076. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  33077. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33078. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33079. }
  33080. // Color3
  33081. case Animation.ANIMATIONTYPE_COLOR3:
  33082. switch (loopMode) {
  33083. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33084. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33085. return this.color3InterpolateFunction(startValue, endValue, gradient);
  33086. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33087. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  33088. }
  33089. // Matrix
  33090. case Animation.ANIMATIONTYPE_MATRIX:
  33091. switch (loopMode) {
  33092. case Animation.ANIMATIONLOOPMODE_CYCLE:
  33093. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  33094. if (this.allowMatricesInterpolation) {
  33095. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  33096. }
  33097. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  33098. return startValue;
  33099. }
  33100. default:
  33101. break;
  33102. }
  33103. break;
  33104. }
  33105. }
  33106. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  33107. };
  33108. Animation.prototype.setValue = function (currentValue, blend) {
  33109. if (blend === void 0) { blend = false; }
  33110. // Set value
  33111. var path;
  33112. var destination;
  33113. if (this.targetPropertyPath.length > 1) {
  33114. var property = this._target[this.targetPropertyPath[0]];
  33115. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  33116. property = property[this.targetPropertyPath[index]];
  33117. }
  33118. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  33119. destination = property;
  33120. }
  33121. else {
  33122. path = this.targetPropertyPath[0];
  33123. destination = this._target;
  33124. }
  33125. // Blending
  33126. if (this.enableBlending && this._blendingFactor <= 1.0) {
  33127. if (!this._originalBlendValue) {
  33128. if (destination[path].clone) {
  33129. this._originalBlendValue = destination[path].clone();
  33130. }
  33131. else {
  33132. this._originalBlendValue = destination[path];
  33133. }
  33134. }
  33135. if (this._originalBlendValue.prototype) {
  33136. if (this._originalBlendValue.prototype.Lerp) {
  33137. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  33138. }
  33139. else {
  33140. destination[path] = currentValue;
  33141. }
  33142. }
  33143. else if (this._originalBlendValue.m) {
  33144. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  33145. }
  33146. else {
  33147. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  33148. }
  33149. this._blendingFactor += this.blendingSpeed;
  33150. }
  33151. else {
  33152. destination[path] = currentValue;
  33153. }
  33154. if (this._target.markAsDirty) {
  33155. this._target.markAsDirty(this.targetProperty);
  33156. }
  33157. };
  33158. Animation.prototype.goToFrame = function (frame) {
  33159. if (frame < this._keys[0].frame) {
  33160. frame = this._keys[0].frame;
  33161. }
  33162. else if (frame > this._keys[this._keys.length - 1].frame) {
  33163. frame = this._keys[this._keys.length - 1].frame;
  33164. }
  33165. var currentValue = this._interpolate(frame, 0, this.loopMode);
  33166. this.setValue(currentValue);
  33167. };
  33168. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  33169. if (blend === void 0) { blend = false; }
  33170. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  33171. this._stopped = true;
  33172. return false;
  33173. }
  33174. var returnValue = true;
  33175. // Adding a start key at frame 0 if missing
  33176. if (this._keys[0].frame !== 0) {
  33177. var newKey = { frame: 0, value: this._keys[0].value };
  33178. this._keys.splice(0, 0, newKey);
  33179. }
  33180. // Check limits
  33181. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  33182. from = this._keys[0].frame;
  33183. }
  33184. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  33185. to = this._keys[this._keys.length - 1].frame;
  33186. }
  33187. //to and from cannot be the same key
  33188. if (from === to) {
  33189. from++;
  33190. }
  33191. // Compute ratio
  33192. var range = to - from;
  33193. var offsetValue;
  33194. // ratio represents the frame delta between from and to
  33195. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  33196. var highLimitValue = 0;
  33197. if (ratio > range && !loop) {
  33198. returnValue = false;
  33199. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  33200. }
  33201. else {
  33202. // Get max value if required
  33203. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  33204. var keyOffset = to.toString() + from.toString();
  33205. if (!this._offsetsCache[keyOffset]) {
  33206. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33207. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  33208. switch (this.dataType) {
  33209. // Float
  33210. case Animation.ANIMATIONTYPE_FLOAT:
  33211. this._offsetsCache[keyOffset] = toValue - fromValue;
  33212. break;
  33213. // Quaternion
  33214. case Animation.ANIMATIONTYPE_QUATERNION:
  33215. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33216. break;
  33217. // Vector3
  33218. case Animation.ANIMATIONTYPE_VECTOR3:
  33219. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33220. // Vector2
  33221. case Animation.ANIMATIONTYPE_VECTOR2:
  33222. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33223. // Size
  33224. case Animation.ANIMATIONTYPE_SIZE:
  33225. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33226. // Color3
  33227. case Animation.ANIMATIONTYPE_COLOR3:
  33228. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  33229. default:
  33230. break;
  33231. }
  33232. this._highLimitsCache[keyOffset] = toValue;
  33233. }
  33234. highLimitValue = this._highLimitsCache[keyOffset];
  33235. offsetValue = this._offsetsCache[keyOffset];
  33236. }
  33237. }
  33238. if (offsetValue === undefined) {
  33239. switch (this.dataType) {
  33240. // Float
  33241. case Animation.ANIMATIONTYPE_FLOAT:
  33242. offsetValue = 0;
  33243. break;
  33244. // Quaternion
  33245. case Animation.ANIMATIONTYPE_QUATERNION:
  33246. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  33247. break;
  33248. // Vector3
  33249. case Animation.ANIMATIONTYPE_VECTOR3:
  33250. offsetValue = BABYLON.Vector3.Zero();
  33251. break;
  33252. // Vector2
  33253. case Animation.ANIMATIONTYPE_VECTOR2:
  33254. offsetValue = BABYLON.Vector2.Zero();
  33255. break;
  33256. // Size
  33257. case Animation.ANIMATIONTYPE_SIZE:
  33258. offsetValue = BABYLON.Size.Zero();
  33259. break;
  33260. // Color3
  33261. case Animation.ANIMATIONTYPE_COLOR3:
  33262. offsetValue = BABYLON.Color3.Black();
  33263. }
  33264. }
  33265. // Compute value
  33266. var repeatCount = (ratio / range) >> 0;
  33267. var currentFrame = returnValue ? from + ratio % range : to;
  33268. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  33269. // Set value
  33270. this.setValue(currentValue);
  33271. // Check events
  33272. for (var index = 0; index < this._events.length; index++) {
  33273. if (currentFrame >= this._events[index].frame) {
  33274. var event = this._events[index];
  33275. if (!event.isDone) {
  33276. // If event should be done only once, remove it.
  33277. if (event.onlyOnce) {
  33278. this._events.splice(index, 1);
  33279. index--;
  33280. }
  33281. event.isDone = true;
  33282. event.action();
  33283. } // Don't do anything if the event has already be done.
  33284. }
  33285. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  33286. // reset event, the animation is looping
  33287. this._events[index].isDone = false;
  33288. }
  33289. }
  33290. if (!returnValue) {
  33291. this._stopped = true;
  33292. }
  33293. return returnValue;
  33294. };
  33295. Animation.prototype.serialize = function () {
  33296. var serializationObject = {};
  33297. serializationObject.name = this.name;
  33298. serializationObject.property = this.targetProperty;
  33299. serializationObject.framePerSecond = this.framePerSecond;
  33300. serializationObject.dataType = this.dataType;
  33301. serializationObject.loopBehavior = this.loopMode;
  33302. serializationObject.enableBlending = this.enableBlending;
  33303. serializationObject.blendingSpeed = this.blendingSpeed;
  33304. var dataType = this.dataType;
  33305. serializationObject.keys = [];
  33306. var keys = this.getKeys();
  33307. for (var index = 0; index < keys.length; index++) {
  33308. var animationKey = keys[index];
  33309. var key = {};
  33310. key.frame = animationKey.frame;
  33311. switch (dataType) {
  33312. case Animation.ANIMATIONTYPE_FLOAT:
  33313. key.values = [animationKey.value];
  33314. break;
  33315. case Animation.ANIMATIONTYPE_QUATERNION:
  33316. case Animation.ANIMATIONTYPE_MATRIX:
  33317. case Animation.ANIMATIONTYPE_VECTOR3:
  33318. case Animation.ANIMATIONTYPE_COLOR3:
  33319. key.values = animationKey.value.asArray();
  33320. break;
  33321. }
  33322. serializationObject.keys.push(key);
  33323. }
  33324. serializationObject.ranges = [];
  33325. for (var name in this._ranges) {
  33326. var range = {};
  33327. range.name = name;
  33328. range.from = this._ranges[name].from;
  33329. range.to = this._ranges[name].to;
  33330. serializationObject.ranges.push(range);
  33331. }
  33332. return serializationObject;
  33333. };
  33334. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  33335. get: function () {
  33336. return Animation._ANIMATIONTYPE_FLOAT;
  33337. },
  33338. enumerable: true,
  33339. configurable: true
  33340. });
  33341. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  33342. get: function () {
  33343. return Animation._ANIMATIONTYPE_VECTOR3;
  33344. },
  33345. enumerable: true,
  33346. configurable: true
  33347. });
  33348. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  33349. get: function () {
  33350. return Animation._ANIMATIONTYPE_VECTOR2;
  33351. },
  33352. enumerable: true,
  33353. configurable: true
  33354. });
  33355. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  33356. get: function () {
  33357. return Animation._ANIMATIONTYPE_SIZE;
  33358. },
  33359. enumerable: true,
  33360. configurable: true
  33361. });
  33362. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  33363. get: function () {
  33364. return Animation._ANIMATIONTYPE_QUATERNION;
  33365. },
  33366. enumerable: true,
  33367. configurable: true
  33368. });
  33369. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  33370. get: function () {
  33371. return Animation._ANIMATIONTYPE_MATRIX;
  33372. },
  33373. enumerable: true,
  33374. configurable: true
  33375. });
  33376. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  33377. get: function () {
  33378. return Animation._ANIMATIONTYPE_COLOR3;
  33379. },
  33380. enumerable: true,
  33381. configurable: true
  33382. });
  33383. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  33384. get: function () {
  33385. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  33386. },
  33387. enumerable: true,
  33388. configurable: true
  33389. });
  33390. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  33391. get: function () {
  33392. return Animation._ANIMATIONLOOPMODE_CYCLE;
  33393. },
  33394. enumerable: true,
  33395. configurable: true
  33396. });
  33397. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  33398. get: function () {
  33399. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  33400. },
  33401. enumerable: true,
  33402. configurable: true
  33403. });
  33404. Animation.Parse = function (parsedAnimation) {
  33405. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  33406. var dataType = parsedAnimation.dataType;
  33407. var keys = [];
  33408. var data;
  33409. var index;
  33410. if (parsedAnimation.enableBlending) {
  33411. animation.enableBlending = parsedAnimation.enableBlending;
  33412. }
  33413. if (parsedAnimation.blendingSpeed) {
  33414. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  33415. }
  33416. for (index = 0; index < parsedAnimation.keys.length; index++) {
  33417. var key = parsedAnimation.keys[index];
  33418. switch (dataType) {
  33419. case Animation.ANIMATIONTYPE_FLOAT:
  33420. data = key.values[0];
  33421. break;
  33422. case Animation.ANIMATIONTYPE_QUATERNION:
  33423. data = BABYLON.Quaternion.FromArray(key.values);
  33424. break;
  33425. case Animation.ANIMATIONTYPE_MATRIX:
  33426. data = BABYLON.Matrix.FromArray(key.values);
  33427. break;
  33428. case Animation.ANIMATIONTYPE_COLOR3:
  33429. data = BABYLON.Color3.FromArray(key.values);
  33430. break;
  33431. case Animation.ANIMATIONTYPE_VECTOR3:
  33432. default:
  33433. data = BABYLON.Vector3.FromArray(key.values);
  33434. break;
  33435. }
  33436. keys.push({
  33437. frame: key.frame,
  33438. value: data
  33439. });
  33440. }
  33441. animation.setKeys(keys);
  33442. if (parsedAnimation.ranges) {
  33443. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  33444. data = parsedAnimation.ranges[index];
  33445. animation.createRange(data.name, data.from, data.to);
  33446. }
  33447. }
  33448. return animation;
  33449. };
  33450. Animation.AppendSerializedAnimations = function (source, destination) {
  33451. if (source.animations) {
  33452. destination.animations = [];
  33453. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  33454. var animation = source.animations[animationIndex];
  33455. destination.animations.push(animation.serialize());
  33456. }
  33457. }
  33458. };
  33459. return Animation;
  33460. }());
  33461. // Statics
  33462. Animation._ANIMATIONTYPE_FLOAT = 0;
  33463. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  33464. Animation._ANIMATIONTYPE_QUATERNION = 2;
  33465. Animation._ANIMATIONTYPE_MATRIX = 3;
  33466. Animation._ANIMATIONTYPE_COLOR3 = 4;
  33467. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  33468. Animation._ANIMATIONTYPE_SIZE = 6;
  33469. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  33470. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  33471. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  33472. BABYLON.Animation = Animation;
  33473. })(BABYLON || (BABYLON = {}));
  33474. //# sourceMappingURL=babylon.animation.js.map
  33475. var BABYLON;
  33476. (function (BABYLON) {
  33477. var Animatable = (function () {
  33478. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  33479. if (fromFrame === void 0) { fromFrame = 0; }
  33480. if (toFrame === void 0) { toFrame = 100; }
  33481. if (loopAnimation === void 0) { loopAnimation = false; }
  33482. if (speedRatio === void 0) { speedRatio = 1.0; }
  33483. this.target = target;
  33484. this.fromFrame = fromFrame;
  33485. this.toFrame = toFrame;
  33486. this.loopAnimation = loopAnimation;
  33487. this.speedRatio = speedRatio;
  33488. this.onAnimationEnd = onAnimationEnd;
  33489. this._animations = new Array();
  33490. this._paused = false;
  33491. this.animationStarted = false;
  33492. if (animations) {
  33493. this.appendAnimations(target, animations);
  33494. }
  33495. this._scene = scene;
  33496. scene._activeAnimatables.push(this);
  33497. }
  33498. // Methods
  33499. Animatable.prototype.getAnimations = function () {
  33500. return this._animations;
  33501. };
  33502. Animatable.prototype.appendAnimations = function (target, animations) {
  33503. for (var index = 0; index < animations.length; index++) {
  33504. var animation = animations[index];
  33505. animation._target = target;
  33506. this._animations.push(animation);
  33507. }
  33508. };
  33509. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  33510. var animations = this._animations;
  33511. for (var index = 0; index < animations.length; index++) {
  33512. if (animations[index].targetProperty === property) {
  33513. return animations[index];
  33514. }
  33515. }
  33516. return null;
  33517. };
  33518. Animatable.prototype.reset = function () {
  33519. var animations = this._animations;
  33520. for (var index = 0; index < animations.length; index++) {
  33521. animations[index].reset();
  33522. }
  33523. this._localDelayOffset = null;
  33524. this._pausedDelay = null;
  33525. };
  33526. Animatable.prototype.enableBlending = function (blendingSpeed) {
  33527. var animations = this._animations;
  33528. for (var index = 0; index < animations.length; index++) {
  33529. animations[index].enableBlending = true;
  33530. animations[index].blendingSpeed = blendingSpeed;
  33531. }
  33532. };
  33533. Animatable.prototype.disableBlending = function () {
  33534. var animations = this._animations;
  33535. for (var index = 0; index < animations.length; index++) {
  33536. animations[index].enableBlending = false;
  33537. }
  33538. };
  33539. Animatable.prototype.goToFrame = function (frame) {
  33540. var animations = this._animations;
  33541. if (animations[0]) {
  33542. var fps = animations[0].framePerSecond;
  33543. var currentFrame = animations[0].currentFrame;
  33544. var adjustTime = frame - currentFrame;
  33545. var delay = adjustTime * 1000 / fps;
  33546. this._localDelayOffset -= delay;
  33547. }
  33548. for (var index = 0; index < animations.length; index++) {
  33549. animations[index].goToFrame(frame);
  33550. }
  33551. };
  33552. Animatable.prototype.pause = function () {
  33553. if (this._paused) {
  33554. return;
  33555. }
  33556. this._paused = true;
  33557. };
  33558. Animatable.prototype.restart = function () {
  33559. this._paused = false;
  33560. };
  33561. Animatable.prototype.stop = function (animationName) {
  33562. if (animationName) {
  33563. var idx = this._scene._activeAnimatables.indexOf(this);
  33564. if (idx > -1) {
  33565. var animations = this._animations;
  33566. for (var index = animations.length - 1; index >= 0; index--) {
  33567. if (typeof animationName === "string" && animations[index].name != animationName) {
  33568. continue;
  33569. }
  33570. animations[index].reset();
  33571. animations.splice(index, 1);
  33572. }
  33573. if (animations.length == 0) {
  33574. this._scene._activeAnimatables.splice(idx, 1);
  33575. if (this.onAnimationEnd) {
  33576. this.onAnimationEnd();
  33577. }
  33578. }
  33579. }
  33580. }
  33581. else {
  33582. var index = this._scene._activeAnimatables.indexOf(this);
  33583. if (index > -1) {
  33584. this._scene._activeAnimatables.splice(index, 1);
  33585. var animations = this._animations;
  33586. for (var index = 0; index < animations.length; index++) {
  33587. animations[index].reset();
  33588. }
  33589. if (this.onAnimationEnd) {
  33590. this.onAnimationEnd();
  33591. }
  33592. }
  33593. }
  33594. };
  33595. Animatable.prototype._animate = function (delay) {
  33596. if (this._paused) {
  33597. this.animationStarted = false;
  33598. if (!this._pausedDelay) {
  33599. this._pausedDelay = delay;
  33600. }
  33601. return true;
  33602. }
  33603. if (!this._localDelayOffset) {
  33604. this._localDelayOffset = delay;
  33605. }
  33606. else if (this._pausedDelay) {
  33607. this._localDelayOffset += delay - this._pausedDelay;
  33608. this._pausedDelay = null;
  33609. }
  33610. // Animating
  33611. var running = false;
  33612. var animations = this._animations;
  33613. var index;
  33614. for (index = 0; index < animations.length; index++) {
  33615. var animation = animations[index];
  33616. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33617. running = running || isRunning;
  33618. }
  33619. this.animationStarted = running;
  33620. if (!running) {
  33621. // Remove from active animatables
  33622. index = this._scene._activeAnimatables.indexOf(this);
  33623. this._scene._activeAnimatables.splice(index, 1);
  33624. }
  33625. if (!running && this.onAnimationEnd) {
  33626. this.onAnimationEnd();
  33627. this.onAnimationEnd = null;
  33628. }
  33629. return running;
  33630. };
  33631. return Animatable;
  33632. }());
  33633. BABYLON.Animatable = Animatable;
  33634. })(BABYLON || (BABYLON = {}));
  33635. //# sourceMappingURL=babylon.animatable.js.map
  33636. var BABYLON;
  33637. (function (BABYLON) {
  33638. var EasingFunction = (function () {
  33639. function EasingFunction() {
  33640. // Properties
  33641. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33642. }
  33643. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33644. get: function () {
  33645. return EasingFunction._EASINGMODE_EASEIN;
  33646. },
  33647. enumerable: true,
  33648. configurable: true
  33649. });
  33650. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33651. get: function () {
  33652. return EasingFunction._EASINGMODE_EASEOUT;
  33653. },
  33654. enumerable: true,
  33655. configurable: true
  33656. });
  33657. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33658. get: function () {
  33659. return EasingFunction._EASINGMODE_EASEINOUT;
  33660. },
  33661. enumerable: true,
  33662. configurable: true
  33663. });
  33664. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33665. var n = Math.min(Math.max(easingMode, 0), 2);
  33666. this._easingMode = n;
  33667. };
  33668. EasingFunction.prototype.getEasingMode = function () {
  33669. return this._easingMode;
  33670. };
  33671. EasingFunction.prototype.easeInCore = function (gradient) {
  33672. throw new Error('You must implement this method');
  33673. };
  33674. EasingFunction.prototype.ease = function (gradient) {
  33675. switch (this._easingMode) {
  33676. case EasingFunction.EASINGMODE_EASEIN:
  33677. return this.easeInCore(gradient);
  33678. case EasingFunction.EASINGMODE_EASEOUT:
  33679. return (1 - this.easeInCore(1 - gradient));
  33680. }
  33681. if (gradient >= 0.5) {
  33682. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33683. }
  33684. return (this.easeInCore(gradient * 2) * 0.5);
  33685. };
  33686. return EasingFunction;
  33687. }());
  33688. //Statics
  33689. EasingFunction._EASINGMODE_EASEIN = 0;
  33690. EasingFunction._EASINGMODE_EASEOUT = 1;
  33691. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33692. BABYLON.EasingFunction = EasingFunction;
  33693. var CircleEase = (function (_super) {
  33694. __extends(CircleEase, _super);
  33695. function CircleEase() {
  33696. return _super !== null && _super.apply(this, arguments) || this;
  33697. }
  33698. CircleEase.prototype.easeInCore = function (gradient) {
  33699. gradient = Math.max(0, Math.min(1, gradient));
  33700. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33701. };
  33702. return CircleEase;
  33703. }(EasingFunction));
  33704. BABYLON.CircleEase = CircleEase;
  33705. var BackEase = (function (_super) {
  33706. __extends(BackEase, _super);
  33707. function BackEase(amplitude) {
  33708. if (amplitude === void 0) { amplitude = 1; }
  33709. var _this = _super.call(this) || this;
  33710. _this.amplitude = amplitude;
  33711. return _this;
  33712. }
  33713. BackEase.prototype.easeInCore = function (gradient) {
  33714. var num = Math.max(0, this.amplitude);
  33715. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33716. };
  33717. return BackEase;
  33718. }(EasingFunction));
  33719. BABYLON.BackEase = BackEase;
  33720. var BounceEase = (function (_super) {
  33721. __extends(BounceEase, _super);
  33722. function BounceEase(bounces, bounciness) {
  33723. if (bounces === void 0) { bounces = 3; }
  33724. if (bounciness === void 0) { bounciness = 2; }
  33725. var _this = _super.call(this) || this;
  33726. _this.bounces = bounces;
  33727. _this.bounciness = bounciness;
  33728. return _this;
  33729. }
  33730. BounceEase.prototype.easeInCore = function (gradient) {
  33731. var y = Math.max(0.0, this.bounces);
  33732. var bounciness = this.bounciness;
  33733. if (bounciness <= 1.0) {
  33734. bounciness = 1.001;
  33735. }
  33736. var num9 = Math.pow(bounciness, y);
  33737. var num5 = 1.0 - bounciness;
  33738. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33739. var num15 = gradient * num4;
  33740. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33741. var num3 = Math.floor(num65);
  33742. var num13 = num3 + 1.0;
  33743. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33744. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33745. var num7 = (num8 + num12) * 0.5;
  33746. var num6 = gradient - num7;
  33747. var num2 = num7 - num8;
  33748. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33749. };
  33750. return BounceEase;
  33751. }(EasingFunction));
  33752. BABYLON.BounceEase = BounceEase;
  33753. var CubicEase = (function (_super) {
  33754. __extends(CubicEase, _super);
  33755. function CubicEase() {
  33756. return _super !== null && _super.apply(this, arguments) || this;
  33757. }
  33758. CubicEase.prototype.easeInCore = function (gradient) {
  33759. return (gradient * gradient * gradient);
  33760. };
  33761. return CubicEase;
  33762. }(EasingFunction));
  33763. BABYLON.CubicEase = CubicEase;
  33764. var ElasticEase = (function (_super) {
  33765. __extends(ElasticEase, _super);
  33766. function ElasticEase(oscillations, springiness) {
  33767. if (oscillations === void 0) { oscillations = 3; }
  33768. if (springiness === void 0) { springiness = 3; }
  33769. var _this = _super.call(this) || this;
  33770. _this.oscillations = oscillations;
  33771. _this.springiness = springiness;
  33772. return _this;
  33773. }
  33774. ElasticEase.prototype.easeInCore = function (gradient) {
  33775. var num2;
  33776. var num3 = Math.max(0.0, this.oscillations);
  33777. var num = Math.max(0.0, this.springiness);
  33778. if (num == 0) {
  33779. num2 = gradient;
  33780. }
  33781. else {
  33782. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33783. }
  33784. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33785. };
  33786. return ElasticEase;
  33787. }(EasingFunction));
  33788. BABYLON.ElasticEase = ElasticEase;
  33789. var ExponentialEase = (function (_super) {
  33790. __extends(ExponentialEase, _super);
  33791. function ExponentialEase(exponent) {
  33792. if (exponent === void 0) { exponent = 2; }
  33793. var _this = _super.call(this) || this;
  33794. _this.exponent = exponent;
  33795. return _this;
  33796. }
  33797. ExponentialEase.prototype.easeInCore = function (gradient) {
  33798. if (this.exponent <= 0) {
  33799. return gradient;
  33800. }
  33801. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33802. };
  33803. return ExponentialEase;
  33804. }(EasingFunction));
  33805. BABYLON.ExponentialEase = ExponentialEase;
  33806. var PowerEase = (function (_super) {
  33807. __extends(PowerEase, _super);
  33808. function PowerEase(power) {
  33809. if (power === void 0) { power = 2; }
  33810. var _this = _super.call(this) || this;
  33811. _this.power = power;
  33812. return _this;
  33813. }
  33814. PowerEase.prototype.easeInCore = function (gradient) {
  33815. var y = Math.max(0.0, this.power);
  33816. return Math.pow(gradient, y);
  33817. };
  33818. return PowerEase;
  33819. }(EasingFunction));
  33820. BABYLON.PowerEase = PowerEase;
  33821. var QuadraticEase = (function (_super) {
  33822. __extends(QuadraticEase, _super);
  33823. function QuadraticEase() {
  33824. return _super !== null && _super.apply(this, arguments) || this;
  33825. }
  33826. QuadraticEase.prototype.easeInCore = function (gradient) {
  33827. return (gradient * gradient);
  33828. };
  33829. return QuadraticEase;
  33830. }(EasingFunction));
  33831. BABYLON.QuadraticEase = QuadraticEase;
  33832. var QuarticEase = (function (_super) {
  33833. __extends(QuarticEase, _super);
  33834. function QuarticEase() {
  33835. return _super !== null && _super.apply(this, arguments) || this;
  33836. }
  33837. QuarticEase.prototype.easeInCore = function (gradient) {
  33838. return (gradient * gradient * gradient * gradient);
  33839. };
  33840. return QuarticEase;
  33841. }(EasingFunction));
  33842. BABYLON.QuarticEase = QuarticEase;
  33843. var QuinticEase = (function (_super) {
  33844. __extends(QuinticEase, _super);
  33845. function QuinticEase() {
  33846. return _super !== null && _super.apply(this, arguments) || this;
  33847. }
  33848. QuinticEase.prototype.easeInCore = function (gradient) {
  33849. return (gradient * gradient * gradient * gradient * gradient);
  33850. };
  33851. return QuinticEase;
  33852. }(EasingFunction));
  33853. BABYLON.QuinticEase = QuinticEase;
  33854. var SineEase = (function (_super) {
  33855. __extends(SineEase, _super);
  33856. function SineEase() {
  33857. return _super !== null && _super.apply(this, arguments) || this;
  33858. }
  33859. SineEase.prototype.easeInCore = function (gradient) {
  33860. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33861. };
  33862. return SineEase;
  33863. }(EasingFunction));
  33864. BABYLON.SineEase = SineEase;
  33865. var BezierCurveEase = (function (_super) {
  33866. __extends(BezierCurveEase, _super);
  33867. function BezierCurveEase(x1, y1, x2, y2) {
  33868. if (x1 === void 0) { x1 = 0; }
  33869. if (y1 === void 0) { y1 = 0; }
  33870. if (x2 === void 0) { x2 = 1; }
  33871. if (y2 === void 0) { y2 = 1; }
  33872. var _this = _super.call(this) || this;
  33873. _this.x1 = x1;
  33874. _this.y1 = y1;
  33875. _this.x2 = x2;
  33876. _this.y2 = y2;
  33877. return _this;
  33878. }
  33879. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33880. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33881. };
  33882. return BezierCurveEase;
  33883. }(EasingFunction));
  33884. BABYLON.BezierCurveEase = BezierCurveEase;
  33885. })(BABYLON || (BABYLON = {}));
  33886. //# sourceMappingURL=babylon.easing.js.map
  33887. /// <reference path="..\babylon.node.ts" />
  33888. var BABYLON;
  33889. (function (BABYLON) {
  33890. var Bone = (function (_super) {
  33891. __extends(Bone, _super);
  33892. function Bone(name, skeleton, parentBone, matrix, restPose) {
  33893. var _this = _super.call(this, name, skeleton.getScene()) || this;
  33894. _this.name = name;
  33895. _this.children = new Array();
  33896. _this.animations = new Array();
  33897. _this._worldTransform = new BABYLON.Matrix();
  33898. _this._absoluteTransform = new BABYLON.Matrix();
  33899. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  33900. _this._scaleMatrix = BABYLON.Matrix.Identity();
  33901. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  33902. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  33903. _this._scalingDeterminant = 1;
  33904. _this._skeleton = skeleton;
  33905. _this._localMatrix = matrix;
  33906. _this._baseMatrix = matrix.clone();
  33907. _this._restPose = restPose ? restPose : matrix.clone();
  33908. skeleton.bones.push(_this);
  33909. if (parentBone) {
  33910. _this._parent = parentBone;
  33911. parentBone.children.push(_this);
  33912. }
  33913. else {
  33914. _this._parent = null;
  33915. }
  33916. _this._updateDifferenceMatrix();
  33917. if (_this.getAbsoluteTransform().determinant() < 0) {
  33918. _this._scalingDeterminant *= -1;
  33919. }
  33920. return _this;
  33921. }
  33922. Object.defineProperty(Bone.prototype, "_matrix", {
  33923. get: function () {
  33924. return this._localMatrix;
  33925. },
  33926. set: function (val) {
  33927. if (this._localMatrix) {
  33928. this._localMatrix.copyFrom(val);
  33929. }
  33930. else {
  33931. this._localMatrix = val;
  33932. }
  33933. },
  33934. enumerable: true,
  33935. configurable: true
  33936. });
  33937. // Members
  33938. Bone.prototype.getParent = function () {
  33939. return this._parent;
  33940. };
  33941. Bone.prototype.getLocalMatrix = function () {
  33942. return this._localMatrix;
  33943. };
  33944. Bone.prototype.getBaseMatrix = function () {
  33945. return this._baseMatrix;
  33946. };
  33947. Bone.prototype.getRestPose = function () {
  33948. return this._restPose;
  33949. };
  33950. Bone.prototype.returnToRest = function () {
  33951. this.updateMatrix(this._restPose.clone());
  33952. };
  33953. Bone.prototype.getWorldMatrix = function () {
  33954. return this._worldTransform;
  33955. };
  33956. Bone.prototype.getInvertedAbsoluteTransform = function () {
  33957. return this._invertedAbsoluteTransform;
  33958. };
  33959. Bone.prototype.getAbsoluteTransform = function () {
  33960. return this._absoluteTransform;
  33961. };
  33962. // Methods
  33963. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  33964. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  33965. this._baseMatrix = matrix.clone();
  33966. this._localMatrix = matrix.clone();
  33967. this._skeleton._markAsDirty();
  33968. if (updateDifferenceMatrix) {
  33969. this._updateDifferenceMatrix();
  33970. }
  33971. };
  33972. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  33973. if (!rootMatrix) {
  33974. rootMatrix = this._baseMatrix;
  33975. }
  33976. if (this._parent) {
  33977. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  33978. }
  33979. else {
  33980. this._absoluteTransform.copyFrom(rootMatrix);
  33981. }
  33982. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  33983. for (var index = 0; index < this.children.length; index++) {
  33984. this.children[index]._updateDifferenceMatrix();
  33985. }
  33986. };
  33987. Bone.prototype.markAsDirty = function () {
  33988. this._currentRenderId++;
  33989. this._skeleton._markAsDirty();
  33990. };
  33991. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  33992. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  33993. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  33994. // all animation may be coming from a library skeleton, so may need to create animation
  33995. if (this.animations.length === 0) {
  33996. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  33997. this.animations[0].setKeys([]);
  33998. }
  33999. // get animation info / verify there is such a range from the source bone
  34000. var sourceRange = source.animations[0].getRange(rangeName);
  34001. if (!sourceRange) {
  34002. return false;
  34003. }
  34004. var from = sourceRange.from;
  34005. var to = sourceRange.to;
  34006. var sourceKeys = source.animations[0].getKeys();
  34007. // rescaling prep
  34008. var sourceBoneLength = source.length;
  34009. var sourceParent = source.getParent();
  34010. var parent = this.getParent();
  34011. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  34012. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  34013. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  34014. var destKeys = this.animations[0].getKeys();
  34015. // loop vars declaration
  34016. var orig;
  34017. var origTranslation;
  34018. var mat;
  34019. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  34020. orig = sourceKeys[key];
  34021. if (orig.frame >= from && orig.frame <= to) {
  34022. if (rescaleAsRequired) {
  34023. mat = orig.value.clone();
  34024. // scale based on parent ratio, when bone has parent
  34025. if (parentScalingReqd) {
  34026. origTranslation = mat.getTranslation();
  34027. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  34028. // scale based on skeleton dimension ratio when root bone, and value is passed
  34029. }
  34030. else if (dimensionsScalingReqd) {
  34031. origTranslation = mat.getTranslation();
  34032. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  34033. // use original when root bone, and no data for skelDimensionsRatio
  34034. }
  34035. else {
  34036. mat = orig.value;
  34037. }
  34038. }
  34039. else {
  34040. mat = orig.value;
  34041. }
  34042. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  34043. }
  34044. }
  34045. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  34046. return true;
  34047. };
  34048. /**
  34049. * Translate the bone in local or world space.
  34050. * @param vec The amount to translate the bone.
  34051. * @param space The space that the translation is in.
  34052. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34053. */
  34054. Bone.prototype.translate = function (vec, space, mesh) {
  34055. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34056. var lm = this.getLocalMatrix();
  34057. if (space == BABYLON.Space.LOCAL) {
  34058. lm.m[12] += vec.x;
  34059. lm.m[13] += vec.y;
  34060. lm.m[14] += vec.z;
  34061. }
  34062. else {
  34063. var wm;
  34064. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34065. if (mesh) {
  34066. wm = mesh.getWorldMatrix();
  34067. }
  34068. this._skeleton.computeAbsoluteTransforms();
  34069. var tmat = BABYLON.Tmp.Matrix[0];
  34070. var tvec = BABYLON.Tmp.Vector3[0];
  34071. if (mesh) {
  34072. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34073. tmat.multiplyToRef(wm, tmat);
  34074. }
  34075. else {
  34076. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34077. }
  34078. tmat.m[12] = 0;
  34079. tmat.m[13] = 0;
  34080. tmat.m[14] = 0;
  34081. tmat.invert();
  34082. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  34083. lm.m[12] += tvec.x;
  34084. lm.m[13] += tvec.y;
  34085. lm.m[14] += tvec.z;
  34086. }
  34087. this.markAsDirty();
  34088. };
  34089. /**
  34090. * Set the postion of the bone in local or world space.
  34091. * @param position The position to set the bone.
  34092. * @param space The space that the position is in.
  34093. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34094. */
  34095. Bone.prototype.setPosition = function (position, space, mesh) {
  34096. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34097. var lm = this.getLocalMatrix();
  34098. if (space == BABYLON.Space.LOCAL) {
  34099. lm.m[12] = position.x;
  34100. lm.m[13] = position.y;
  34101. lm.m[14] = position.z;
  34102. }
  34103. else {
  34104. var wm;
  34105. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34106. if (mesh) {
  34107. wm = mesh.getWorldMatrix();
  34108. }
  34109. this._skeleton.computeAbsoluteTransforms();
  34110. var tmat = BABYLON.Tmp.Matrix[0];
  34111. var vec = BABYLON.Tmp.Vector3[0];
  34112. if (mesh) {
  34113. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34114. tmat.multiplyToRef(wm, tmat);
  34115. }
  34116. else {
  34117. tmat.copyFrom(this._parent.getAbsoluteTransform());
  34118. }
  34119. tmat.invert();
  34120. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  34121. lm.m[12] = vec.x;
  34122. lm.m[13] = vec.y;
  34123. lm.m[14] = vec.z;
  34124. }
  34125. this.markAsDirty();
  34126. };
  34127. /**
  34128. * Set the absolute postion of the bone (world space).
  34129. * @param position The position to set the bone.
  34130. * @param mesh The mesh that this bone is attached to.
  34131. */
  34132. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  34133. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  34134. };
  34135. /**
  34136. * Set the scale of the bone on the x, y and z axes.
  34137. * @param x The scale of the bone on the x axis.
  34138. * @param x The scale of the bone on the y axis.
  34139. * @param z The scale of the bone on the z axis.
  34140. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34141. */
  34142. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  34143. if (scaleChildren === void 0) { scaleChildren = false; }
  34144. if (this.animations[0] && !this.animations[0].isStopped()) {
  34145. if (!scaleChildren) {
  34146. this._negateScaleChildren.x = 1 / x;
  34147. this._negateScaleChildren.y = 1 / y;
  34148. this._negateScaleChildren.z = 1 / z;
  34149. }
  34150. this._syncScaleVector();
  34151. }
  34152. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  34153. };
  34154. /**
  34155. * Scale the bone on the x, y and z axes.
  34156. * @param x The amount to scale the bone on the x axis.
  34157. * @param x The amount to scale the bone on the y axis.
  34158. * @param z The amount to scale the bone on the z axis.
  34159. * @param scaleChildren Set this to true if children of the bone should be scaled.
  34160. */
  34161. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  34162. if (scaleChildren === void 0) { scaleChildren = false; }
  34163. var locMat = this.getLocalMatrix();
  34164. var origLocMat = BABYLON.Tmp.Matrix[0];
  34165. origLocMat.copyFrom(locMat);
  34166. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  34167. origLocMatInv.copyFrom(origLocMat);
  34168. origLocMatInv.invert();
  34169. var scaleMat = BABYLON.Tmp.Matrix[2];
  34170. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  34171. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  34172. this._scaleVector.x *= x;
  34173. this._scaleVector.y *= y;
  34174. this._scaleVector.z *= z;
  34175. locMat.multiplyToRef(origLocMatInv, locMat);
  34176. locMat.multiplyToRef(scaleMat, locMat);
  34177. locMat.multiplyToRef(origLocMat, locMat);
  34178. var parent = this.getParent();
  34179. if (parent) {
  34180. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  34181. }
  34182. else {
  34183. this.getAbsoluteTransform().copyFrom(locMat);
  34184. }
  34185. var len = this.children.length;
  34186. scaleMat.invert();
  34187. for (var i = 0; i < len; i++) {
  34188. var child = this.children[i];
  34189. var cm = child.getLocalMatrix();
  34190. cm.multiplyToRef(scaleMat, cm);
  34191. var lm = child.getLocalMatrix();
  34192. lm.m[12] *= x;
  34193. lm.m[13] *= y;
  34194. lm.m[14] *= z;
  34195. }
  34196. this.computeAbsoluteTransforms();
  34197. if (scaleChildren) {
  34198. for (var i = 0; i < len; i++) {
  34199. this.children[i].scale(x, y, z, scaleChildren);
  34200. }
  34201. }
  34202. this.markAsDirty();
  34203. };
  34204. /**
  34205. * Set the yaw, pitch, and roll of the bone in local or world space.
  34206. * @param yaw The rotation of the bone on the y axis.
  34207. * @param pitch The rotation of the bone on the x axis.
  34208. * @param roll The rotation of the bone on the z axis.
  34209. * @param space The space that the axes of rotation are in.
  34210. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34211. */
  34212. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  34213. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34214. var rotMat = BABYLON.Tmp.Matrix[0];
  34215. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  34216. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34217. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34218. rotMatInv.multiplyToRef(rotMat, rotMat);
  34219. this._rotateWithMatrix(rotMat, space, mesh);
  34220. };
  34221. /**
  34222. * Rotate the bone on an axis in local or world space.
  34223. * @param axis The axis to rotate the bone on.
  34224. * @param amount The amount to rotate the bone.
  34225. * @param space The space that the axis is in.
  34226. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34227. */
  34228. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  34229. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34230. var rmat = BABYLON.Tmp.Matrix[0];
  34231. rmat.m[12] = 0;
  34232. rmat.m[13] = 0;
  34233. rmat.m[14] = 0;
  34234. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  34235. this._rotateWithMatrix(rmat, space, mesh);
  34236. };
  34237. /**
  34238. * Set the rotation of the bone to a particular axis angle in local or world space.
  34239. * @param axis The axis to rotate the bone on.
  34240. * @param angle The angle that the bone should be rotated to.
  34241. * @param space The space that the axis is in.
  34242. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34243. */
  34244. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  34245. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34246. var rotMat = BABYLON.Tmp.Matrix[0];
  34247. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  34248. var rotMatInv = BABYLON.Tmp.Matrix[1];
  34249. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34250. rotMatInv.multiplyToRef(rotMat, rotMat);
  34251. this._rotateWithMatrix(rotMat, space, mesh);
  34252. };
  34253. /**
  34254. * Set the euler rotation of the bone in local of world space.
  34255. * @param rotation The euler rotation that the bone should be set to.
  34256. * @param space The space that the rotation is in.
  34257. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34258. */
  34259. Bone.prototype.setRotation = function (rotation, space, mesh) {
  34260. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34261. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  34262. };
  34263. /**
  34264. * Set the quaternion rotation of the bone in local of world space.
  34265. * @param quat The quaternion rotation that the bone should be set to.
  34266. * @param space The space that the rotation is in.
  34267. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34268. */
  34269. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  34270. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34271. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34272. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34273. var rotMat = BABYLON.Tmp.Matrix[1];
  34274. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  34275. rotMatInv.multiplyToRef(rotMat, rotMat);
  34276. this._rotateWithMatrix(rotMat, space, mesh);
  34277. };
  34278. /**
  34279. * Set the rotation matrix of the bone in local of world space.
  34280. * @param rotMat The rotation matrix that the bone should be set to.
  34281. * @param space The space that the rotation is in.
  34282. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34283. */
  34284. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  34285. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34286. var rotMatInv = BABYLON.Tmp.Matrix[0];
  34287. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  34288. var rotMat2 = BABYLON.Tmp.Matrix[1];
  34289. rotMat2.copyFrom(rotMat);
  34290. rotMatInv.multiplyToRef(rotMat, rotMat2);
  34291. this._rotateWithMatrix(rotMat2, space, mesh);
  34292. };
  34293. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  34294. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34295. var lmat = this.getLocalMatrix();
  34296. var lx = lmat.m[12];
  34297. var ly = lmat.m[13];
  34298. var lz = lmat.m[14];
  34299. var parent = this.getParent();
  34300. var parentScale = BABYLON.Tmp.Matrix[3];
  34301. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  34302. if (parent) {
  34303. if (space == BABYLON.Space.WORLD) {
  34304. if (mesh) {
  34305. parentScale.copyFrom(mesh.getWorldMatrix());
  34306. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  34307. }
  34308. else {
  34309. parentScale.copyFrom(parent.getAbsoluteTransform());
  34310. }
  34311. }
  34312. else {
  34313. parentScale = parent._scaleMatrix;
  34314. }
  34315. parentScaleInv.copyFrom(parentScale);
  34316. parentScaleInv.invert();
  34317. lmat.multiplyToRef(parentScale, lmat);
  34318. lmat.multiplyToRef(rmat, lmat);
  34319. lmat.multiplyToRef(parentScaleInv, lmat);
  34320. }
  34321. else {
  34322. if (space == BABYLON.Space.WORLD && mesh) {
  34323. parentScale.copyFrom(mesh.getWorldMatrix());
  34324. parentScaleInv.copyFrom(parentScale);
  34325. parentScaleInv.invert();
  34326. lmat.multiplyToRef(parentScale, lmat);
  34327. lmat.multiplyToRef(rmat, lmat);
  34328. lmat.multiplyToRef(parentScaleInv, lmat);
  34329. }
  34330. else {
  34331. lmat.multiplyToRef(rmat, lmat);
  34332. }
  34333. }
  34334. lmat.m[12] = lx;
  34335. lmat.m[13] = ly;
  34336. lmat.m[14] = lz;
  34337. this.computeAbsoluteTransforms();
  34338. this.markAsDirty();
  34339. };
  34340. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  34341. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34342. if (space == BABYLON.Space.WORLD) {
  34343. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34344. scaleMatrix.copyFrom(this._scaleMatrix);
  34345. rotMatInv.copyFrom(this.getAbsoluteTransform());
  34346. if (mesh) {
  34347. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  34348. var meshScale = BABYLON.Tmp.Matrix[3];
  34349. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  34350. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  34351. }
  34352. rotMatInv.invert();
  34353. scaleMatrix.m[0] *= this._scalingDeterminant;
  34354. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34355. }
  34356. else {
  34357. rotMatInv.copyFrom(this.getLocalMatrix());
  34358. rotMatInv.invert();
  34359. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  34360. scaleMatrix.copyFrom(this._scaleMatrix);
  34361. if (this._parent) {
  34362. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  34363. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  34364. pscaleMatrix.invert();
  34365. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  34366. }
  34367. else {
  34368. scaleMatrix.m[0] *= this._scalingDeterminant;
  34369. }
  34370. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  34371. }
  34372. };
  34373. /**
  34374. * Get the scale of the bone
  34375. * @returns the scale of the bone
  34376. */
  34377. Bone.prototype.getScale = function () {
  34378. return this._scaleVector.clone();
  34379. };
  34380. /**
  34381. * Copy the scale of the bone to a vector3.
  34382. * @param result The vector3 to copy the scale to
  34383. */
  34384. Bone.prototype.getScaleToRef = function (result) {
  34385. result.copyFrom(this._scaleVector);
  34386. };
  34387. /**
  34388. * Get the position of the bone in local or world space.
  34389. * @param space The space that the returned position is in.
  34390. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34391. * @returns The position of the bone
  34392. */
  34393. Bone.prototype.getPosition = function (space, mesh) {
  34394. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34395. var pos = BABYLON.Vector3.Zero();
  34396. this.getPositionToRef(space, mesh, pos);
  34397. return pos;
  34398. };
  34399. /**
  34400. * Copy the position of the bone to a vector3 in local or world space.
  34401. * @param space The space that the returned position is in.
  34402. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34403. * @param result The vector3 to copy the position to.
  34404. */
  34405. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  34406. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34407. if (space == BABYLON.Space.LOCAL) {
  34408. var lm = this.getLocalMatrix();
  34409. result.x = lm.m[12];
  34410. result.y = lm.m[13];
  34411. result.z = lm.m[14];
  34412. }
  34413. else {
  34414. var wm;
  34415. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34416. if (mesh) {
  34417. wm = mesh.getWorldMatrix();
  34418. }
  34419. this._skeleton.computeAbsoluteTransforms();
  34420. var tmat = BABYLON.Tmp.Matrix[0];
  34421. if (mesh) {
  34422. tmat.copyFrom(this.getAbsoluteTransform());
  34423. tmat.multiplyToRef(wm, tmat);
  34424. }
  34425. else {
  34426. tmat = this.getAbsoluteTransform();
  34427. }
  34428. result.x = tmat.m[12];
  34429. result.y = tmat.m[13];
  34430. result.z = tmat.m[14];
  34431. }
  34432. };
  34433. /**
  34434. * Get the absolute position of the bone (world space).
  34435. * @param mesh The mesh that this bone is attached to.
  34436. * @returns The absolute position of the bone
  34437. */
  34438. Bone.prototype.getAbsolutePosition = function (mesh) {
  34439. var pos = BABYLON.Vector3.Zero();
  34440. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  34441. return pos;
  34442. };
  34443. /**
  34444. * Copy the absolute position of the bone (world space) to the result param.
  34445. * @param mesh The mesh that this bone is attached to.
  34446. * @param result The vector3 to copy the absolute position to.
  34447. */
  34448. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  34449. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  34450. };
  34451. /**
  34452. * Compute the absolute transforms of this bone and its children.
  34453. */
  34454. Bone.prototype.computeAbsoluteTransforms = function () {
  34455. if (this._parent) {
  34456. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  34457. }
  34458. else {
  34459. this._absoluteTransform.copyFrom(this._localMatrix);
  34460. var poseMatrix = this._skeleton.getPoseMatrix();
  34461. if (poseMatrix) {
  34462. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  34463. }
  34464. }
  34465. var children = this.children;
  34466. var len = children.length;
  34467. for (var i = 0; i < len; i++) {
  34468. children[i].computeAbsoluteTransforms();
  34469. }
  34470. };
  34471. Bone.prototype._syncScaleVector = function () {
  34472. var lm = this.getLocalMatrix();
  34473. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  34474. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  34475. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  34476. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  34477. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  34478. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  34479. this._scaleVector.x = xs * Math.sqrt(xsq);
  34480. this._scaleVector.y = ys * Math.sqrt(ysq);
  34481. this._scaleVector.z = zs * Math.sqrt(zsq);
  34482. if (this._parent) {
  34483. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  34484. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  34485. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  34486. }
  34487. 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);
  34488. };
  34489. /**
  34490. * Get the world direction from an axis that is in the local space of the bone.
  34491. * @param localAxis The local direction that is used to compute the world direction.
  34492. * @param mesh The mesh that this bone is attached to.
  34493. * @returns The world direction
  34494. */
  34495. Bone.prototype.getDirection = function (localAxis, mesh) {
  34496. var result = BABYLON.Vector3.Zero();
  34497. this.getDirectionToRef(localAxis, mesh, result);
  34498. return result;
  34499. };
  34500. /**
  34501. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  34502. * @param localAxis The local direction that is used to compute the world direction.
  34503. * @param mesh The mesh that this bone is attached to.
  34504. * @param result The vector3 that the world direction will be copied to.
  34505. */
  34506. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  34507. var wm;
  34508. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34509. if (mesh) {
  34510. wm = mesh.getWorldMatrix();
  34511. }
  34512. this._skeleton.computeAbsoluteTransforms();
  34513. var mat = BABYLON.Tmp.Matrix[0];
  34514. mat.copyFrom(this.getAbsoluteTransform());
  34515. if (mesh) {
  34516. mat.multiplyToRef(wm, mat);
  34517. }
  34518. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  34519. result.normalize();
  34520. };
  34521. /**
  34522. * Get the euler rotation of the bone in local or world space.
  34523. * @param space The space that the rotation should be in.
  34524. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34525. * @returns The euler rotation
  34526. */
  34527. Bone.prototype.getRotation = function (space, mesh) {
  34528. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34529. var result = BABYLON.Vector3.Zero();
  34530. this.getRotationToRef(space, mesh, result);
  34531. return result;
  34532. };
  34533. /**
  34534. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  34535. * @param space The space that the rotation should be in.
  34536. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34537. * @param result The vector3 that the rotation should be copied to.
  34538. */
  34539. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  34540. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34541. var quat = BABYLON.Tmp.Quaternion[0];
  34542. this.getRotationQuaternionToRef(space, mesh, quat);
  34543. quat.toEulerAnglesToRef(result);
  34544. };
  34545. /**
  34546. * Get the quaternion rotation of the bone in either local or world space.
  34547. * @param space The space that the rotation should be in.
  34548. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34549. * @returns The quaternion rotation
  34550. */
  34551. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  34552. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34553. var result = BABYLON.Quaternion.Identity();
  34554. this.getRotationQuaternionToRef(space, mesh, result);
  34555. return result;
  34556. };
  34557. /**
  34558. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  34559. * @param space The space that the rotation should be in.
  34560. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34561. * @param result The quaternion that the rotation should be copied to.
  34562. */
  34563. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  34564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34565. if (space == BABYLON.Space.LOCAL) {
  34566. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34567. }
  34568. else {
  34569. var mat = BABYLON.Tmp.Matrix[0];
  34570. var amat = this.getAbsoluteTransform();
  34571. if (mesh) {
  34572. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34573. }
  34574. else {
  34575. mat.copyFrom(amat);
  34576. }
  34577. mat.m[0] *= this._scalingDeterminant;
  34578. mat.m[1] *= this._scalingDeterminant;
  34579. mat.m[2] *= this._scalingDeterminant;
  34580. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  34581. }
  34582. };
  34583. /**
  34584. * Get the rotation matrix of the bone in local or world space.
  34585. * @param space The space that the rotation should be in.
  34586. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34587. * @returns The rotation matrix
  34588. */
  34589. Bone.prototype.getRotationMatrix = function (space, mesh) {
  34590. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34591. var result = BABYLON.Matrix.Identity();
  34592. this.getRotationMatrixToRef(space, mesh, result);
  34593. return result;
  34594. };
  34595. /**
  34596. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  34597. * @param space The space that the rotation should be in.
  34598. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  34599. * @param result The quaternion that the rotation should be copied to.
  34600. */
  34601. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  34602. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  34603. if (space == BABYLON.Space.LOCAL) {
  34604. this.getLocalMatrix().getRotationMatrixToRef(result);
  34605. }
  34606. else {
  34607. var mat = BABYLON.Tmp.Matrix[0];
  34608. var amat = this.getAbsoluteTransform();
  34609. if (mesh) {
  34610. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  34611. }
  34612. else {
  34613. mat.copyFrom(amat);
  34614. }
  34615. mat.m[0] *= this._scalingDeterminant;
  34616. mat.m[1] *= this._scalingDeterminant;
  34617. mat.m[2] *= this._scalingDeterminant;
  34618. mat.getRotationMatrixToRef(result);
  34619. }
  34620. };
  34621. /**
  34622. * Get the world position of a point that is in the local space of the bone.
  34623. * @param position The local position
  34624. * @param mesh The mesh that this bone is attached to.
  34625. * @returns The world position
  34626. */
  34627. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  34628. var result = BABYLON.Vector3.Zero();
  34629. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  34630. return result;
  34631. };
  34632. /**
  34633. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  34634. * @param position The local position
  34635. * @param mesh The mesh that this bone is attached to.
  34636. * @param result The vector3 that the world position should be copied to.
  34637. */
  34638. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  34639. var wm;
  34640. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34641. if (mesh) {
  34642. wm = mesh.getWorldMatrix();
  34643. }
  34644. this._skeleton.computeAbsoluteTransforms();
  34645. var tmat = BABYLON.Tmp.Matrix[0];
  34646. if (mesh) {
  34647. tmat.copyFrom(this.getAbsoluteTransform());
  34648. tmat.multiplyToRef(wm, tmat);
  34649. }
  34650. else {
  34651. tmat = this.getAbsoluteTransform();
  34652. }
  34653. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34654. };
  34655. /**
  34656. * Get the local position of a point that is in world space.
  34657. * @param position The world position
  34658. * @param mesh The mesh that this bone is attached to.
  34659. * @returns The local position
  34660. */
  34661. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  34662. var result = BABYLON.Vector3.Zero();
  34663. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  34664. return result;
  34665. };
  34666. /**
  34667. * Get the local position of a point that is in world space and copy it to the result param.
  34668. * @param position The world position
  34669. * @param mesh The mesh that this bone is attached to.
  34670. * @param result The vector3 that the local position should be copied to.
  34671. */
  34672. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  34673. var wm;
  34674. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  34675. if (mesh) {
  34676. wm = mesh.getWorldMatrix();
  34677. }
  34678. this._skeleton.computeAbsoluteTransforms();
  34679. var tmat = BABYLON.Tmp.Matrix[0];
  34680. tmat.copyFrom(this.getAbsoluteTransform());
  34681. if (mesh) {
  34682. tmat.multiplyToRef(wm, tmat);
  34683. }
  34684. tmat.invert();
  34685. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  34686. };
  34687. return Bone;
  34688. }(BABYLON.Node));
  34689. BABYLON.Bone = Bone;
  34690. })(BABYLON || (BABYLON = {}));
  34691. //# sourceMappingURL=babylon.bone.js.map
  34692. var BABYLON;
  34693. (function (BABYLON) {
  34694. var BoneIKController = (function () {
  34695. function BoneIKController(mesh, bone, options) {
  34696. this.targetPosition = BABYLON.Vector3.Zero();
  34697. this.poleTargetPosition = BABYLON.Vector3.Zero();
  34698. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  34699. this.poleAngle = 0;
  34700. this.slerpAmount = 1;
  34701. this._bone1Quat = BABYLON.Quaternion.Identity();
  34702. this._bone1Mat = BABYLON.Matrix.Identity();
  34703. this._bone2Ang = Math.PI;
  34704. this._maxAngle = Math.PI;
  34705. this._rightHandedSystem = false;
  34706. this._bendAxis = BABYLON.Vector3.Right();
  34707. this._slerping = false;
  34708. this._adjustRoll = 0;
  34709. this._bone2 = bone;
  34710. this._bone1 = bone.getParent();
  34711. this.mesh = mesh;
  34712. var bonePos = bone.getPosition();
  34713. if (bone.getAbsoluteTransform().determinant() > 0) {
  34714. this._rightHandedSystem = true;
  34715. this._bendAxis.x = 0;
  34716. this._bendAxis.y = 0;
  34717. this._bendAxis.z = -1;
  34718. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  34719. this._adjustRoll = Math.PI * .5;
  34720. this._bendAxis.z = 1;
  34721. }
  34722. }
  34723. if (this._bone1.length) {
  34724. var boneScale1 = this._bone1.getScale();
  34725. var boneScale2 = this._bone2.getScale();
  34726. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  34727. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  34728. }
  34729. else if (this._bone1.children[0]) {
  34730. mesh.computeWorldMatrix(true);
  34731. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  34732. var pos2 = this._bone2.getAbsolutePosition(mesh);
  34733. var pos3 = this._bone1.getAbsolutePosition(mesh);
  34734. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  34735. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  34736. }
  34737. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  34738. this.maxAngle = Math.PI;
  34739. if (options) {
  34740. if (options.targetMesh) {
  34741. this.targetMesh = options.targetMesh;
  34742. this.targetMesh.computeWorldMatrix(true);
  34743. }
  34744. if (options.poleTargetMesh) {
  34745. this.poleTargetMesh = options.poleTargetMesh;
  34746. this.poleTargetMesh.computeWorldMatrix(true);
  34747. }
  34748. else if (options.poleTargetBone) {
  34749. this.poleTargetBone = options.poleTargetBone;
  34750. }
  34751. else if (this._bone1.getParent()) {
  34752. this.poleTargetBone = this._bone1.getParent();
  34753. }
  34754. if (options.poleTargetLocalOffset) {
  34755. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  34756. }
  34757. if (options.poleAngle) {
  34758. this.poleAngle = options.poleAngle;
  34759. }
  34760. if (options.bendAxis) {
  34761. this._bendAxis.copyFrom(options.bendAxis);
  34762. }
  34763. if (options.maxAngle) {
  34764. this.maxAngle = options.maxAngle;
  34765. }
  34766. if (options.slerpAmount) {
  34767. this.slerpAmount = options.slerpAmount;
  34768. }
  34769. }
  34770. }
  34771. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  34772. get: function () {
  34773. return this._maxAngle;
  34774. },
  34775. set: function (value) {
  34776. this._setMaxAngle(value);
  34777. },
  34778. enumerable: true,
  34779. configurable: true
  34780. });
  34781. BoneIKController.prototype._setMaxAngle = function (ang) {
  34782. if (ang < 0) {
  34783. ang = 0;
  34784. }
  34785. if (ang > Math.PI || ang == undefined) {
  34786. ang = Math.PI;
  34787. }
  34788. this._maxAngle = ang;
  34789. var a = this._bone1Length;
  34790. var b = this._bone2Length;
  34791. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  34792. };
  34793. BoneIKController.prototype.update = function () {
  34794. var bone1 = this._bone1;
  34795. var target = this.targetPosition;
  34796. var poleTarget = this.poleTargetPosition;
  34797. var mat1 = BoneIKController._tmpMats[0];
  34798. var mat2 = BoneIKController._tmpMats[1];
  34799. if (this.targetMesh) {
  34800. target.copyFrom(this.targetMesh.getAbsolutePosition());
  34801. }
  34802. if (this.poleTargetBone) {
  34803. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  34804. }
  34805. else if (this.poleTargetMesh) {
  34806. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  34807. }
  34808. var bonePos = BoneIKController._tmpVecs[0];
  34809. var zaxis = BoneIKController._tmpVecs[1];
  34810. var xaxis = BoneIKController._tmpVecs[2];
  34811. var yaxis = BoneIKController._tmpVecs[3];
  34812. var upAxis = BoneIKController._tmpVecs[4];
  34813. var _tmpQuat = BoneIKController._tmpQuat;
  34814. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  34815. poleTarget.subtractToRef(bonePos, upAxis);
  34816. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  34817. upAxis.y = 1;
  34818. }
  34819. else {
  34820. upAxis.normalize();
  34821. }
  34822. target.subtractToRef(bonePos, yaxis);
  34823. yaxis.normalize();
  34824. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  34825. zaxis.normalize();
  34826. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  34827. xaxis.normalize();
  34828. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  34829. var a = this._bone1Length;
  34830. var b = this._bone2Length;
  34831. var c = BABYLON.Vector3.Distance(bonePos, target);
  34832. if (this._maxReach > 0) {
  34833. c = Math.min(this._maxReach, c);
  34834. }
  34835. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  34836. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  34837. if (acosa > 1) {
  34838. acosa = 1;
  34839. }
  34840. if (acosb > 1) {
  34841. acosb = 1;
  34842. }
  34843. if (acosa < -1) {
  34844. acosa = -1;
  34845. }
  34846. if (acosb < -1) {
  34847. acosb = -1;
  34848. }
  34849. var angA = Math.acos(acosa);
  34850. var angB = Math.acos(acosb);
  34851. var angC = -angA - angB;
  34852. if (this._rightHandedSystem) {
  34853. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  34854. mat2.multiplyToRef(mat1, mat1);
  34855. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  34856. mat2.multiplyToRef(mat1, mat1);
  34857. }
  34858. else {
  34859. var _tmpVec = BoneIKController._tmpVecs[5];
  34860. _tmpVec.copyFrom(this._bendAxis);
  34861. _tmpVec.x *= -1;
  34862. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  34863. mat2.multiplyToRef(mat1, mat1);
  34864. }
  34865. if (this.poleAngle) {
  34866. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  34867. mat1.multiplyToRef(mat2, mat1);
  34868. }
  34869. if (this.slerpAmount < 1) {
  34870. if (!this._slerping) {
  34871. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  34872. }
  34873. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  34874. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  34875. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  34876. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  34877. this._slerping = true;
  34878. }
  34879. else {
  34880. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  34881. this._bone1Mat.copyFrom(mat1);
  34882. this._slerping = false;
  34883. }
  34884. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  34885. this._bone2Ang = angC;
  34886. };
  34887. return BoneIKController;
  34888. }());
  34889. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  34890. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  34891. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  34892. BABYLON.BoneIKController = BoneIKController;
  34893. })(BABYLON || (BABYLON = {}));
  34894. //# sourceMappingURL=babylon.boneIKController.js.map
  34895. var BABYLON;
  34896. (function (BABYLON) {
  34897. var BoneLookController = (function () {
  34898. /**
  34899. * Create a BoneLookController
  34900. * @param mesh the mesh that the bone belongs to
  34901. * @param bone the bone that will be looking to the target
  34902. * @param target the target Vector3 to look at
  34903. * @param settings optional settings:
  34904. * - maxYaw: the maximum angle the bone will yaw to
  34905. * - minYaw: the minimum angle the bone will yaw to
  34906. * - maxPitch: the maximum angle the bone will pitch to
  34907. * - minPitch: the minimum angle the bone will yaw to
  34908. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  34909. * - upAxis: the up axis of the coordinate system
  34910. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34911. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  34912. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  34913. * - adjustYaw: used to make an adjustment to the yaw of the bone
  34914. * - adjustPitch: used to make an adjustment to the pitch of the bone
  34915. * - adjustRoll: used to make an adjustment to the roll of the bone
  34916. **/
  34917. function BoneLookController(mesh, bone, target, options) {
  34918. /**
  34919. * The up axis of the coordinate system that is used when the bone is rotated.
  34920. */
  34921. this.upAxis = BABYLON.Vector3.Up();
  34922. /**
  34923. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  34924. */
  34925. this.upAxisSpace = BABYLON.Space.LOCAL;
  34926. /**
  34927. * Used to make an adjustment to the yaw of the bone.
  34928. */
  34929. this.adjustYaw = 0;
  34930. /**
  34931. * Used to make an adjustment to the pitch of the bone.
  34932. */
  34933. this.adjustPitch = 0;
  34934. /**
  34935. * Used to make an adjustment to the roll of the bone.
  34936. */
  34937. this.adjustRoll = 0;
  34938. /**
  34939. * 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).
  34940. */
  34941. this.slerpAmount = 1;
  34942. this._boneQuat = BABYLON.Quaternion.Identity();
  34943. this._slerping = false;
  34944. this._firstFrameSkipped = false;
  34945. this._fowardAxis = BABYLON.Vector3.Forward();
  34946. this.mesh = mesh;
  34947. this.bone = bone;
  34948. this.target = target;
  34949. if (options) {
  34950. if (options.adjustYaw) {
  34951. this.adjustYaw = options.adjustYaw;
  34952. }
  34953. if (options.adjustPitch) {
  34954. this.adjustPitch = options.adjustPitch;
  34955. }
  34956. if (options.adjustRoll) {
  34957. this.adjustRoll = options.adjustRoll;
  34958. }
  34959. if (options.maxYaw != null) {
  34960. this.maxYaw = options.maxYaw;
  34961. }
  34962. else {
  34963. this.maxYaw = Math.PI;
  34964. }
  34965. if (options.minYaw != null) {
  34966. this.minYaw = options.minYaw;
  34967. }
  34968. else {
  34969. this.minYaw = -Math.PI;
  34970. }
  34971. if (options.maxPitch != null) {
  34972. this.maxPitch = options.maxPitch;
  34973. }
  34974. else {
  34975. this.maxPitch = Math.PI;
  34976. }
  34977. if (options.minPitch != null) {
  34978. this.minPitch = options.minPitch;
  34979. }
  34980. else {
  34981. this.minPitch = -Math.PI;
  34982. }
  34983. if (options.slerpAmount != null) {
  34984. this.slerpAmount = options.slerpAmount;
  34985. }
  34986. if (options.upAxis != null) {
  34987. this.upAxis = options.upAxis;
  34988. }
  34989. if (options.upAxisSpace != null) {
  34990. this.upAxisSpace = options.upAxisSpace;
  34991. }
  34992. if (options.yawAxis != null || options.pitchAxis != null) {
  34993. var newYawAxis = BABYLON.Axis.Y;
  34994. var newPitchAxis = BABYLON.Axis.X;
  34995. if (options.yawAxis != null) {
  34996. newYawAxis = options.yawAxis.clone();
  34997. newYawAxis.normalize();
  34998. }
  34999. if (options.pitchAxis != null) {
  35000. newPitchAxis = options.pitchAxis.clone();
  35001. newPitchAxis.normalize();
  35002. }
  35003. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  35004. this._transformYawPitch = BABYLON.Matrix.Identity();
  35005. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  35006. this._transformYawPitchInv = this._transformYawPitch.clone();
  35007. this._transformYawPitch.invert();
  35008. }
  35009. }
  35010. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  35011. this.upAxisSpace = BABYLON.Space.LOCAL;
  35012. }
  35013. }
  35014. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  35015. /**
  35016. * Get/set the minimum yaw angle that the bone can look to.
  35017. */
  35018. get: function () {
  35019. return this._minYaw;
  35020. },
  35021. set: function (value) {
  35022. this._minYaw = value;
  35023. this._minYawSin = Math.sin(value);
  35024. this._minYawCos = Math.cos(value);
  35025. if (this._maxYaw != null) {
  35026. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  35027. this._yawRange = this._maxYaw - this._minYaw;
  35028. }
  35029. },
  35030. enumerable: true,
  35031. configurable: true
  35032. });
  35033. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  35034. /**
  35035. * Get/set the maximum yaw angle that the bone can look to.
  35036. */
  35037. get: function () {
  35038. return this._maxYaw;
  35039. },
  35040. set: function (value) {
  35041. this._maxYaw = value;
  35042. this._maxYawSin = Math.sin(value);
  35043. this._maxYawCos = Math.cos(value);
  35044. if (this._minYaw != null) {
  35045. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  35046. this._yawRange = this._maxYaw - this._minYaw;
  35047. }
  35048. },
  35049. enumerable: true,
  35050. configurable: true
  35051. });
  35052. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  35053. /**
  35054. * Get/set the minimum pitch angle that the bone can look to.
  35055. */
  35056. get: function () {
  35057. return this._minPitch;
  35058. },
  35059. set: function (value) {
  35060. this._minPitch = value;
  35061. this._minPitchTan = Math.tan(value);
  35062. },
  35063. enumerable: true,
  35064. configurable: true
  35065. });
  35066. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  35067. /**
  35068. * Get/set the maximum pitch angle that the bone can look to.
  35069. */
  35070. get: function () {
  35071. return this._maxPitch;
  35072. },
  35073. set: function (value) {
  35074. this._maxPitch = value;
  35075. this._maxPitchTan = Math.tan(value);
  35076. },
  35077. enumerable: true,
  35078. configurable: true
  35079. });
  35080. /**
  35081. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  35082. */
  35083. BoneLookController.prototype.update = function () {
  35084. //skip the first frame when slerping so that the mesh rotation is correct
  35085. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  35086. this._firstFrameSkipped = true;
  35087. return;
  35088. }
  35089. var bone = this.bone;
  35090. var bonePos = BoneLookController._tmpVecs[0];
  35091. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  35092. var target = this.target;
  35093. var _tmpMat1 = BoneLookController._tmpMats[0];
  35094. var _tmpMat2 = BoneLookController._tmpMats[1];
  35095. var mesh = this.mesh;
  35096. var parentBone = bone.getParent();
  35097. var upAxis = BoneLookController._tmpVecs[1];
  35098. upAxis.copyFrom(this.upAxis);
  35099. if (this.upAxisSpace == BABYLON.Space.BONE) {
  35100. if (this._transformYawPitch) {
  35101. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  35102. }
  35103. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  35104. }
  35105. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  35106. mesh.getDirectionToRef(upAxis, upAxis);
  35107. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  35108. upAxis.normalize();
  35109. }
  35110. }
  35111. var checkYaw = false;
  35112. var checkPitch = false;
  35113. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  35114. checkYaw = true;
  35115. }
  35116. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  35117. checkPitch = true;
  35118. }
  35119. if (checkYaw || checkPitch) {
  35120. var spaceMat = BoneLookController._tmpMats[2];
  35121. var spaceMatInv = BoneLookController._tmpMats[3];
  35122. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  35123. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  35124. }
  35125. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  35126. spaceMat.copyFrom(mesh.getWorldMatrix());
  35127. }
  35128. else {
  35129. var forwardAxis = BoneLookController._tmpVecs[2];
  35130. forwardAxis.copyFrom(this._fowardAxis);
  35131. if (this._transformYawPitch) {
  35132. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  35133. }
  35134. if (parentBone) {
  35135. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  35136. }
  35137. else {
  35138. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  35139. }
  35140. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  35141. rightAxis.normalize();
  35142. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  35143. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  35144. }
  35145. spaceMat.invertToRef(spaceMatInv);
  35146. var xzlen;
  35147. if (checkPitch) {
  35148. var localTarget = BoneLookController._tmpVecs[3];
  35149. target.subtractToRef(bonePos, localTarget);
  35150. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35151. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35152. var pitch = Math.atan2(localTarget.y, xzlen);
  35153. var newPitch = pitch;
  35154. if (pitch > this._maxPitch) {
  35155. localTarget.y = this._maxPitchTan * xzlen;
  35156. newPitch = this._maxPitch;
  35157. }
  35158. else if (pitch < this._minPitch) {
  35159. localTarget.y = this._minPitchTan * xzlen;
  35160. newPitch = this._minPitch;
  35161. }
  35162. if (pitch != newPitch) {
  35163. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35164. localTarget.addInPlace(bonePos);
  35165. target = localTarget;
  35166. }
  35167. }
  35168. if (checkYaw) {
  35169. var localTarget = BoneLookController._tmpVecs[4];
  35170. target.subtractToRef(bonePos, localTarget);
  35171. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  35172. var yaw = Math.atan2(localTarget.x, localTarget.z);
  35173. var newYaw = yaw;
  35174. if (yaw > this._maxYaw || yaw < this._minYaw) {
  35175. if (xzlen == null) {
  35176. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35177. }
  35178. if (this._yawRange > Math.PI) {
  35179. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  35180. localTarget.z = this._maxYawCos * xzlen;
  35181. localTarget.x = this._maxYawSin * xzlen;
  35182. newYaw = this._maxYaw;
  35183. }
  35184. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  35185. localTarget.z = this._minYawCos * xzlen;
  35186. localTarget.x = this._minYawSin * xzlen;
  35187. newYaw = this._minYaw;
  35188. }
  35189. }
  35190. else {
  35191. if (yaw > this._maxYaw) {
  35192. localTarget.z = this._maxYawCos * xzlen;
  35193. localTarget.x = this._maxYawSin * xzlen;
  35194. newYaw = this._maxYaw;
  35195. }
  35196. else if (yaw < this._minYaw) {
  35197. localTarget.z = this._minYawCos * xzlen;
  35198. localTarget.x = this._minYawSin * xzlen;
  35199. newYaw = this._minYaw;
  35200. }
  35201. }
  35202. }
  35203. if (this._slerping && this._yawRange > Math.PI) {
  35204. //are we going to be crossing into the min/max region?
  35205. var boneFwd = BoneLookController._tmpVecs[8];
  35206. boneFwd.copyFrom(BABYLON.Axis.Z);
  35207. if (this._transformYawPitch) {
  35208. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  35209. }
  35210. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  35211. this._boneQuat.toRotationMatrix(boneRotMat);
  35212. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  35213. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  35214. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  35215. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  35216. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  35217. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  35218. if (angBtwTar > angBtwMidYaw) {
  35219. if (xzlen == null) {
  35220. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  35221. }
  35222. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  35223. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  35224. if (angBtwMin < angBtwMax) {
  35225. newYaw = boneYaw + Math.PI * .75;
  35226. localTarget.z = Math.cos(newYaw) * xzlen;
  35227. localTarget.x = Math.sin(newYaw) * xzlen;
  35228. }
  35229. else {
  35230. newYaw = boneYaw - Math.PI * .75;
  35231. localTarget.z = Math.cos(newYaw) * xzlen;
  35232. localTarget.x = Math.sin(newYaw) * xzlen;
  35233. }
  35234. }
  35235. }
  35236. if (yaw != newYaw) {
  35237. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  35238. localTarget.addInPlace(bonePos);
  35239. target = localTarget;
  35240. }
  35241. }
  35242. }
  35243. var zaxis = BoneLookController._tmpVecs[5];
  35244. var xaxis = BoneLookController._tmpVecs[6];
  35245. var yaxis = BoneLookController._tmpVecs[7];
  35246. var _tmpQuat = BoneLookController._tmpQuat;
  35247. target.subtractToRef(bonePos, zaxis);
  35248. zaxis.normalize();
  35249. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  35250. xaxis.normalize();
  35251. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  35252. yaxis.normalize();
  35253. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  35254. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  35255. return;
  35256. }
  35257. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  35258. return;
  35259. }
  35260. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  35261. return;
  35262. }
  35263. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  35264. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  35265. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  35266. }
  35267. if (this.slerpAmount < 1) {
  35268. if (!this._slerping) {
  35269. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  35270. }
  35271. if (this._transformYawPitch) {
  35272. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35273. }
  35274. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  35275. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  35276. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  35277. this._slerping = true;
  35278. }
  35279. else {
  35280. if (this._transformYawPitch) {
  35281. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  35282. }
  35283. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  35284. this._slerping = false;
  35285. }
  35286. };
  35287. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  35288. var angDiff = ang2 - ang1;
  35289. angDiff %= Math.PI * 2;
  35290. if (angDiff > Math.PI) {
  35291. angDiff -= Math.PI * 2;
  35292. }
  35293. else if (angDiff < -Math.PI) {
  35294. angDiff += Math.PI * 2;
  35295. }
  35296. return angDiff;
  35297. };
  35298. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  35299. ang1 %= (2 * Math.PI);
  35300. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35301. ang2 %= (2 * Math.PI);
  35302. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35303. var ab = 0;
  35304. if (ang1 < ang2) {
  35305. ab = ang2 - ang1;
  35306. }
  35307. else {
  35308. ab = ang1 - ang2;
  35309. }
  35310. if (ab > Math.PI) {
  35311. ab = Math.PI * 2 - ab;
  35312. }
  35313. return ab;
  35314. };
  35315. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  35316. ang %= (2 * Math.PI);
  35317. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  35318. ang1 %= (2 * Math.PI);
  35319. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  35320. ang2 %= (2 * Math.PI);
  35321. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  35322. if (ang1 < ang2) {
  35323. if (ang > ang1 && ang < ang2) {
  35324. return true;
  35325. }
  35326. }
  35327. else {
  35328. if (ang > ang2 && ang < ang1) {
  35329. return true;
  35330. }
  35331. }
  35332. return false;
  35333. };
  35334. return BoneLookController;
  35335. }());
  35336. 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()];
  35337. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  35338. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  35339. BABYLON.BoneLookController = BoneLookController;
  35340. })(BABYLON || (BABYLON = {}));
  35341. //# sourceMappingURL=babylon.boneLookController.js.map
  35342. var BABYLON;
  35343. (function (BABYLON) {
  35344. var Skeleton = (function () {
  35345. function Skeleton(name, id, scene) {
  35346. this.name = name;
  35347. this.id = id;
  35348. this.bones = new Array();
  35349. this.needInitialSkinMatrix = false;
  35350. this._isDirty = true;
  35351. this._meshesWithPoseMatrix = new Array();
  35352. this._identity = BABYLON.Matrix.Identity();
  35353. this._ranges = {};
  35354. this._lastAbsoluteTransformsUpdateId = -1;
  35355. // Events
  35356. /**
  35357. * An event triggered before computing the skeleton's matrices
  35358. * @type {BABYLON.Observable}
  35359. */
  35360. this.onBeforeComputeObservable = new BABYLON.Observable();
  35361. this.bones = [];
  35362. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35363. scene.skeletons.push(this);
  35364. //make sure it will recalculate the matrix next time prepare is called.
  35365. this._isDirty = true;
  35366. }
  35367. // Members
  35368. Skeleton.prototype.getTransformMatrices = function (mesh) {
  35369. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  35370. return mesh._bonesTransformMatrices;
  35371. }
  35372. if (!this._transformMatrices) {
  35373. this.prepare();
  35374. }
  35375. return this._transformMatrices;
  35376. };
  35377. Skeleton.prototype.getScene = function () {
  35378. return this._scene;
  35379. };
  35380. // Methods
  35381. /**
  35382. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  35383. */
  35384. Skeleton.prototype.toString = function (fullDetails) {
  35385. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  35386. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  35387. if (fullDetails) {
  35388. ret += ", Ranges: {";
  35389. var first = true;
  35390. for (var name_1 in this._ranges) {
  35391. if (first) {
  35392. ret += ", ";
  35393. first = false;
  35394. }
  35395. ret += name_1;
  35396. }
  35397. ret += "}";
  35398. }
  35399. return ret;
  35400. };
  35401. /**
  35402. * Get bone's index searching by name
  35403. * @param {string} name is bone's name to search for
  35404. * @return {number} Indice of the bone. Returns -1 if not found
  35405. */
  35406. Skeleton.prototype.getBoneIndexByName = function (name) {
  35407. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  35408. if (this.bones[boneIndex].name === name) {
  35409. return boneIndex;
  35410. }
  35411. }
  35412. return -1;
  35413. };
  35414. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  35415. // check name not already in use
  35416. if (!this._ranges[name]) {
  35417. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  35418. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35419. if (this.bones[i].animations[0]) {
  35420. this.bones[i].animations[0].createRange(name, from, to);
  35421. }
  35422. }
  35423. }
  35424. };
  35425. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  35426. if (deleteFrames === void 0) { deleteFrames = true; }
  35427. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35428. if (this.bones[i].animations[0]) {
  35429. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  35430. }
  35431. }
  35432. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  35433. };
  35434. Skeleton.prototype.getAnimationRange = function (name) {
  35435. return this._ranges[name];
  35436. };
  35437. /**
  35438. * Returns as an Array, all AnimationRanges defined on this skeleton
  35439. */
  35440. Skeleton.prototype.getAnimationRanges = function () {
  35441. var animationRanges = [];
  35442. var name;
  35443. var i = 0;
  35444. for (name in this._ranges) {
  35445. animationRanges[i] = this._ranges[name];
  35446. i++;
  35447. }
  35448. return animationRanges;
  35449. };
  35450. /**
  35451. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  35452. */
  35453. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  35454. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  35455. if (this._ranges[name] || !source.getAnimationRange(name)) {
  35456. return false;
  35457. }
  35458. var ret = true;
  35459. var frameOffset = this._getHighestAnimationFrame() + 1;
  35460. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  35461. var boneDict = {};
  35462. var sourceBones = source.bones;
  35463. var nBones;
  35464. var i;
  35465. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  35466. boneDict[sourceBones[i].name] = sourceBones[i];
  35467. }
  35468. if (this.bones.length !== sourceBones.length) {
  35469. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  35470. ret = false;
  35471. }
  35472. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  35473. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  35474. var boneName = this.bones[i].name;
  35475. var sourceBone = boneDict[boneName];
  35476. if (sourceBone) {
  35477. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  35478. }
  35479. else {
  35480. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  35481. ret = false;
  35482. }
  35483. }
  35484. // do not call createAnimationRange(), since it also is done to bones, which was already done
  35485. var range = source.getAnimationRange(name);
  35486. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  35487. return ret;
  35488. };
  35489. Skeleton.prototype.returnToRest = function () {
  35490. for (var index = 0; index < this.bones.length; index++) {
  35491. this.bones[index].returnToRest();
  35492. }
  35493. };
  35494. Skeleton.prototype._getHighestAnimationFrame = function () {
  35495. var ret = 0;
  35496. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  35497. if (this.bones[i].animations[0]) {
  35498. var highest = this.bones[i].animations[0].getHighestFrame();
  35499. if (ret < highest) {
  35500. ret = highest;
  35501. }
  35502. }
  35503. }
  35504. return ret;
  35505. };
  35506. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  35507. var range = this.getAnimationRange(name);
  35508. if (!range) {
  35509. return null;
  35510. }
  35511. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  35512. };
  35513. Skeleton.prototype._markAsDirty = function () {
  35514. this._isDirty = true;
  35515. };
  35516. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  35517. this._meshesWithPoseMatrix.push(mesh);
  35518. };
  35519. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  35520. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  35521. if (index > -1) {
  35522. this._meshesWithPoseMatrix.splice(index, 1);
  35523. }
  35524. };
  35525. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  35526. this.onBeforeComputeObservable.notifyObservers(this);
  35527. for (var index = 0; index < this.bones.length; index++) {
  35528. var bone = this.bones[index];
  35529. var parentBone = bone.getParent();
  35530. if (parentBone) {
  35531. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  35532. }
  35533. else {
  35534. if (initialSkinMatrix) {
  35535. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  35536. }
  35537. else {
  35538. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  35539. }
  35540. }
  35541. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  35542. }
  35543. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  35544. };
  35545. Skeleton.prototype.prepare = function () {
  35546. if (!this._isDirty) {
  35547. return;
  35548. }
  35549. if (this.needInitialSkinMatrix) {
  35550. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  35551. var mesh = this._meshesWithPoseMatrix[index];
  35552. var poseMatrix = mesh.getPoseMatrix();
  35553. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  35554. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35555. }
  35556. if (this._synchronizedWithMesh !== mesh) {
  35557. this._synchronizedWithMesh = mesh;
  35558. // Prepare bones
  35559. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  35560. var bone = this.bones[boneIndex];
  35561. if (!bone.getParent()) {
  35562. var matrix = bone.getBaseMatrix();
  35563. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  35564. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  35565. }
  35566. }
  35567. }
  35568. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  35569. }
  35570. }
  35571. else {
  35572. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  35573. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  35574. }
  35575. this._computeTransformMatrices(this._transformMatrices, null);
  35576. }
  35577. this._isDirty = false;
  35578. this._scene._activeBones.addCount(this.bones.length, false);
  35579. };
  35580. Skeleton.prototype.getAnimatables = function () {
  35581. if (!this._animatables || this._animatables.length !== this.bones.length) {
  35582. this._animatables = [];
  35583. for (var index = 0; index < this.bones.length; index++) {
  35584. this._animatables.push(this.bones[index]);
  35585. }
  35586. }
  35587. return this._animatables;
  35588. };
  35589. Skeleton.prototype.clone = function (name, id) {
  35590. var result = new Skeleton(name, id || name, this._scene);
  35591. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35592. for (var index = 0; index < this.bones.length; index++) {
  35593. var source = this.bones[index];
  35594. var parentBone = null;
  35595. if (source.getParent()) {
  35596. var parentIndex = this.bones.indexOf(source.getParent());
  35597. parentBone = result.bones[parentIndex];
  35598. }
  35599. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  35600. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  35601. }
  35602. if (this._ranges) {
  35603. result._ranges = {};
  35604. for (var rangeName in this._ranges) {
  35605. result._ranges[rangeName] = this._ranges[rangeName].clone();
  35606. }
  35607. }
  35608. this._isDirty = true;
  35609. return result;
  35610. };
  35611. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  35612. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  35613. this.bones.forEach(function (bone) {
  35614. bone.animations.forEach(function (animation) {
  35615. animation.enableBlending = true;
  35616. animation.blendingSpeed = blendingSpeed;
  35617. });
  35618. });
  35619. };
  35620. Skeleton.prototype.dispose = function () {
  35621. this._meshesWithPoseMatrix = [];
  35622. // Animations
  35623. this.getScene().stopAnimation(this);
  35624. // Remove from scene
  35625. this.getScene().removeSkeleton(this);
  35626. };
  35627. Skeleton.prototype.serialize = function () {
  35628. var serializationObject = {};
  35629. serializationObject.name = this.name;
  35630. serializationObject.id = this.id;
  35631. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  35632. serializationObject.bones = [];
  35633. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  35634. for (var index = 0; index < this.bones.length; index++) {
  35635. var bone = this.bones[index];
  35636. var serializedBone = {
  35637. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  35638. name: bone.name,
  35639. matrix: bone.getBaseMatrix().toArray(),
  35640. rest: bone.getRestPose().toArray()
  35641. };
  35642. serializationObject.bones.push(serializedBone);
  35643. if (bone.length) {
  35644. serializedBone.length = bone.length;
  35645. }
  35646. if (bone.animations && bone.animations.length > 0) {
  35647. serializedBone.animation = bone.animations[0].serialize();
  35648. }
  35649. serializationObject.ranges = [];
  35650. for (var name in this._ranges) {
  35651. var range = {};
  35652. range.name = name;
  35653. range.from = this._ranges[name].from;
  35654. range.to = this._ranges[name].to;
  35655. serializationObject.ranges.push(range);
  35656. }
  35657. }
  35658. return serializationObject;
  35659. };
  35660. Skeleton.Parse = function (parsedSkeleton, scene) {
  35661. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  35662. if (parsedSkeleton.dimensionsAtRest) {
  35663. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  35664. }
  35665. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  35666. var index;
  35667. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  35668. var parsedBone = parsedSkeleton.bones[index];
  35669. var parentBone = null;
  35670. if (parsedBone.parentBoneIndex > -1) {
  35671. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  35672. }
  35673. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  35674. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  35675. if (parsedBone.length) {
  35676. bone.length = parsedBone.length;
  35677. }
  35678. if (parsedBone.animation) {
  35679. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  35680. }
  35681. }
  35682. // placed after bones, so createAnimationRange can cascade down
  35683. if (parsedSkeleton.ranges) {
  35684. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  35685. var data = parsedSkeleton.ranges[index];
  35686. skeleton.createAnimationRange(data.name, data.from, data.to);
  35687. }
  35688. }
  35689. return skeleton;
  35690. };
  35691. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  35692. if (forceUpdate === void 0) { forceUpdate = false; }
  35693. var renderId = this._scene.getRenderId();
  35694. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  35695. this.bones[0].computeAbsoluteTransforms();
  35696. this._lastAbsoluteTransformsUpdateId = renderId;
  35697. }
  35698. };
  35699. Skeleton.prototype.getPoseMatrix = function () {
  35700. var poseMatrix;
  35701. if (this._meshesWithPoseMatrix.length > 0) {
  35702. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  35703. }
  35704. return poseMatrix;
  35705. };
  35706. return Skeleton;
  35707. }());
  35708. BABYLON.Skeleton = Skeleton;
  35709. })(BABYLON || (BABYLON = {}));
  35710. //# sourceMappingURL=babylon.skeleton.js.map
  35711. var BABYLON;
  35712. (function (BABYLON) {
  35713. var PostProcess = (function () {
  35714. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  35715. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  35716. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  35717. this.name = name;
  35718. this.width = -1;
  35719. this.height = -1;
  35720. /*
  35721. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  35722. Can only be used on a single postprocess or on the last one of a chain.
  35723. */
  35724. this.enablePixelPerfectMode = false;
  35725. this.samples = 1;
  35726. this._reusable = false;
  35727. this._textures = new BABYLON.SmartArray(2);
  35728. this._currentRenderTextureInd = 0;
  35729. this._scaleRatio = new BABYLON.Vector2(1, 1);
  35730. // Events
  35731. /**
  35732. * An event triggered when the postprocess is activated.
  35733. * @type {BABYLON.Observable}
  35734. */
  35735. this.onActivateObservable = new BABYLON.Observable();
  35736. /**
  35737. * An event triggered when the postprocess changes its size.
  35738. * @type {BABYLON.Observable}
  35739. */
  35740. this.onSizeChangedObservable = new BABYLON.Observable();
  35741. /**
  35742. * An event triggered when the postprocess applies its effect.
  35743. * @type {BABYLON.Observable}
  35744. */
  35745. this.onApplyObservable = new BABYLON.Observable();
  35746. /**
  35747. * An event triggered before rendering the postprocess
  35748. * @type {BABYLON.Observable}
  35749. */
  35750. this.onBeforeRenderObservable = new BABYLON.Observable();
  35751. /**
  35752. * An event triggered after rendering the postprocess
  35753. * @type {BABYLON.Observable}
  35754. */
  35755. this.onAfterRenderObservable = new BABYLON.Observable();
  35756. if (camera != null) {
  35757. this._camera = camera;
  35758. this._scene = camera.getScene();
  35759. camera.attachPostProcess(this);
  35760. this._engine = this._scene.getEngine();
  35761. }
  35762. else {
  35763. this._engine = engine;
  35764. }
  35765. this._options = options;
  35766. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  35767. this._reusable = reusable || false;
  35768. this._textureType = textureType;
  35769. this._samplers = samplers || [];
  35770. this._samplers.push("textureSampler");
  35771. this._fragmentUrl = fragmentUrl;
  35772. this._parameters = parameters || [];
  35773. this._parameters.push("scale");
  35774. this.updateEffect(defines);
  35775. }
  35776. Object.defineProperty(PostProcess.prototype, "onActivate", {
  35777. set: function (callback) {
  35778. if (this._onActivateObserver) {
  35779. this.onActivateObservable.remove(this._onActivateObserver);
  35780. }
  35781. this._onActivateObserver = this.onActivateObservable.add(callback);
  35782. },
  35783. enumerable: true,
  35784. configurable: true
  35785. });
  35786. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  35787. set: function (callback) {
  35788. if (this._onSizeChangedObserver) {
  35789. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  35790. }
  35791. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  35792. },
  35793. enumerable: true,
  35794. configurable: true
  35795. });
  35796. Object.defineProperty(PostProcess.prototype, "onApply", {
  35797. set: function (callback) {
  35798. if (this._onApplyObserver) {
  35799. this.onApplyObservable.remove(this._onApplyObserver);
  35800. }
  35801. this._onApplyObserver = this.onApplyObservable.add(callback);
  35802. },
  35803. enumerable: true,
  35804. configurable: true
  35805. });
  35806. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  35807. set: function (callback) {
  35808. if (this._onBeforeRenderObserver) {
  35809. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  35810. }
  35811. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  35812. },
  35813. enumerable: true,
  35814. configurable: true
  35815. });
  35816. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  35817. set: function (callback) {
  35818. if (this._onAfterRenderObserver) {
  35819. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  35820. }
  35821. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  35822. },
  35823. enumerable: true,
  35824. configurable: true
  35825. });
  35826. PostProcess.prototype.updateEffect = function (defines) {
  35827. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  35828. };
  35829. PostProcess.prototype.isReusable = function () {
  35830. return this._reusable;
  35831. };
  35832. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  35833. PostProcess.prototype.markTextureDirty = function () {
  35834. this.width = -1;
  35835. };
  35836. PostProcess.prototype.activate = function (camera, sourceTexture) {
  35837. var _this = this;
  35838. camera = camera || this._camera;
  35839. var scene = camera.getScene();
  35840. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  35841. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  35842. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  35843. var desiredWidth = this._options.width || requiredWidth;
  35844. var desiredHeight = this._options.height || requiredHeight;
  35845. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  35846. if (!this._options.width) {
  35847. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  35848. }
  35849. if (!this._options.height) {
  35850. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  35851. }
  35852. }
  35853. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  35854. if (this._textures.length > 0) {
  35855. for (var i = 0; i < this._textures.length; i++) {
  35856. this._engine._releaseTexture(this._textures.data[i]);
  35857. }
  35858. this._textures.reset();
  35859. }
  35860. this.width = desiredWidth;
  35861. this.height = desiredHeight;
  35862. var textureSize = { width: this.width, height: this.height };
  35863. var textureOptions = {
  35864. generateMipMaps: false,
  35865. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  35866. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  35867. samplingMode: this.renderTargetSamplingMode,
  35868. type: this._textureType
  35869. };
  35870. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35871. if (this._reusable) {
  35872. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  35873. }
  35874. this.onSizeChangedObservable.notifyObservers(this);
  35875. }
  35876. this._textures.forEach(function (texture) {
  35877. if (texture.samples !== _this.samples) {
  35878. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  35879. }
  35880. });
  35881. if (this.enablePixelPerfectMode) {
  35882. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  35883. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  35884. }
  35885. else {
  35886. this._scaleRatio.copyFromFloats(1, 1);
  35887. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  35888. }
  35889. this.onActivateObservable.notifyObservers(camera);
  35890. // Clear
  35891. if (this.clearColor) {
  35892. this._engine.clear(this.clearColor, true, true, true);
  35893. }
  35894. else {
  35895. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  35896. }
  35897. if (this._reusable) {
  35898. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  35899. }
  35900. };
  35901. Object.defineProperty(PostProcess.prototype, "isSupported", {
  35902. get: function () {
  35903. return this._effect.isSupported;
  35904. },
  35905. enumerable: true,
  35906. configurable: true
  35907. });
  35908. PostProcess.prototype.apply = function () {
  35909. // Check
  35910. if (!this._effect.isReady())
  35911. return null;
  35912. // States
  35913. this._engine.enableEffect(this._effect);
  35914. this._engine.setState(false);
  35915. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35916. this._engine.setDepthBuffer(false);
  35917. this._engine.setDepthWrite(false);
  35918. // Texture
  35919. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  35920. // Parameters
  35921. this._effect.setVector2("scale", this._scaleRatio);
  35922. this.onApplyObservable.notifyObservers(this._effect);
  35923. return this._effect;
  35924. };
  35925. PostProcess.prototype.dispose = function (camera) {
  35926. camera = camera || this._camera;
  35927. if (this._textures.length > 0) {
  35928. for (var i = 0; i < this._textures.length; i++) {
  35929. this._engine._releaseTexture(this._textures.data[i]);
  35930. }
  35931. }
  35932. this._textures.dispose();
  35933. if (!camera) {
  35934. return;
  35935. }
  35936. camera.detachPostProcess(this);
  35937. var index = camera._postProcesses.indexOf(this);
  35938. if (index === 0 && camera._postProcesses.length > 0) {
  35939. this._camera._postProcesses[0].markTextureDirty();
  35940. }
  35941. this.onActivateObservable.clear();
  35942. this.onAfterRenderObservable.clear();
  35943. this.onApplyObservable.clear();
  35944. this.onBeforeRenderObservable.clear();
  35945. this.onSizeChangedObservable.clear();
  35946. };
  35947. return PostProcess;
  35948. }());
  35949. BABYLON.PostProcess = PostProcess;
  35950. })(BABYLON || (BABYLON = {}));
  35951. //# sourceMappingURL=babylon.postProcess.js.map
  35952. var BABYLON;
  35953. (function (BABYLON) {
  35954. var PostProcessManager = (function () {
  35955. function PostProcessManager(scene) {
  35956. this._vertexBuffers = {};
  35957. this._scene = scene;
  35958. }
  35959. PostProcessManager.prototype._prepareBuffers = function () {
  35960. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  35961. return;
  35962. }
  35963. // VBO
  35964. var vertices = [];
  35965. vertices.push(1, 1);
  35966. vertices.push(-1, 1);
  35967. vertices.push(-1, -1);
  35968. vertices.push(1, -1);
  35969. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  35970. // Indices
  35971. var indices = [];
  35972. indices.push(0);
  35973. indices.push(1);
  35974. indices.push(2);
  35975. indices.push(0);
  35976. indices.push(2);
  35977. indices.push(3);
  35978. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  35979. };
  35980. // Methods
  35981. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  35982. var postProcesses = this._scene.activeCamera._postProcesses;
  35983. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  35984. return false;
  35985. }
  35986. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  35987. return true;
  35988. };
  35989. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  35990. var engine = this._scene.getEngine();
  35991. for (var index = 0; index < postProcesses.length; index++) {
  35992. if (index < postProcesses.length - 1) {
  35993. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  35994. }
  35995. else {
  35996. if (targetTexture) {
  35997. engine.bindFramebuffer(targetTexture);
  35998. }
  35999. else {
  36000. engine.restoreDefaultFramebuffer();
  36001. }
  36002. }
  36003. var pp = postProcesses[index];
  36004. var effect = pp.apply();
  36005. if (effect) {
  36006. pp.onBeforeRenderObservable.notifyObservers(effect);
  36007. // VBOs
  36008. this._prepareBuffers();
  36009. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36010. // Draw order
  36011. engine.draw(true, 0, 6);
  36012. pp.onAfterRenderObservable.notifyObservers(effect);
  36013. }
  36014. }
  36015. // Restore depth buffer
  36016. engine.setDepthBuffer(true);
  36017. engine.setDepthWrite(true);
  36018. };
  36019. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  36020. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  36021. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36022. return;
  36023. }
  36024. var engine = this._scene.getEngine();
  36025. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36026. if (index < len - 1) {
  36027. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36028. }
  36029. else {
  36030. if (targetTexture) {
  36031. engine.bindFramebuffer(targetTexture, faceIndex);
  36032. }
  36033. else {
  36034. engine.restoreDefaultFramebuffer();
  36035. }
  36036. }
  36037. if (doNotPresent) {
  36038. break;
  36039. }
  36040. var pp = postProcesses[index];
  36041. var effect = pp.apply();
  36042. if (effect) {
  36043. pp.onBeforeRenderObservable.notifyObservers(effect);
  36044. // VBOs
  36045. this._prepareBuffers();
  36046. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36047. // Draw order
  36048. engine.draw(true, 0, 6);
  36049. pp.onAfterRenderObservable.notifyObservers(effect);
  36050. }
  36051. }
  36052. // Restore depth buffer
  36053. engine.setDepthBuffer(true);
  36054. engine.setDepthWrite(true);
  36055. };
  36056. PostProcessManager.prototype.dispose = function () {
  36057. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36058. if (buffer) {
  36059. buffer.dispose();
  36060. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36061. }
  36062. if (this._indexBuffer) {
  36063. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36064. this._indexBuffer = null;
  36065. }
  36066. };
  36067. return PostProcessManager;
  36068. }());
  36069. BABYLON.PostProcessManager = PostProcessManager;
  36070. })(BABYLON || (BABYLON = {}));
  36071. //# sourceMappingURL=babylon.postProcessManager.js.map
  36072. var BABYLON;
  36073. (function (BABYLON) {
  36074. var PassPostProcess = (function (_super) {
  36075. __extends(PassPostProcess, _super);
  36076. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  36077. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  36078. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  36079. }
  36080. return PassPostProcess;
  36081. }(BABYLON.PostProcess));
  36082. BABYLON.PassPostProcess = PassPostProcess;
  36083. })(BABYLON || (BABYLON = {}));
  36084. //# sourceMappingURL=babylon.passPostProcess.js.map
  36085. var BABYLON;
  36086. (function (BABYLON) {
  36087. /**
  36088. * This is a holder class for the physics joint created by the physics plugin.
  36089. * It holds a set of functions to control the underlying joint.
  36090. */
  36091. var PhysicsJoint = (function () {
  36092. function PhysicsJoint(type, jointData) {
  36093. this.type = type;
  36094. this.jointData = jointData;
  36095. jointData.nativeParams = jointData.nativeParams || {};
  36096. }
  36097. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  36098. get: function () {
  36099. return this._physicsJoint;
  36100. },
  36101. set: function (newJoint) {
  36102. if (this._physicsJoint) {
  36103. //remove from the wolrd
  36104. }
  36105. this._physicsJoint = newJoint;
  36106. },
  36107. enumerable: true,
  36108. configurable: true
  36109. });
  36110. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  36111. set: function (physicsPlugin) {
  36112. this._physicsPlugin = physicsPlugin;
  36113. },
  36114. enumerable: true,
  36115. configurable: true
  36116. });
  36117. /**
  36118. * Execute a function that is physics-plugin specific.
  36119. * @param {Function} func the function that will be executed.
  36120. * It accepts two parameters: the physics world and the physics joint.
  36121. */
  36122. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  36123. func(this._physicsPlugin.world, this._physicsJoint);
  36124. };
  36125. return PhysicsJoint;
  36126. }());
  36127. //TODO check if the native joints are the same
  36128. //Joint Types
  36129. PhysicsJoint.DistanceJoint = 0;
  36130. PhysicsJoint.HingeJoint = 1;
  36131. PhysicsJoint.BallAndSocketJoint = 2;
  36132. PhysicsJoint.WheelJoint = 3;
  36133. PhysicsJoint.SliderJoint = 4;
  36134. //OIMO
  36135. PhysicsJoint.PrismaticJoint = 5;
  36136. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  36137. PhysicsJoint.UniversalJoint = 6;
  36138. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  36139. //Cannon
  36140. //Similar to a Ball-Joint. Different in params
  36141. PhysicsJoint.PointToPointJoint = 8;
  36142. //Cannon only at the moment
  36143. PhysicsJoint.SpringJoint = 9;
  36144. PhysicsJoint.LockJoint = 10;
  36145. BABYLON.PhysicsJoint = PhysicsJoint;
  36146. /**
  36147. * A class representing a physics distance joint.
  36148. */
  36149. var DistanceJoint = (function (_super) {
  36150. __extends(DistanceJoint, _super);
  36151. function DistanceJoint(jointData) {
  36152. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  36153. }
  36154. /**
  36155. * Update the predefined distance.
  36156. */
  36157. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  36158. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  36159. };
  36160. return DistanceJoint;
  36161. }(PhysicsJoint));
  36162. BABYLON.DistanceJoint = DistanceJoint;
  36163. var MotorEnabledJoint = (function (_super) {
  36164. __extends(MotorEnabledJoint, _super);
  36165. function MotorEnabledJoint(type, jointData) {
  36166. return _super.call(this, type, jointData) || this;
  36167. }
  36168. /**
  36169. * Set the motor values.
  36170. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36171. * @param {number} force the force to apply
  36172. * @param {number} maxForce max force for this motor.
  36173. */
  36174. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  36175. this._physicsPlugin.setMotor(this, force, maxForce);
  36176. };
  36177. /**
  36178. * Set the motor's limits.
  36179. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36180. */
  36181. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36182. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36183. };
  36184. return MotorEnabledJoint;
  36185. }(PhysicsJoint));
  36186. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  36187. /**
  36188. * This class represents a single hinge physics joint
  36189. */
  36190. var HingeJoint = (function (_super) {
  36191. __extends(HingeJoint, _super);
  36192. function HingeJoint(jointData) {
  36193. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  36194. }
  36195. /**
  36196. * Set the motor values.
  36197. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36198. * @param {number} force the force to apply
  36199. * @param {number} maxForce max force for this motor.
  36200. */
  36201. HingeJoint.prototype.setMotor = function (force, maxForce) {
  36202. this._physicsPlugin.setMotor(this, force, maxForce);
  36203. };
  36204. /**
  36205. * Set the motor's limits.
  36206. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36207. */
  36208. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  36209. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  36210. };
  36211. return HingeJoint;
  36212. }(MotorEnabledJoint));
  36213. BABYLON.HingeJoint = HingeJoint;
  36214. /**
  36215. * This class represents a dual hinge physics joint (same as wheel joint)
  36216. */
  36217. var Hinge2Joint = (function (_super) {
  36218. __extends(Hinge2Joint, _super);
  36219. function Hinge2Joint(jointData) {
  36220. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  36221. }
  36222. /**
  36223. * Set the motor values.
  36224. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36225. * @param {number} force the force to apply
  36226. * @param {number} maxForce max force for this motor.
  36227. * @param {motorIndex} the motor's index, 0 or 1.
  36228. */
  36229. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  36230. if (motorIndex === void 0) { motorIndex = 0; }
  36231. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  36232. };
  36233. /**
  36234. * Set the motor limits.
  36235. * Attention, this function is plugin specific. Engines won't react 100% the same.
  36236. * @param {number} upperLimit the upper limit
  36237. * @param {number} lowerLimit lower limit
  36238. * @param {motorIndex} the motor's index, 0 or 1.
  36239. */
  36240. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  36241. if (motorIndex === void 0) { motorIndex = 0; }
  36242. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  36243. };
  36244. return Hinge2Joint;
  36245. }(MotorEnabledJoint));
  36246. BABYLON.Hinge2Joint = Hinge2Joint;
  36247. })(BABYLON || (BABYLON = {}));
  36248. //# sourceMappingURL=babylon.physicsJoint.js.map
  36249. var BABYLON;
  36250. (function (BABYLON) {
  36251. var PhysicsImpostor = (function () {
  36252. function PhysicsImpostor(object, type, _options, _scene) {
  36253. if (_options === void 0) { _options = { mass: 0 }; }
  36254. var _this = this;
  36255. this.object = object;
  36256. this.type = type;
  36257. this._options = _options;
  36258. this._scene = _scene;
  36259. this._bodyUpdateRequired = false;
  36260. this._onBeforePhysicsStepCallbacks = new Array();
  36261. this._onAfterPhysicsStepCallbacks = new Array();
  36262. this._onPhysicsCollideCallbacks = [];
  36263. this._deltaPosition = BABYLON.Vector3.Zero();
  36264. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  36265. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  36266. /**
  36267. * this function is executed by the physics engine.
  36268. */
  36269. this.beforeStep = function () {
  36270. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  36271. //conjugate deltaRotation
  36272. if (_this._deltaRotationConjugated) {
  36273. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  36274. }
  36275. else {
  36276. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  36277. }
  36278. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  36279. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  36280. func(_this);
  36281. });
  36282. };
  36283. /**
  36284. * this function is executed by the physics engine.
  36285. */
  36286. this.afterStep = function () {
  36287. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  36288. func(_this);
  36289. });
  36290. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  36291. _this.object.position.addInPlace(_this._deltaPosition);
  36292. if (_this._deltaRotation) {
  36293. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  36294. }
  36295. };
  36296. /**
  36297. * Legacy collision detection event support
  36298. */
  36299. this.onCollideEvent = null;
  36300. //event and body object due to cannon's event-based architecture.
  36301. this.onCollide = function (e) {
  36302. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  36303. return;
  36304. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  36305. if (otherImpostor) {
  36306. // Legacy collision detection event support
  36307. if (_this.onCollideEvent) {
  36308. _this.onCollideEvent(_this, otherImpostor);
  36309. }
  36310. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  36311. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  36312. }).forEach(function (obj) {
  36313. obj.callback(_this, otherImpostor);
  36314. });
  36315. }
  36316. };
  36317. //sanity check!
  36318. if (!this.object) {
  36319. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  36320. return;
  36321. }
  36322. //legacy support for old syntax.
  36323. if (!this._scene && object.getScene) {
  36324. this._scene = object.getScene();
  36325. }
  36326. this._physicsEngine = this._scene.getPhysicsEngine();
  36327. if (!this._physicsEngine) {
  36328. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  36329. }
  36330. else {
  36331. //set the object's quaternion, if not set
  36332. if (!this.object.rotationQuaternion) {
  36333. if (this.object.rotation) {
  36334. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  36335. }
  36336. else {
  36337. this.object.rotationQuaternion = new BABYLON.Quaternion();
  36338. }
  36339. }
  36340. //default options params
  36341. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  36342. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  36343. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  36344. this._joints = [];
  36345. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  36346. if (!this.object.parent) {
  36347. this._init();
  36348. }
  36349. }
  36350. }
  36351. /**
  36352. * This function will completly initialize this impostor.
  36353. * It will create a new body - but only if this mesh has no parent.
  36354. * If it has, this impostor will not be used other than to define the impostor
  36355. * of the child mesh.
  36356. */
  36357. PhysicsImpostor.prototype._init = function () {
  36358. this._physicsEngine.removeImpostor(this);
  36359. this.physicsBody = null;
  36360. this._parent = this._parent || this._getPhysicsParent();
  36361. if (!this.parent) {
  36362. this._physicsEngine.addImpostor(this);
  36363. }
  36364. };
  36365. PhysicsImpostor.prototype._getPhysicsParent = function () {
  36366. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  36367. var parentMesh = this.object.parent;
  36368. return parentMesh.physicsImpostor;
  36369. }
  36370. return;
  36371. };
  36372. /**
  36373. * Should a new body be generated.
  36374. */
  36375. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  36376. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  36377. };
  36378. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  36379. this.forceUpdate();
  36380. };
  36381. /**
  36382. * Force a regeneration of this or the parent's impostor's body.
  36383. * Use under cautious - This will remove all joints already implemented.
  36384. */
  36385. PhysicsImpostor.prototype.forceUpdate = function () {
  36386. this._init();
  36387. if (this.parent) {
  36388. this.parent.forceUpdate();
  36389. }
  36390. };
  36391. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  36392. /*public get mesh(): AbstractMesh {
  36393. return this._mesh;
  36394. }*/
  36395. /**
  36396. * Gets the body that holds this impostor. Either its own, or its parent.
  36397. */
  36398. get: function () {
  36399. return this._parent ? this._parent.physicsBody : this._physicsBody;
  36400. },
  36401. /**
  36402. * Set the physics body. Used mainly by the physics engine/plugin
  36403. */
  36404. set: function (physicsBody) {
  36405. if (this._physicsBody) {
  36406. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  36407. }
  36408. this._physicsBody = physicsBody;
  36409. this.resetUpdateFlags();
  36410. },
  36411. enumerable: true,
  36412. configurable: true
  36413. });
  36414. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  36415. get: function () {
  36416. return this._parent;
  36417. },
  36418. set: function (value) {
  36419. this._parent = value;
  36420. },
  36421. enumerable: true,
  36422. configurable: true
  36423. });
  36424. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  36425. this._bodyUpdateRequired = false;
  36426. };
  36427. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  36428. if (this.object.getBoundingInfo) {
  36429. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  36430. return this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2).multiply(this.object.scaling);
  36431. }
  36432. else {
  36433. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  36434. }
  36435. };
  36436. PhysicsImpostor.prototype.getObjectCenter = function () {
  36437. if (this.object.getBoundingInfo) {
  36438. return this.object.getBoundingInfo().boundingBox.centerWorld;
  36439. }
  36440. else {
  36441. return this.object.position;
  36442. }
  36443. };
  36444. /**
  36445. * Get a specific parametes from the options parameter.
  36446. */
  36447. PhysicsImpostor.prototype.getParam = function (paramName) {
  36448. return this._options[paramName];
  36449. };
  36450. /**
  36451. * Sets a specific parameter in the options given to the physics plugin
  36452. */
  36453. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  36454. this._options[paramName] = value;
  36455. this._bodyUpdateRequired = true;
  36456. };
  36457. /**
  36458. * Specifically change the body's mass option. Won't recreate the physics body object
  36459. */
  36460. PhysicsImpostor.prototype.setMass = function (mass) {
  36461. if (this.getParam("mass") !== mass) {
  36462. this.setParam("mass", mass);
  36463. }
  36464. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  36465. };
  36466. PhysicsImpostor.prototype.getLinearVelocity = function () {
  36467. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  36468. };
  36469. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  36470. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  36471. };
  36472. PhysicsImpostor.prototype.getAngularVelocity = function () {
  36473. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  36474. };
  36475. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  36476. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  36477. };
  36478. /**
  36479. * Execute a function with the physics plugin native code.
  36480. * Provide a function the will have two variables - the world object and the physics body object.
  36481. */
  36482. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  36483. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  36484. };
  36485. /**
  36486. * Register a function that will be executed before the physics world is stepping forward.
  36487. */
  36488. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  36489. this._onBeforePhysicsStepCallbacks.push(func);
  36490. };
  36491. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  36492. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  36493. if (index > -1) {
  36494. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  36495. }
  36496. else {
  36497. BABYLON.Tools.Warn("Function to remove was not found");
  36498. }
  36499. };
  36500. /**
  36501. * Register a function that will be executed after the physics step
  36502. */
  36503. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  36504. this._onAfterPhysicsStepCallbacks.push(func);
  36505. };
  36506. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  36507. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  36508. if (index > -1) {
  36509. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  36510. }
  36511. else {
  36512. BABYLON.Tools.Warn("Function to remove was not found");
  36513. }
  36514. };
  36515. /**
  36516. * register a function that will be executed when this impostor collides against a different body.
  36517. */
  36518. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  36519. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36520. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  36521. };
  36522. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  36523. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  36524. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  36525. if (index > -1) {
  36526. this._onPhysicsCollideCallbacks.splice(index, 1);
  36527. }
  36528. else {
  36529. BABYLON.Tools.Warn("Function to remove was not found");
  36530. }
  36531. };
  36532. /**
  36533. * Apply a force
  36534. */
  36535. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  36536. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  36537. };
  36538. /**
  36539. * Apply an impulse
  36540. */
  36541. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  36542. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  36543. };
  36544. /**
  36545. * A help function to create a joint.
  36546. */
  36547. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  36548. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  36549. this.addJoint(otherImpostor, joint);
  36550. };
  36551. /**
  36552. * Add a joint to this impostor with a different impostor.
  36553. */
  36554. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  36555. this._joints.push({
  36556. otherImpostor: otherImpostor,
  36557. joint: joint
  36558. });
  36559. this._physicsEngine.addJoint(this, otherImpostor, joint);
  36560. };
  36561. /**
  36562. * Will keep this body still, in a sleep mode.
  36563. */
  36564. PhysicsImpostor.prototype.sleep = function () {
  36565. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  36566. };
  36567. /**
  36568. * Wake the body up.
  36569. */
  36570. PhysicsImpostor.prototype.wakeUp = function () {
  36571. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  36572. };
  36573. PhysicsImpostor.prototype.clone = function (newObject) {
  36574. if (!newObject)
  36575. return null;
  36576. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  36577. };
  36578. PhysicsImpostor.prototype.dispose = function () {
  36579. var _this = this;
  36580. //no dispose if no physics engine is available.
  36581. if (!this._physicsEngine) {
  36582. return;
  36583. }
  36584. this._joints.forEach(function (j) {
  36585. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  36586. });
  36587. //dispose the physics body
  36588. this._physicsEngine.removeImpostor(this);
  36589. if (this.parent) {
  36590. this.parent.forceUpdate();
  36591. }
  36592. else {
  36593. /*this._object.getChildMeshes().forEach(function(mesh) {
  36594. if (mesh.physicsImpostor) {
  36595. if (disposeChildren) {
  36596. mesh.physicsImpostor.dispose();
  36597. mesh.physicsImpostor = null;
  36598. }
  36599. }
  36600. })*/
  36601. }
  36602. };
  36603. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  36604. this._deltaPosition.copyFrom(position);
  36605. };
  36606. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  36607. if (!this._deltaRotation) {
  36608. this._deltaRotation = new BABYLON.Quaternion();
  36609. }
  36610. this._deltaRotation.copyFrom(rotation);
  36611. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  36612. };
  36613. return PhysicsImpostor;
  36614. }());
  36615. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  36616. //Impostor types
  36617. PhysicsImpostor.NoImpostor = 0;
  36618. PhysicsImpostor.SphereImpostor = 1;
  36619. PhysicsImpostor.BoxImpostor = 2;
  36620. PhysicsImpostor.PlaneImpostor = 3;
  36621. PhysicsImpostor.MeshImpostor = 4;
  36622. PhysicsImpostor.CylinderImpostor = 7;
  36623. PhysicsImpostor.ParticleImpostor = 8;
  36624. PhysicsImpostor.HeightmapImpostor = 9;
  36625. BABYLON.PhysicsImpostor = PhysicsImpostor;
  36626. })(BABYLON || (BABYLON = {}));
  36627. //# sourceMappingURL=babylon.physicsImpostor.js.map
  36628. var BABYLON;
  36629. (function (BABYLON) {
  36630. var PhysicsEngine = (function () {
  36631. function PhysicsEngine(gravity, _physicsPlugin) {
  36632. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  36633. this._physicsPlugin = _physicsPlugin;
  36634. //new methods and parameters
  36635. this._impostors = [];
  36636. this._joints = [];
  36637. if (!this._physicsPlugin.isSupported()) {
  36638. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  36639. + "Please make sure it is included.");
  36640. }
  36641. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  36642. this.setGravity(gravity);
  36643. this.setTimeStep();
  36644. }
  36645. PhysicsEngine.prototype.setGravity = function (gravity) {
  36646. this.gravity = gravity;
  36647. this._physicsPlugin.setGravity(this.gravity);
  36648. };
  36649. /**
  36650. * Set the time step of the physics engine.
  36651. * default is 1/60.
  36652. * To slow it down, enter 1/600 for example.
  36653. * To speed it up, 1/30
  36654. * @param {number} newTimeStep the new timestep to apply to this world.
  36655. */
  36656. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  36657. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  36658. this._physicsPlugin.setTimeStep(newTimeStep);
  36659. };
  36660. PhysicsEngine.prototype.dispose = function () {
  36661. this._impostors.forEach(function (impostor) {
  36662. impostor.dispose();
  36663. });
  36664. this._physicsPlugin.dispose();
  36665. };
  36666. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  36667. return this._physicsPlugin.name;
  36668. };
  36669. /**
  36670. * Adding a new impostor for the impostor tracking.
  36671. * This will be done by the impostor itself.
  36672. * @param {PhysicsImpostor} impostor the impostor to add
  36673. */
  36674. PhysicsEngine.prototype.addImpostor = function (impostor) {
  36675. impostor.uniqueId = this._impostors.push(impostor);
  36676. //if no parent, generate the body
  36677. if (!impostor.parent) {
  36678. this._physicsPlugin.generatePhysicsBody(impostor);
  36679. }
  36680. };
  36681. /**
  36682. * Remove an impostor from the engine.
  36683. * This impostor and its mesh will not longer be updated by the physics engine.
  36684. * @param {PhysicsImpostor} impostor the impostor to remove
  36685. */
  36686. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  36687. var index = this._impostors.indexOf(impostor);
  36688. if (index > -1) {
  36689. var removed = this._impostors.splice(index, 1);
  36690. //Is it needed?
  36691. if (removed.length) {
  36692. //this will also remove it from the world.
  36693. removed[0].physicsBody = null;
  36694. }
  36695. }
  36696. };
  36697. /**
  36698. * Add a joint to the physics engine
  36699. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  36700. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  36701. * @param {PhysicsJoint} the joint that will connect both impostors.
  36702. */
  36703. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  36704. var impostorJoint = {
  36705. mainImpostor: mainImpostor,
  36706. connectedImpostor: connectedImpostor,
  36707. joint: joint
  36708. };
  36709. joint.physicsPlugin = this._physicsPlugin;
  36710. this._joints.push(impostorJoint);
  36711. this._physicsPlugin.generateJoint(impostorJoint);
  36712. };
  36713. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  36714. var matchingJoints = this._joints.filter(function (impostorJoint) {
  36715. return (impostorJoint.connectedImpostor === connectedImpostor
  36716. && impostorJoint.joint === joint
  36717. && impostorJoint.mainImpostor === mainImpostor);
  36718. });
  36719. if (matchingJoints.length) {
  36720. this._physicsPlugin.removeJoint(matchingJoints[0]);
  36721. //TODO remove it from the list as well
  36722. }
  36723. };
  36724. /**
  36725. * Called by the scene. no need to call it.
  36726. */
  36727. PhysicsEngine.prototype._step = function (delta) {
  36728. var _this = this;
  36729. //check if any mesh has no body / requires an update
  36730. this._impostors.forEach(function (impostor) {
  36731. if (impostor.isBodyInitRequired()) {
  36732. _this._physicsPlugin.generatePhysicsBody(impostor);
  36733. }
  36734. });
  36735. if (delta > 0.1) {
  36736. delta = 0.1;
  36737. }
  36738. else if (delta <= 0) {
  36739. delta = 1.0 / 60.0;
  36740. }
  36741. this._physicsPlugin.executeStep(delta, this._impostors);
  36742. };
  36743. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  36744. return this._physicsPlugin;
  36745. };
  36746. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  36747. for (var i = 0; i < this._impostors.length; ++i) {
  36748. if (this._impostors[i].object === object) {
  36749. return this._impostors[i];
  36750. }
  36751. }
  36752. };
  36753. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  36754. for (var i = 0; i < this._impostors.length; ++i) {
  36755. if (this._impostors[i].physicsBody === body) {
  36756. return this._impostors[i];
  36757. }
  36758. }
  36759. };
  36760. return PhysicsEngine;
  36761. }());
  36762. // Statics
  36763. PhysicsEngine.Epsilon = 0.001;
  36764. BABYLON.PhysicsEngine = PhysicsEngine;
  36765. })(BABYLON || (BABYLON = {}));
  36766. //# sourceMappingURL=babylon.physicsEngine.js.map
  36767. var BABYLON;
  36768. (function (BABYLON) {
  36769. var VertexData = (function () {
  36770. function VertexData() {
  36771. }
  36772. VertexData.prototype.set = function (data, kind) {
  36773. switch (kind) {
  36774. case BABYLON.VertexBuffer.PositionKind:
  36775. this.positions = data;
  36776. break;
  36777. case BABYLON.VertexBuffer.NormalKind:
  36778. this.normals = data;
  36779. break;
  36780. case BABYLON.VertexBuffer.TangentKind:
  36781. this.tangents = data;
  36782. break;
  36783. case BABYLON.VertexBuffer.UVKind:
  36784. this.uvs = data;
  36785. break;
  36786. case BABYLON.VertexBuffer.UV2Kind:
  36787. this.uvs2 = data;
  36788. break;
  36789. case BABYLON.VertexBuffer.UV3Kind:
  36790. this.uvs3 = data;
  36791. break;
  36792. case BABYLON.VertexBuffer.UV4Kind:
  36793. this.uvs4 = data;
  36794. break;
  36795. case BABYLON.VertexBuffer.UV5Kind:
  36796. this.uvs5 = data;
  36797. break;
  36798. case BABYLON.VertexBuffer.UV6Kind:
  36799. this.uvs6 = data;
  36800. break;
  36801. case BABYLON.VertexBuffer.ColorKind:
  36802. this.colors = data;
  36803. break;
  36804. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36805. this.matricesIndices = data;
  36806. break;
  36807. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36808. this.matricesWeights = data;
  36809. break;
  36810. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36811. this.matricesIndicesExtra = data;
  36812. break;
  36813. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36814. this.matricesWeightsExtra = data;
  36815. break;
  36816. }
  36817. };
  36818. /**
  36819. * Associates the vertexData to the passed Mesh.
  36820. * Sets it as updatable or not (default `false`).
  36821. * Returns the VertexData.
  36822. */
  36823. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36824. this._applyTo(mesh, updatable);
  36825. return this;
  36826. };
  36827. /**
  36828. * Associates the vertexData to the passed Geometry.
  36829. * Sets it as updatable or not (default `false`).
  36830. * Returns the VertexData.
  36831. */
  36832. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36833. this._applyTo(geometry, updatable);
  36834. return this;
  36835. };
  36836. /**
  36837. * Updates the associated mesh.
  36838. * Returns the VertexData.
  36839. */
  36840. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36841. this._update(mesh);
  36842. return this;
  36843. };
  36844. /**
  36845. * Updates the associated geometry.
  36846. * Returns the VertexData.
  36847. */
  36848. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36849. this._update(geometry);
  36850. return this;
  36851. };
  36852. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36853. if (this.positions) {
  36854. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36855. }
  36856. if (this.normals) {
  36857. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36858. }
  36859. if (this.tangents) {
  36860. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36861. }
  36862. if (this.uvs) {
  36863. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36864. }
  36865. if (this.uvs2) {
  36866. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36867. }
  36868. if (this.uvs3) {
  36869. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36870. }
  36871. if (this.uvs4) {
  36872. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36873. }
  36874. if (this.uvs5) {
  36875. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36876. }
  36877. if (this.uvs6) {
  36878. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36879. }
  36880. if (this.colors) {
  36881. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36882. }
  36883. if (this.matricesIndices) {
  36884. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36885. }
  36886. if (this.matricesWeights) {
  36887. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36888. }
  36889. if (this.matricesIndicesExtra) {
  36890. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36891. }
  36892. if (this.matricesWeightsExtra) {
  36893. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36894. }
  36895. if (this.indices) {
  36896. meshOrGeometry.setIndices(this.indices);
  36897. }
  36898. return this;
  36899. };
  36900. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36901. if (this.positions) {
  36902. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36903. }
  36904. if (this.normals) {
  36905. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36906. }
  36907. if (this.tangents) {
  36908. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36909. }
  36910. if (this.uvs) {
  36911. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36912. }
  36913. if (this.uvs2) {
  36914. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36915. }
  36916. if (this.uvs3) {
  36917. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36918. }
  36919. if (this.uvs4) {
  36920. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36921. }
  36922. if (this.uvs5) {
  36923. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36924. }
  36925. if (this.uvs6) {
  36926. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36927. }
  36928. if (this.colors) {
  36929. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36930. }
  36931. if (this.matricesIndices) {
  36932. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36933. }
  36934. if (this.matricesWeights) {
  36935. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36936. }
  36937. if (this.matricesIndicesExtra) {
  36938. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36939. }
  36940. if (this.matricesWeightsExtra) {
  36941. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36942. }
  36943. if (this.indices) {
  36944. meshOrGeometry.setIndices(this.indices);
  36945. }
  36946. return this;
  36947. };
  36948. /**
  36949. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  36950. * Returns the VertexData.
  36951. */
  36952. VertexData.prototype.transform = function (matrix) {
  36953. var transformed = BABYLON.Vector3.Zero();
  36954. var index;
  36955. if (this.positions) {
  36956. var position = BABYLON.Vector3.Zero();
  36957. for (index = 0; index < this.positions.length; index += 3) {
  36958. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36959. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36960. this.positions[index] = transformed.x;
  36961. this.positions[index + 1] = transformed.y;
  36962. this.positions[index + 2] = transformed.z;
  36963. }
  36964. }
  36965. if (this.normals) {
  36966. var normal = BABYLON.Vector3.Zero();
  36967. for (index = 0; index < this.normals.length; index += 3) {
  36968. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36969. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36970. this.normals[index] = transformed.x;
  36971. this.normals[index + 1] = transformed.y;
  36972. this.normals[index + 2] = transformed.z;
  36973. }
  36974. }
  36975. if (this.tangents) {
  36976. var tangent = BABYLON.Vector4.Zero();
  36977. var tangentTransformed = BABYLON.Vector4.Zero();
  36978. for (index = 0; index < this.tangents.length; index += 4) {
  36979. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36980. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36981. this.tangents[index] = tangentTransformed.x;
  36982. this.tangents[index + 1] = tangentTransformed.y;
  36983. this.tangents[index + 2] = tangentTransformed.z;
  36984. this.tangents[index + 3] = tangentTransformed.w;
  36985. }
  36986. }
  36987. return this;
  36988. };
  36989. /**
  36990. * Merges the passed VertexData into the current one.
  36991. * Returns the modified VertexData.
  36992. */
  36993. VertexData.prototype.merge = function (other) {
  36994. if (other.indices) {
  36995. if (!this.indices) {
  36996. this.indices = [];
  36997. }
  36998. var offset = this.positions ? this.positions.length / 3 : 0;
  36999. for (var index = 0; index < other.indices.length; index++) {
  37000. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  37001. this.indices.push(other.indices[index] + offset);
  37002. }
  37003. }
  37004. this.positions = this._mergeElement(this.positions, other.positions);
  37005. this.normals = this._mergeElement(this.normals, other.normals);
  37006. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37007. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37008. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37009. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37010. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37011. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37012. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37013. this.colors = this._mergeElement(this.colors, other.colors);
  37014. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37015. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37016. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37017. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37018. return this;
  37019. };
  37020. VertexData.prototype._mergeElement = function (source, other) {
  37021. if (!other)
  37022. return source;
  37023. if (!source)
  37024. return other;
  37025. var len = other.length + source.length;
  37026. var isSrcTypedArray = source instanceof Float32Array;
  37027. var isOthTypedArray = other instanceof Float32Array;
  37028. // use non-loop method when the source is Float32Array
  37029. if (isSrcTypedArray) {
  37030. var ret32 = new Float32Array(len);
  37031. ret32.set(source);
  37032. ret32.set(other, source.length);
  37033. return ret32;
  37034. // source is number[], when other is also use concat
  37035. }
  37036. else if (!isOthTypedArray) {
  37037. return source.concat(other);
  37038. // source is a number[], but other is a Float32Array, loop required
  37039. }
  37040. else {
  37041. var ret = source.slice(0); // copy source to a separate array
  37042. for (var i = 0, len = other.length; i < len; i++) {
  37043. ret.push(other[i]);
  37044. }
  37045. return ret;
  37046. }
  37047. };
  37048. /**
  37049. * Serializes the VertexData.
  37050. * Returns a serialized object.
  37051. */
  37052. VertexData.prototype.serialize = function () {
  37053. var serializationObject = this.serialize();
  37054. if (this.positions) {
  37055. serializationObject.positions = this.positions;
  37056. }
  37057. if (this.normals) {
  37058. serializationObject.normals = this.normals;
  37059. }
  37060. if (this.tangents) {
  37061. serializationObject.tangents = this.tangents;
  37062. }
  37063. if (this.uvs) {
  37064. serializationObject.uvs = this.uvs;
  37065. }
  37066. if (this.uvs2) {
  37067. serializationObject.uvs2 = this.uvs2;
  37068. }
  37069. if (this.uvs3) {
  37070. serializationObject.uvs3 = this.uvs3;
  37071. }
  37072. if (this.uvs4) {
  37073. serializationObject.uvs4 = this.uvs4;
  37074. }
  37075. if (this.uvs5) {
  37076. serializationObject.uvs5 = this.uvs5;
  37077. }
  37078. if (this.uvs6) {
  37079. serializationObject.uvs6 = this.uvs6;
  37080. }
  37081. if (this.colors) {
  37082. serializationObject.colors = this.colors;
  37083. }
  37084. if (this.matricesIndices) {
  37085. serializationObject.matricesIndices = this.matricesIndices;
  37086. serializationObject.matricesIndices._isExpanded = true;
  37087. }
  37088. if (this.matricesWeights) {
  37089. serializationObject.matricesWeights = this.matricesWeights;
  37090. }
  37091. if (this.matricesIndicesExtra) {
  37092. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37093. serializationObject.matricesIndicesExtra._isExpanded = true;
  37094. }
  37095. if (this.matricesWeightsExtra) {
  37096. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37097. }
  37098. serializationObject.indices = this.indices;
  37099. return serializationObject;
  37100. };
  37101. // Statics
  37102. /**
  37103. * Returns the object VertexData associated to the passed mesh.
  37104. */
  37105. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  37106. return VertexData._ExtractFrom(mesh, copyWhenShared);
  37107. };
  37108. /**
  37109. * Returns the object VertexData associated to the passed geometry.
  37110. */
  37111. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  37112. return VertexData._ExtractFrom(geometry, copyWhenShared);
  37113. };
  37114. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  37115. var result = new VertexData();
  37116. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37117. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  37118. }
  37119. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37120. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  37121. }
  37122. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37123. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  37124. }
  37125. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37126. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  37127. }
  37128. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37129. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  37130. }
  37131. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37132. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  37133. }
  37134. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37135. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  37136. }
  37137. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37138. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  37139. }
  37140. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37141. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  37142. }
  37143. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37144. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  37145. }
  37146. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37147. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  37148. }
  37149. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37150. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  37151. }
  37152. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37153. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  37154. }
  37155. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37156. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  37157. }
  37158. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37159. return result;
  37160. };
  37161. /**
  37162. * Creates the vertexData of the Ribbon.
  37163. */
  37164. VertexData.CreateRibbon = function (options) {
  37165. var pathArray = options.pathArray;
  37166. var closeArray = options.closeArray || false;
  37167. var closePath = options.closePath || false;
  37168. var invertUV = options.invertUV || false;
  37169. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37170. var offset = options.offset || defaultOffset;
  37171. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37172. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37173. var customUV = options.uvs;
  37174. var customColors = options.colors;
  37175. var positions = [];
  37176. var indices = [];
  37177. var normals = [];
  37178. var uvs = [];
  37179. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37180. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37181. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37182. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37183. var minlg; // minimal length among all paths from pathArray
  37184. var lg = []; // array of path lengths : nb of vertex per path
  37185. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37186. var p; // path iterator
  37187. var i; // point iterator
  37188. var j; // point iterator
  37189. // if single path in pathArray
  37190. if (pathArray.length < 2) {
  37191. var ar1 = [];
  37192. var ar2 = [];
  37193. for (i = 0; i < pathArray[0].length - offset; i++) {
  37194. ar1.push(pathArray[0][i]);
  37195. ar2.push(pathArray[0][i + offset]);
  37196. }
  37197. pathArray = [ar1, ar2];
  37198. }
  37199. // positions and horizontal distances (u)
  37200. var idc = 0;
  37201. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37202. var path;
  37203. var l;
  37204. minlg = pathArray[0].length;
  37205. var vectlg;
  37206. var dist;
  37207. for (p = 0; p < pathArray.length; p++) {
  37208. uTotalDistance[p] = 0;
  37209. us[p] = [0];
  37210. path = pathArray[p];
  37211. l = path.length;
  37212. minlg = (minlg < l) ? minlg : l;
  37213. j = 0;
  37214. while (j < l) {
  37215. positions.push(path[j].x, path[j].y, path[j].z);
  37216. if (j > 0) {
  37217. vectlg = path[j].subtract(path[j - 1]).length();
  37218. dist = vectlg + uTotalDistance[p];
  37219. us[p].push(dist);
  37220. uTotalDistance[p] = dist;
  37221. }
  37222. j++;
  37223. }
  37224. if (closePath) {
  37225. j--;
  37226. positions.push(path[0].x, path[0].y, path[0].z);
  37227. vectlg = path[j].subtract(path[0]).length();
  37228. dist = vectlg + uTotalDistance[p];
  37229. us[p].push(dist);
  37230. uTotalDistance[p] = dist;
  37231. }
  37232. lg[p] = l + closePathCorr;
  37233. idx[p] = idc;
  37234. idc += (l + closePathCorr);
  37235. }
  37236. // vertical distances (v)
  37237. var path1;
  37238. var path2;
  37239. var vertex1;
  37240. var vertex2;
  37241. for (i = 0; i < minlg + closePathCorr; i++) {
  37242. vTotalDistance[i] = 0;
  37243. vs[i] = [0];
  37244. for (p = 0; p < pathArray.length - 1; p++) {
  37245. path1 = pathArray[p];
  37246. path2 = pathArray[p + 1];
  37247. if (i === minlg) {
  37248. vertex1 = path1[0];
  37249. vertex2 = path2[0];
  37250. }
  37251. else {
  37252. vertex1 = path1[i];
  37253. vertex2 = path2[i];
  37254. }
  37255. vectlg = vertex2.subtract(vertex1).length();
  37256. dist = vectlg + vTotalDistance[i];
  37257. vs[i].push(dist);
  37258. vTotalDistance[i] = dist;
  37259. }
  37260. if (closeArray) {
  37261. path1 = pathArray[p];
  37262. path2 = pathArray[0];
  37263. if (i === minlg) {
  37264. vertex2 = path2[0];
  37265. }
  37266. vectlg = vertex2.subtract(vertex1).length();
  37267. dist = vectlg + vTotalDistance[i];
  37268. vTotalDistance[i] = dist;
  37269. }
  37270. }
  37271. // uvs
  37272. var u;
  37273. var v;
  37274. if (customUV) {
  37275. for (p = 0; p < customUV.length; p++) {
  37276. uvs.push(customUV[p].x, customUV[p].y);
  37277. }
  37278. }
  37279. else {
  37280. for (p = 0; p < pathArray.length; p++) {
  37281. for (i = 0; i < minlg + closePathCorr; i++) {
  37282. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37283. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37284. if (invertUV) {
  37285. uvs.push(v, u);
  37286. }
  37287. else {
  37288. uvs.push(u, v);
  37289. }
  37290. }
  37291. }
  37292. }
  37293. // indices
  37294. p = 0; // path index
  37295. var pi = 0; // positions array index
  37296. var l1 = lg[p] - 1; // path1 length
  37297. var l2 = lg[p + 1] - 1; // path2 length
  37298. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37299. var shft = idx[1] - idx[0]; // shift
  37300. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37301. while (pi <= min && p < path1nb) {
  37302. // 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
  37303. indices.push(pi, pi + shft, pi + 1);
  37304. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37305. pi += 1;
  37306. if (pi === min) {
  37307. p++;
  37308. if (p === lg.length - 1) {
  37309. shft = idx[0] - idx[p];
  37310. l1 = lg[p] - 1;
  37311. l2 = lg[0] - 1;
  37312. }
  37313. else {
  37314. shft = idx[p + 1] - idx[p];
  37315. l1 = lg[p] - 1;
  37316. l2 = lg[p + 1] - 1;
  37317. }
  37318. pi = idx[p];
  37319. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37320. }
  37321. }
  37322. // normals
  37323. VertexData.ComputeNormals(positions, indices, normals);
  37324. if (closePath) {
  37325. var indexFirst = 0;
  37326. var indexLast = 0;
  37327. for (p = 0; p < pathArray.length; p++) {
  37328. indexFirst = idx[p] * 3;
  37329. if (p + 1 < pathArray.length) {
  37330. indexLast = (idx[p + 1] - 1) * 3;
  37331. }
  37332. else {
  37333. indexLast = normals.length - 3;
  37334. }
  37335. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37336. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37337. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37338. normals[indexLast] = normals[indexFirst];
  37339. normals[indexLast + 1] = normals[indexFirst + 1];
  37340. normals[indexLast + 2] = normals[indexFirst + 2];
  37341. }
  37342. }
  37343. // sides
  37344. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37345. // Colors
  37346. if (customColors) {
  37347. var colors = new Float32Array(customColors.length * 4);
  37348. for (var c = 0; c < customColors.length; c++) {
  37349. colors[c * 4] = customColors[c].r;
  37350. colors[c * 4 + 1] = customColors[c].g;
  37351. colors[c * 4 + 2] = customColors[c].b;
  37352. colors[c * 4 + 3] = customColors[c].a;
  37353. }
  37354. }
  37355. // Result
  37356. var vertexData = new VertexData();
  37357. var positions32 = new Float32Array(positions);
  37358. var normals32 = new Float32Array(normals);
  37359. var uvs32 = new Float32Array(uvs);
  37360. vertexData.indices = indices;
  37361. vertexData.positions = positions32;
  37362. vertexData.normals = normals32;
  37363. vertexData.uvs = uvs32;
  37364. if (customColors) {
  37365. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37366. }
  37367. if (closePath) {
  37368. vertexData._idx = idx;
  37369. }
  37370. return vertexData;
  37371. };
  37372. /**
  37373. * Creates the VertexData of the Box.
  37374. */
  37375. VertexData.CreateBox = function (options) {
  37376. var normalsSource = [
  37377. new BABYLON.Vector3(0, 0, 1),
  37378. new BABYLON.Vector3(0, 0, -1),
  37379. new BABYLON.Vector3(1, 0, 0),
  37380. new BABYLON.Vector3(-1, 0, 0),
  37381. new BABYLON.Vector3(0, 1, 0),
  37382. new BABYLON.Vector3(0, -1, 0)
  37383. ];
  37384. var indices = [];
  37385. var positions = [];
  37386. var normals = [];
  37387. var uvs = [];
  37388. var width = options.width || options.size || 1;
  37389. var height = options.height || options.size || 1;
  37390. var depth = options.depth || options.size || 1;
  37391. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37392. var faceUV = options.faceUV || new Array(6);
  37393. var faceColors = options.faceColors;
  37394. var colors = [];
  37395. // default face colors and UV if undefined
  37396. for (var f = 0; f < 6; f++) {
  37397. if (faceUV[f] === undefined) {
  37398. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37399. }
  37400. if (faceColors && faceColors[f] === undefined) {
  37401. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37402. }
  37403. }
  37404. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37405. // Create each face in turn.
  37406. for (var index = 0; index < normalsSource.length; index++) {
  37407. var normal = normalsSource[index];
  37408. // Get two vectors perpendicular to the face normal and to each other.
  37409. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37410. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37411. // Six indices (two triangles) per face.
  37412. var verticesLength = positions.length / 3;
  37413. indices.push(verticesLength);
  37414. indices.push(verticesLength + 1);
  37415. indices.push(verticesLength + 2);
  37416. indices.push(verticesLength);
  37417. indices.push(verticesLength + 2);
  37418. indices.push(verticesLength + 3);
  37419. // Four vertices per face.
  37420. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37421. positions.push(vertex.x, vertex.y, vertex.z);
  37422. normals.push(normal.x, normal.y, normal.z);
  37423. uvs.push(faceUV[index].z, faceUV[index].w);
  37424. if (faceColors) {
  37425. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37426. }
  37427. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37428. positions.push(vertex.x, vertex.y, vertex.z);
  37429. normals.push(normal.x, normal.y, normal.z);
  37430. uvs.push(faceUV[index].x, faceUV[index].w);
  37431. if (faceColors) {
  37432. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37433. }
  37434. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37435. positions.push(vertex.x, vertex.y, vertex.z);
  37436. normals.push(normal.x, normal.y, normal.z);
  37437. uvs.push(faceUV[index].x, faceUV[index].y);
  37438. if (faceColors) {
  37439. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37440. }
  37441. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37442. positions.push(vertex.x, vertex.y, vertex.z);
  37443. normals.push(normal.x, normal.y, normal.z);
  37444. uvs.push(faceUV[index].z, faceUV[index].y);
  37445. if (faceColors) {
  37446. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37447. }
  37448. }
  37449. // sides
  37450. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37451. // Result
  37452. var vertexData = new VertexData();
  37453. vertexData.indices = indices;
  37454. vertexData.positions = positions;
  37455. vertexData.normals = normals;
  37456. vertexData.uvs = uvs;
  37457. if (faceColors) {
  37458. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37459. vertexData.colors = totalColors;
  37460. }
  37461. return vertexData;
  37462. };
  37463. /**
  37464. * Creates the VertexData of the Sphere.
  37465. */
  37466. VertexData.CreateSphere = function (options) {
  37467. var segments = options.segments || 32;
  37468. var diameterX = options.diameterX || options.diameter || 1;
  37469. var diameterY = options.diameterY || options.diameter || 1;
  37470. var diameterZ = options.diameterZ || options.diameter || 1;
  37471. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37472. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37473. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37474. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37475. var totalZRotationSteps = 2 + segments;
  37476. var totalYRotationSteps = 2 * totalZRotationSteps;
  37477. var indices = [];
  37478. var positions = [];
  37479. var normals = [];
  37480. var uvs = [];
  37481. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37482. var normalizedZ = zRotationStep / totalZRotationSteps;
  37483. var angleZ = normalizedZ * Math.PI * slice;
  37484. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37485. var normalizedY = yRotationStep / totalYRotationSteps;
  37486. var angleY = normalizedY * Math.PI * 2 * arc;
  37487. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37488. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37489. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37490. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37491. var vertex = complete.multiply(radius);
  37492. var normal = complete.divide(radius).normalize();
  37493. positions.push(vertex.x, vertex.y, vertex.z);
  37494. normals.push(normal.x, normal.y, normal.z);
  37495. uvs.push(normalizedY, normalizedZ);
  37496. }
  37497. if (zRotationStep > 0) {
  37498. var verticesCount = positions.length / 3;
  37499. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37500. indices.push((firstIndex));
  37501. indices.push((firstIndex + 1));
  37502. indices.push(firstIndex + totalYRotationSteps + 1);
  37503. indices.push((firstIndex + totalYRotationSteps + 1));
  37504. indices.push((firstIndex + 1));
  37505. indices.push((firstIndex + totalYRotationSteps + 2));
  37506. }
  37507. }
  37508. }
  37509. // Sides
  37510. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37511. // Result
  37512. var vertexData = new VertexData();
  37513. vertexData.indices = indices;
  37514. vertexData.positions = positions;
  37515. vertexData.normals = normals;
  37516. vertexData.uvs = uvs;
  37517. return vertexData;
  37518. };
  37519. /**
  37520. * Creates the VertexData of the Cylinder or Cone.
  37521. */
  37522. VertexData.CreateCylinder = function (options) {
  37523. var height = options.height || 2;
  37524. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37525. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37526. var tessellation = options.tessellation || 24;
  37527. var subdivisions = options.subdivisions || 1;
  37528. var hasRings = options.hasRings;
  37529. var enclose = options.enclose;
  37530. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37531. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37532. var faceUV = options.faceUV || new Array(3);
  37533. var faceColors = options.faceColors;
  37534. // default face colors and UV if undefined
  37535. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37536. var ringNb = (hasRings) ? subdivisions : 1;
  37537. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37538. var f;
  37539. for (f = 0; f < surfaceNb; f++) {
  37540. if (faceColors && faceColors[f] === undefined) {
  37541. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37542. }
  37543. }
  37544. for (f = 0; f < surfaceNb; f++) {
  37545. if (faceUV && faceUV[f] === undefined) {
  37546. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37547. }
  37548. }
  37549. var indices = [];
  37550. var positions = [];
  37551. var normals = [];
  37552. var uvs = [];
  37553. var colors = [];
  37554. var angle_step = Math.PI * 2 * arc / tessellation;
  37555. var angle;
  37556. var h;
  37557. var radius;
  37558. var tan = (diameterBottom - diameterTop) / 2 / height;
  37559. var ringVertex = BABYLON.Vector3.Zero();
  37560. var ringNormal = BABYLON.Vector3.Zero();
  37561. var ringFirstVertex = BABYLON.Vector3.Zero();
  37562. var ringFirstNormal = BABYLON.Vector3.Zero();
  37563. var quadNormal = BABYLON.Vector3.Zero();
  37564. var Y = BABYLON.Axis.Y;
  37565. // positions, normals, uvs
  37566. var i;
  37567. var j;
  37568. var r;
  37569. var ringIdx = 1;
  37570. var s = 1; // surface index
  37571. var cs = 0;
  37572. var v = 0;
  37573. for (i = 0; i <= subdivisions; i++) {
  37574. h = i / subdivisions;
  37575. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37576. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37577. for (r = 0; r < ringIdx; r++) {
  37578. if (hasRings) {
  37579. s += r;
  37580. }
  37581. if (enclose) {
  37582. s += 2 * r;
  37583. }
  37584. for (j = 0; j <= tessellation; j++) {
  37585. angle = j * angle_step;
  37586. // position
  37587. ringVertex.x = Math.cos(-angle) * radius;
  37588. ringVertex.y = -height / 2 + h * height;
  37589. ringVertex.z = Math.sin(-angle) * radius;
  37590. // normal
  37591. if (diameterTop === 0 && i === subdivisions) {
  37592. // if no top cap, reuse former normals
  37593. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37594. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37595. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37596. }
  37597. else {
  37598. ringNormal.x = ringVertex.x;
  37599. ringNormal.z = ringVertex.z;
  37600. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37601. ringNormal.normalize();
  37602. }
  37603. // keep first ring vertex values for enclose
  37604. if (j === 0) {
  37605. ringFirstVertex.copyFrom(ringVertex);
  37606. ringFirstNormal.copyFrom(ringNormal);
  37607. }
  37608. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37609. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37610. if (hasRings) {
  37611. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37612. }
  37613. else {
  37614. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37615. }
  37616. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37617. if (faceColors) {
  37618. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37619. }
  37620. }
  37621. // if enclose, add four vertices and their dedicated normals
  37622. if (arc !== 1 && enclose) {
  37623. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37624. positions.push(0, ringVertex.y, 0);
  37625. positions.push(0, ringVertex.y, 0);
  37626. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37627. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37628. quadNormal.normalize();
  37629. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37630. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37631. quadNormal.normalize();
  37632. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37633. if (hasRings) {
  37634. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37635. }
  37636. else {
  37637. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37638. }
  37639. uvs.push(faceUV[s + 1].x, v);
  37640. uvs.push(faceUV[s + 1].z, v);
  37641. if (hasRings) {
  37642. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37643. }
  37644. else {
  37645. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37646. }
  37647. uvs.push(faceUV[s + 2].x, v);
  37648. uvs.push(faceUV[s + 2].z, v);
  37649. if (faceColors) {
  37650. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37651. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37652. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37653. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37654. }
  37655. }
  37656. if (cs !== s) {
  37657. cs = s;
  37658. }
  37659. }
  37660. }
  37661. // indices
  37662. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37663. var s;
  37664. i = 0;
  37665. for (s = 0; s < subdivisions; s++) {
  37666. for (j = 0; j < tessellation; j++) {
  37667. var i0 = i * (e + 1) + j;
  37668. var i1 = (i + 1) * (e + 1) + j;
  37669. var i2 = i * (e + 1) + (j + 1);
  37670. var i3 = (i + 1) * (e + 1) + (j + 1);
  37671. indices.push(i0, i1, i2);
  37672. indices.push(i3, i2, i1);
  37673. }
  37674. if (arc !== 1 && enclose) {
  37675. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37676. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37677. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37678. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37679. }
  37680. i = (hasRings) ? (i + 2) : (i + 1);
  37681. }
  37682. // Caps
  37683. var createCylinderCap = function (isTop) {
  37684. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37685. if (radius === 0) {
  37686. return;
  37687. }
  37688. // Cap positions, normals & uvs
  37689. var angle;
  37690. var circleVector;
  37691. var i;
  37692. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37693. var c;
  37694. if (faceColors) {
  37695. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37696. }
  37697. // cap center
  37698. var vbase = positions.length / 3;
  37699. var offset = isTop ? height / 2 : -height / 2;
  37700. var center = new BABYLON.Vector3(0, offset, 0);
  37701. positions.push(center.x, center.y, center.z);
  37702. normals.push(0, isTop ? 1 : -1, 0);
  37703. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37704. if (faceColors) {
  37705. colors.push(c.r, c.g, c.b, c.a);
  37706. }
  37707. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37708. for (i = 0; i <= tessellation; i++) {
  37709. angle = Math.PI * 2 * i * arc / tessellation;
  37710. var cos = Math.cos(-angle);
  37711. var sin = Math.sin(-angle);
  37712. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37713. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37714. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37715. normals.push(0, isTop ? 1 : -1, 0);
  37716. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37717. if (faceColors) {
  37718. colors.push(c.r, c.g, c.b, c.a);
  37719. }
  37720. }
  37721. // Cap indices
  37722. for (i = 0; i < tessellation; i++) {
  37723. if (!isTop) {
  37724. indices.push(vbase);
  37725. indices.push(vbase + (i + 1));
  37726. indices.push(vbase + (i + 2));
  37727. }
  37728. else {
  37729. indices.push(vbase);
  37730. indices.push(vbase + (i + 2));
  37731. indices.push(vbase + (i + 1));
  37732. }
  37733. }
  37734. };
  37735. // add caps to geometry
  37736. createCylinderCap(false);
  37737. createCylinderCap(true);
  37738. // Sides
  37739. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37740. var vertexData = new VertexData();
  37741. vertexData.indices = indices;
  37742. vertexData.positions = positions;
  37743. vertexData.normals = normals;
  37744. vertexData.uvs = uvs;
  37745. if (faceColors) {
  37746. vertexData.colors = colors;
  37747. }
  37748. return vertexData;
  37749. };
  37750. /**
  37751. * Creates the VertexData of the Torus.
  37752. */
  37753. VertexData.CreateTorus = function (options) {
  37754. var indices = [];
  37755. var positions = [];
  37756. var normals = [];
  37757. var uvs = [];
  37758. var diameter = options.diameter || 1;
  37759. var thickness = options.thickness || 0.5;
  37760. var tessellation = options.tessellation || 16;
  37761. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37762. var stride = tessellation + 1;
  37763. for (var i = 0; i <= tessellation; i++) {
  37764. var u = i / tessellation;
  37765. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37766. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37767. for (var j = 0; j <= tessellation; j++) {
  37768. var v = 1 - j / tessellation;
  37769. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37770. var dx = Math.cos(innerAngle);
  37771. var dy = Math.sin(innerAngle);
  37772. // Create a vertex.
  37773. var normal = new BABYLON.Vector3(dx, dy, 0);
  37774. var position = normal.scale(thickness / 2);
  37775. var textureCoordinate = new BABYLON.Vector2(u, v);
  37776. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37777. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37778. positions.push(position.x, position.y, position.z);
  37779. normals.push(normal.x, normal.y, normal.z);
  37780. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37781. // And create indices for two triangles.
  37782. var nextI = (i + 1) % stride;
  37783. var nextJ = (j + 1) % stride;
  37784. indices.push(i * stride + j);
  37785. indices.push(i * stride + nextJ);
  37786. indices.push(nextI * stride + j);
  37787. indices.push(i * stride + nextJ);
  37788. indices.push(nextI * stride + nextJ);
  37789. indices.push(nextI * stride + j);
  37790. }
  37791. }
  37792. // Sides
  37793. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  37794. // Result
  37795. var vertexData = new VertexData();
  37796. vertexData.indices = indices;
  37797. vertexData.positions = positions;
  37798. vertexData.normals = normals;
  37799. vertexData.uvs = uvs;
  37800. return vertexData;
  37801. };
  37802. /**
  37803. * Creates the VertexData of the LineSystem.
  37804. */
  37805. VertexData.CreateLineSystem = function (options) {
  37806. var indices = [];
  37807. var positions = [];
  37808. var lines = options.lines;
  37809. var idx = 0;
  37810. for (var l = 0; l < lines.length; l++) {
  37811. var points = lines[l];
  37812. for (var index = 0; index < points.length; index++) {
  37813. positions.push(points[index].x, points[index].y, points[index].z);
  37814. if (index > 0) {
  37815. indices.push(idx - 1);
  37816. indices.push(idx);
  37817. }
  37818. idx++;
  37819. }
  37820. }
  37821. var vertexData = new VertexData();
  37822. vertexData.indices = indices;
  37823. vertexData.positions = positions;
  37824. return vertexData;
  37825. };
  37826. /**
  37827. * Create the VertexData of the DashedLines.
  37828. */
  37829. VertexData.CreateDashedLines = function (options) {
  37830. var dashSize = options.dashSize || 3;
  37831. var gapSize = options.gapSize || 1;
  37832. var dashNb = options.dashNb || 200;
  37833. var points = options.points;
  37834. var positions = new Array();
  37835. var indices = new Array();
  37836. var curvect = BABYLON.Vector3.Zero();
  37837. var lg = 0;
  37838. var nb = 0;
  37839. var shft = 0;
  37840. var dashshft = 0;
  37841. var curshft = 0;
  37842. var idx = 0;
  37843. var i = 0;
  37844. for (i = 0; i < points.length - 1; i++) {
  37845. points[i + 1].subtractToRef(points[i], curvect);
  37846. lg += curvect.length();
  37847. }
  37848. shft = lg / dashNb;
  37849. dashshft = dashSize * shft / (dashSize + gapSize);
  37850. for (i = 0; i < points.length - 1; i++) {
  37851. points[i + 1].subtractToRef(points[i], curvect);
  37852. nb = Math.floor(curvect.length() / shft);
  37853. curvect.normalize();
  37854. for (var j = 0; j < nb; j++) {
  37855. curshft = shft * j;
  37856. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37857. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37858. indices.push(idx, idx + 1);
  37859. idx += 2;
  37860. }
  37861. }
  37862. // Result
  37863. var vertexData = new VertexData();
  37864. vertexData.positions = positions;
  37865. vertexData.indices = indices;
  37866. return vertexData;
  37867. };
  37868. /**
  37869. * Creates the VertexData of the Ground.
  37870. */
  37871. VertexData.CreateGround = function (options) {
  37872. var indices = [];
  37873. var positions = [];
  37874. var normals = [];
  37875. var uvs = [];
  37876. var row, col;
  37877. var width = options.width || 1;
  37878. var height = options.height || 1;
  37879. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37880. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37881. for (row = 0; row <= subdivisionsY; row++) {
  37882. for (col = 0; col <= subdivisionsX; col++) {
  37883. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37884. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37885. positions.push(position.x, position.y, position.z);
  37886. normals.push(normal.x, normal.y, normal.z);
  37887. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37888. }
  37889. }
  37890. for (row = 0; row < subdivisionsY; row++) {
  37891. for (col = 0; col < subdivisionsX; col++) {
  37892. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37893. indices.push(col + 1 + row * (subdivisionsX + 1));
  37894. indices.push(col + row * (subdivisionsX + 1));
  37895. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37896. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37897. indices.push(col + row * (subdivisionsX + 1));
  37898. }
  37899. }
  37900. // Result
  37901. var vertexData = new VertexData();
  37902. vertexData.indices = indices;
  37903. vertexData.positions = positions;
  37904. vertexData.normals = normals;
  37905. vertexData.uvs = uvs;
  37906. return vertexData;
  37907. };
  37908. /**
  37909. * Creates the VertexData of the TiledGround.
  37910. */
  37911. VertexData.CreateTiledGround = function (options) {
  37912. var xmin = options.xmin || -1.0;
  37913. var zmin = options.zmin || -1.0;
  37914. var xmax = options.xmax || 1.0;
  37915. var zmax = options.zmax || 1.0;
  37916. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37917. var precision = options.precision || { w: 1, h: 1 };
  37918. var indices = [];
  37919. var positions = [];
  37920. var normals = [];
  37921. var uvs = [];
  37922. var row, col, tileRow, tileCol;
  37923. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37924. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37925. precision.w = (precision.w < 1) ? 1 : precision.w;
  37926. precision.h = (precision.h < 1) ? 1 : precision.h;
  37927. var tileSize = {
  37928. 'w': (xmax - xmin) / subdivisions.w,
  37929. 'h': (zmax - zmin) / subdivisions.h
  37930. };
  37931. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37932. // Indices
  37933. var base = positions.length / 3;
  37934. var rowLength = precision.w + 1;
  37935. for (row = 0; row < precision.h; row++) {
  37936. for (col = 0; col < precision.w; col++) {
  37937. var square = [
  37938. base + col + row * rowLength,
  37939. base + (col + 1) + row * rowLength,
  37940. base + (col + 1) + (row + 1) * rowLength,
  37941. base + col + (row + 1) * rowLength
  37942. ];
  37943. indices.push(square[1]);
  37944. indices.push(square[2]);
  37945. indices.push(square[3]);
  37946. indices.push(square[0]);
  37947. indices.push(square[1]);
  37948. indices.push(square[3]);
  37949. }
  37950. }
  37951. // Position, normals and uvs
  37952. var position = BABYLON.Vector3.Zero();
  37953. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37954. for (row = 0; row <= precision.h; row++) {
  37955. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37956. for (col = 0; col <= precision.w; col++) {
  37957. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37958. position.y = 0;
  37959. positions.push(position.x, position.y, position.z);
  37960. normals.push(normal.x, normal.y, normal.z);
  37961. uvs.push(col / precision.w, row / precision.h);
  37962. }
  37963. }
  37964. }
  37965. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37966. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37967. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37968. }
  37969. }
  37970. // Result
  37971. var vertexData = new VertexData();
  37972. vertexData.indices = indices;
  37973. vertexData.positions = positions;
  37974. vertexData.normals = normals;
  37975. vertexData.uvs = uvs;
  37976. return vertexData;
  37977. };
  37978. /**
  37979. * Creates the VertexData of the Ground designed from a heightmap.
  37980. */
  37981. VertexData.CreateGroundFromHeightMap = function (options) {
  37982. var indices = [];
  37983. var positions = [];
  37984. var normals = [];
  37985. var uvs = [];
  37986. var row, col;
  37987. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37988. // Vertices
  37989. for (row = 0; row <= options.subdivisions; row++) {
  37990. for (col = 0; col <= options.subdivisions; col++) {
  37991. 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));
  37992. // Compute height
  37993. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37994. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37995. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37996. var r = options.buffer[pos] / 255.0;
  37997. var g = options.buffer[pos + 1] / 255.0;
  37998. var b = options.buffer[pos + 2] / 255.0;
  37999. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38000. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38001. // Add vertex
  38002. positions.push(position.x, position.y, position.z);
  38003. normals.push(0, 0, 0);
  38004. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38005. }
  38006. }
  38007. // Indices
  38008. for (row = 0; row < options.subdivisions; row++) {
  38009. for (col = 0; col < options.subdivisions; col++) {
  38010. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38011. indices.push(col + 1 + row * (options.subdivisions + 1));
  38012. indices.push(col + row * (options.subdivisions + 1));
  38013. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38014. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38015. indices.push(col + row * (options.subdivisions + 1));
  38016. }
  38017. }
  38018. // Normals
  38019. VertexData.ComputeNormals(positions, indices, normals);
  38020. // Result
  38021. var vertexData = new VertexData();
  38022. vertexData.indices = indices;
  38023. vertexData.positions = positions;
  38024. vertexData.normals = normals;
  38025. vertexData.uvs = uvs;
  38026. return vertexData;
  38027. };
  38028. /**
  38029. * Creates the VertexData of the Plane.
  38030. */
  38031. VertexData.CreatePlane = function (options) {
  38032. var indices = [];
  38033. var positions = [];
  38034. var normals = [];
  38035. var uvs = [];
  38036. var width = options.width || options.size || 1;
  38037. var height = options.height || options.size || 1;
  38038. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38039. // Vertices
  38040. var halfWidth = width / 2.0;
  38041. var halfHeight = height / 2.0;
  38042. positions.push(-halfWidth, -halfHeight, 0);
  38043. normals.push(0, 0, -1.0);
  38044. uvs.push(0.0, 0.0);
  38045. positions.push(halfWidth, -halfHeight, 0);
  38046. normals.push(0, 0, -1.0);
  38047. uvs.push(1.0, 0.0);
  38048. positions.push(halfWidth, halfHeight, 0);
  38049. normals.push(0, 0, -1.0);
  38050. uvs.push(1.0, 1.0);
  38051. positions.push(-halfWidth, halfHeight, 0);
  38052. normals.push(0, 0, -1.0);
  38053. uvs.push(0.0, 1.0);
  38054. // Indices
  38055. indices.push(0);
  38056. indices.push(1);
  38057. indices.push(2);
  38058. indices.push(0);
  38059. indices.push(2);
  38060. indices.push(3);
  38061. // Sides
  38062. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38063. // Result
  38064. var vertexData = new VertexData();
  38065. vertexData.indices = indices;
  38066. vertexData.positions = positions;
  38067. vertexData.normals = normals;
  38068. vertexData.uvs = uvs;
  38069. return vertexData;
  38070. };
  38071. /**
  38072. * Creates the VertexData of the Disc or regular Polygon.
  38073. */
  38074. VertexData.CreateDisc = function (options) {
  38075. var positions = [];
  38076. var indices = [];
  38077. var normals = [];
  38078. var uvs = [];
  38079. var radius = options.radius || 0.5;
  38080. var tessellation = options.tessellation || 64;
  38081. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38082. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38083. // positions and uvs
  38084. positions.push(0, 0, 0); // disc center first
  38085. uvs.push(0.5, 0.5);
  38086. var theta = Math.PI * 2 * arc;
  38087. var step = theta / tessellation;
  38088. for (var a = 0; a < theta; a += step) {
  38089. var x = Math.cos(a);
  38090. var y = Math.sin(a);
  38091. var u = (x + 1) / 2;
  38092. var v = (1 - y) / 2;
  38093. positions.push(radius * x, radius * y, 0);
  38094. uvs.push(u, v);
  38095. }
  38096. if (arc === 1) {
  38097. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38098. uvs.push(uvs[2], uvs[3]);
  38099. }
  38100. //indices
  38101. var vertexNb = positions.length / 3;
  38102. for (var i = 1; i < vertexNb - 1; i++) {
  38103. indices.push(i + 1, 0, i);
  38104. }
  38105. // result
  38106. VertexData.ComputeNormals(positions, indices, normals);
  38107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38108. var vertexData = new VertexData();
  38109. vertexData.indices = indices;
  38110. vertexData.positions = positions;
  38111. vertexData.normals = normals;
  38112. vertexData.uvs = uvs;
  38113. return vertexData;
  38114. };
  38115. /**
  38116. * Creates the VertexData of the IcoSphere.
  38117. */
  38118. VertexData.CreateIcoSphere = function (options) {
  38119. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38120. var radius = options.radius || 1;
  38121. var flat = (options.flat === undefined) ? true : options.flat;
  38122. var subdivisions = options.subdivisions || 4;
  38123. var radiusX = options.radiusX || radius;
  38124. var radiusY = options.radiusY || radius;
  38125. var radiusZ = options.radiusZ || radius;
  38126. var t = (1 + Math.sqrt(5)) / 2;
  38127. // 12 vertex x,y,z
  38128. var ico_vertices = [
  38129. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38130. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38131. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38132. ];
  38133. // index of 3 vertex makes a face of icopshere
  38134. var ico_indices = [
  38135. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38136. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38137. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38138. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38139. ];
  38140. // vertex for uv have aliased position, not for UV
  38141. var vertices_unalias_id = [
  38142. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38143. // vertex alias
  38144. 0,
  38145. 2,
  38146. 3,
  38147. 3,
  38148. 3,
  38149. 4,
  38150. 7,
  38151. 8,
  38152. 9,
  38153. 9,
  38154. 10,
  38155. 11 // 23: B + 12
  38156. ];
  38157. // uv as integer step (not pixels !)
  38158. var ico_vertexuv = [
  38159. 5, 1, 3, 1, 6, 4, 0, 0,
  38160. 5, 3, 4, 2, 2, 2, 4, 0,
  38161. 2, 0, 1, 1, 6, 0, 6, 2,
  38162. // vertex alias (for same vertex on different faces)
  38163. 0, 4,
  38164. 3, 3,
  38165. 4, 4,
  38166. 3, 1,
  38167. 4, 2,
  38168. 4, 4,
  38169. 0, 2,
  38170. 1, 1,
  38171. 2, 2,
  38172. 3, 3,
  38173. 1, 3,
  38174. 2, 4 // 23: B + 12
  38175. ];
  38176. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38177. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38178. // First island of uv mapping
  38179. // v = 4h 3+ 2
  38180. // v = 3h 9+ 4
  38181. // v = 2h 9+ 5 B
  38182. // v = 1h 9 1 0
  38183. // v = 0h 3 8 7 A
  38184. // u = 0 1 2 3 4 5 6 *a
  38185. // Second island of uv mapping
  38186. // v = 4h 0+ B+ 4+
  38187. // v = 3h A+ 2+
  38188. // v = 2h 7+ 6 3+
  38189. // v = 1h 8+ 3+
  38190. // v = 0h
  38191. // u = 0 1 2 3 4 5 6 *a
  38192. // Face layout on texture UV mapping
  38193. // ============
  38194. // \ 4 /\ 16 / ======
  38195. // \ / \ / /\ 11 /
  38196. // \/ 7 \/ / \ /
  38197. // ======= / 10 \/
  38198. // /\ 17 /\ =======
  38199. // / \ / \ \ 15 /\
  38200. // / 8 \/ 12 \ \ / \
  38201. // ============ \/ 6 \
  38202. // \ 18 /\ ============
  38203. // \ / \ \ 5 /\ 0 /
  38204. // \/ 13 \ \ / \ /
  38205. // ======= \/ 1 \/
  38206. // =============
  38207. // /\ 19 /\ 2 /\
  38208. // / \ / \ / \
  38209. // / 14 \/ 9 \/ 3 \
  38210. // ===================
  38211. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38212. var ustep = 138 / 1024;
  38213. var vstep = 239 / 1024;
  38214. var uoffset = 60 / 1024;
  38215. var voffset = 26 / 1024;
  38216. // Second island should have margin, not to touch the first island
  38217. // avoid any borderline artefact in pixel rounding
  38218. var island_u_offset = -40 / 1024;
  38219. var island_v_offset = +20 / 1024;
  38220. // face is either island 0 or 1 :
  38221. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38222. var island = [
  38223. 0, 0, 0, 0, 1,
  38224. 0, 0, 1, 1, 0,
  38225. 0, 0, 1, 1, 0,
  38226. 0, 1, 1, 1, 0 // 15 - 19
  38227. ];
  38228. var indices = [];
  38229. var positions = [];
  38230. var normals = [];
  38231. var uvs = [];
  38232. var current_indice = 0;
  38233. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38234. var face_vertex_pos = new Array(3);
  38235. var face_vertex_uv = new Array(3);
  38236. var v012;
  38237. for (v012 = 0; v012 < 3; v012++) {
  38238. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38239. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38240. }
  38241. // create all with normals
  38242. for (var face = 0; face < 20; face++) {
  38243. // 3 vertex per face
  38244. for (v012 = 0; v012 < 3; v012++) {
  38245. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38246. var v_id = ico_indices[3 * face + v012];
  38247. // vertex have 3D position (x,y,z)
  38248. 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]);
  38249. // Normalize to get normal, then scale to radius
  38250. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38251. // uv Coordinates from vertex ID
  38252. 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);
  38253. }
  38254. // Subdivide the face (interpolate pos, norm, uv)
  38255. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38256. // - norm is linear interpolation of vertex corner normal
  38257. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38258. // - uv is linear interpolation
  38259. //
  38260. // Topology is as below for sub-divide by 2
  38261. // vertex shown as v0,v1,v2
  38262. // interp index is i1 to progress in range [v0,v1[
  38263. // interp index is i2 to progress in range [v0,v2[
  38264. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38265. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38266. //
  38267. //
  38268. // i2 v2
  38269. // ^ ^
  38270. // / / \
  38271. // / / \
  38272. // / / \
  38273. // / / (0,1) \
  38274. // / #---------\
  38275. // / / \ (0,0)'/ \
  38276. // / / \ / \
  38277. // / / \ / \
  38278. // / / (0,0) \ / (1,0) \
  38279. // / #---------#---------\
  38280. // v0 v1
  38281. //
  38282. // --------------------> i1
  38283. //
  38284. // interp of (i1,i2):
  38285. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38286. // along i1 : lerp(x0,x1, i1/(S-i2))
  38287. //
  38288. // centroid of triangle is needed to get help normal computation
  38289. // (c1,c2) are used for centroid location
  38290. var interp_vertex = function (i1, i2, c1, c2) {
  38291. // vertex is interpolated from
  38292. // - face_vertex_pos[0..2]
  38293. // - face_vertex_uv[0..2]
  38294. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38295. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38296. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38297. pos_interp.normalize();
  38298. var vertex_normal;
  38299. if (flat) {
  38300. // in flat mode, recalculate normal as face centroid normal
  38301. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38302. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38303. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38304. }
  38305. else {
  38306. // in smooth mode, recalculate normal from each single vertex position
  38307. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38308. }
  38309. // Vertex normal need correction due to X,Y,Z radius scaling
  38310. vertex_normal.x /= radiusX;
  38311. vertex_normal.y /= radiusY;
  38312. vertex_normal.z /= radiusZ;
  38313. vertex_normal.normalize();
  38314. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38315. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38316. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38317. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38318. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38319. uvs.push(uv_interp.x, uv_interp.y);
  38320. // push each vertex has member of a face
  38321. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38322. indices.push(current_indice);
  38323. current_indice++;
  38324. };
  38325. for (var i2 = 0; i2 < subdivisions; i2++) {
  38326. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38327. // face : (i1,i2) for /\ :
  38328. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38329. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38330. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38331. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38332. if (i1 + i2 + 1 < subdivisions) {
  38333. // face : (i1,i2)' for \/ :
  38334. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38335. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38336. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38337. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38338. }
  38339. }
  38340. }
  38341. }
  38342. // Sides
  38343. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38344. // Result
  38345. var vertexData = new VertexData();
  38346. vertexData.indices = indices;
  38347. vertexData.positions = positions;
  38348. vertexData.normals = normals;
  38349. vertexData.uvs = uvs;
  38350. return vertexData;
  38351. };
  38352. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38353. /**
  38354. * Creates the VertexData of the Polyhedron.
  38355. */
  38356. VertexData.CreatePolyhedron = function (options) {
  38357. // provided polyhedron types :
  38358. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38359. // 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)
  38360. var polyhedra = [];
  38361. 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]] };
  38362. 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]] };
  38363. polyhedra[2] = {
  38364. 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]],
  38365. 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]]
  38366. };
  38367. polyhedra[3] = {
  38368. 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]],
  38369. 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]]
  38370. };
  38371. polyhedra[4] = {
  38372. 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]],
  38373. 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]]
  38374. };
  38375. 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]] };
  38376. 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]] };
  38377. 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]] };
  38378. 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]] };
  38379. 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]] };
  38380. 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]] };
  38381. 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]] };
  38382. 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]] };
  38383. 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]] };
  38384. polyhedra[14] = {
  38385. 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]],
  38386. 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]]
  38387. };
  38388. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38389. var size = options.size;
  38390. var sizeX = options.sizeX || size || 1;
  38391. var sizeY = options.sizeY || size || 1;
  38392. var sizeZ = options.sizeZ || size || 1;
  38393. var data = options.custom || polyhedra[type];
  38394. var nbfaces = data.face.length;
  38395. var faceUV = options.faceUV || new Array(nbfaces);
  38396. var faceColors = options.faceColors;
  38397. var flat = (options.flat === undefined) ? true : options.flat;
  38398. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38399. var positions = [];
  38400. var indices = [];
  38401. var normals = [];
  38402. var uvs = [];
  38403. var colors = [];
  38404. var index = 0;
  38405. var faceIdx = 0; // face cursor in the array "indexes"
  38406. var indexes = [];
  38407. var i = 0;
  38408. var f = 0;
  38409. var u, v, ang, x, y, tmp;
  38410. // default face colors and UV if undefined
  38411. if (flat) {
  38412. for (f = 0; f < nbfaces; f++) {
  38413. if (faceColors && faceColors[f] === undefined) {
  38414. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38415. }
  38416. if (faceUV && faceUV[f] === undefined) {
  38417. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38418. }
  38419. }
  38420. }
  38421. if (!flat) {
  38422. for (i = 0; i < data.vertex.length; i++) {
  38423. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38424. uvs.push(0, 0);
  38425. }
  38426. for (f = 0; f < nbfaces; f++) {
  38427. for (i = 0; i < data.face[f].length - 2; i++) {
  38428. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38429. }
  38430. }
  38431. }
  38432. else {
  38433. for (f = 0; f < nbfaces; f++) {
  38434. var fl = data.face[f].length; // number of vertices of the current face
  38435. ang = 2 * Math.PI / fl;
  38436. x = 0.5 * Math.tan(ang / 2);
  38437. y = 0.5;
  38438. // positions, uvs, colors
  38439. for (i = 0; i < fl; i++) {
  38440. // positions
  38441. 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);
  38442. indexes.push(index);
  38443. index++;
  38444. // uvs
  38445. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38446. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38447. uvs.push(u, v);
  38448. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38449. y = x * Math.sin(ang) + y * Math.cos(ang);
  38450. x = tmp;
  38451. // colors
  38452. if (faceColors) {
  38453. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38454. }
  38455. }
  38456. // indices from indexes
  38457. for (i = 0; i < fl - 2; i++) {
  38458. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38459. }
  38460. faceIdx += fl;
  38461. }
  38462. }
  38463. VertexData.ComputeNormals(positions, indices, normals);
  38464. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38465. var vertexData = new VertexData();
  38466. vertexData.positions = positions;
  38467. vertexData.indices = indices;
  38468. vertexData.normals = normals;
  38469. vertexData.uvs = uvs;
  38470. if (faceColors && flat) {
  38471. vertexData.colors = colors;
  38472. }
  38473. return vertexData;
  38474. };
  38475. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38476. /**
  38477. * Creates the VertexData of the Torus Knot.
  38478. */
  38479. VertexData.CreateTorusKnot = function (options) {
  38480. var indices = [];
  38481. var positions = [];
  38482. var normals = [];
  38483. var uvs = [];
  38484. var radius = options.radius || 2;
  38485. var tube = options.tube || 0.5;
  38486. var radialSegments = options.radialSegments || 32;
  38487. var tubularSegments = options.tubularSegments || 32;
  38488. var p = options.p || 2;
  38489. var q = options.q || 3;
  38490. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38491. // Helper
  38492. var getPos = function (angle) {
  38493. var cu = Math.cos(angle);
  38494. var su = Math.sin(angle);
  38495. var quOverP = q / p * angle;
  38496. var cs = Math.cos(quOverP);
  38497. var tx = radius * (2 + cs) * 0.5 * cu;
  38498. var ty = radius * (2 + cs) * su * 0.5;
  38499. var tz = radius * Math.sin(quOverP) * 0.5;
  38500. return new BABYLON.Vector3(tx, ty, tz);
  38501. };
  38502. // Vertices
  38503. var i;
  38504. var j;
  38505. for (i = 0; i <= radialSegments; i++) {
  38506. var modI = i % radialSegments;
  38507. var u = modI / radialSegments * 2 * p * Math.PI;
  38508. var p1 = getPos(u);
  38509. var p2 = getPos(u + 0.01);
  38510. var tang = p2.subtract(p1);
  38511. var n = p2.add(p1);
  38512. var bitan = BABYLON.Vector3.Cross(tang, n);
  38513. n = BABYLON.Vector3.Cross(bitan, tang);
  38514. bitan.normalize();
  38515. n.normalize();
  38516. for (j = 0; j < tubularSegments; j++) {
  38517. var modJ = j % tubularSegments;
  38518. var v = modJ / tubularSegments * 2 * Math.PI;
  38519. var cx = -tube * Math.cos(v);
  38520. var cy = tube * Math.sin(v);
  38521. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38522. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38523. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38524. uvs.push(i / radialSegments);
  38525. uvs.push(j / tubularSegments);
  38526. }
  38527. }
  38528. for (i = 0; i < radialSegments; i++) {
  38529. for (j = 0; j < tubularSegments; j++) {
  38530. var jNext = (j + 1) % tubularSegments;
  38531. var a = i * tubularSegments + j;
  38532. var b = (i + 1) * tubularSegments + j;
  38533. var c = (i + 1) * tubularSegments + jNext;
  38534. var d = i * tubularSegments + jNext;
  38535. indices.push(d);
  38536. indices.push(b);
  38537. indices.push(a);
  38538. indices.push(d);
  38539. indices.push(c);
  38540. indices.push(b);
  38541. }
  38542. }
  38543. // Normals
  38544. VertexData.ComputeNormals(positions, indices, normals);
  38545. // Sides
  38546. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  38547. // Result
  38548. var vertexData = new VertexData();
  38549. vertexData.indices = indices;
  38550. vertexData.positions = positions;
  38551. vertexData.normals = normals;
  38552. vertexData.uvs = uvs;
  38553. return vertexData;
  38554. };
  38555. // Tools
  38556. /**
  38557. * @param {any} - positions (number[] or Float32Array)
  38558. * @param {any} - indices (number[] or Uint16Array)
  38559. * @param {any} - normals (number[] or Float32Array)
  38560. * options (optional) :
  38561. * facetPositions : optional array of facet positions (vector3)
  38562. * facetNormals : optional array of facet normals (vector3)
  38563. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38564. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38565. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38566. * bbSize : optional bounding box size data, required for facetPartitioning computation
  38567. * bInfo : optional bounding info, required for facetPartitioning computation
  38568. */
  38569. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38570. // temporary scalar variables
  38571. var index = 0; // facet index
  38572. var p1p2x = 0.0; // p1p2 vector x coordinate
  38573. var p1p2y = 0.0; // p1p2 vector y coordinate
  38574. var p1p2z = 0.0; // p1p2 vector z coordinate
  38575. var p3p2x = 0.0; // p3p2 vector x coordinate
  38576. var p3p2y = 0.0; // p3p2 vector y coordinate
  38577. var p3p2z = 0.0; // p3p2 vector z coordinate
  38578. var faceNormalx = 0.0; // facet normal x coordinate
  38579. var faceNormaly = 0.0; // facet normal y coordinate
  38580. var faceNormalz = 0.0; // facet normal z coordinate
  38581. var length = 0.0; // facet normal length before normalization
  38582. var v1x = 0; // vector1 x index in the positions array
  38583. var v1y = 0; // vector1 y index in the positions array
  38584. var v1z = 0; // vector1 z index in the positions array
  38585. var v2x = 0; // vector2 x index in the positions array
  38586. var v2y = 0; // vector2 y index in the positions array
  38587. var v2z = 0; // vector2 z index in the positions array
  38588. var v3x = 0; // vector3 x index in the positions array
  38589. var v3y = 0; // vector3 y index in the positions array
  38590. var v3z = 0; // vector3 z index in the positions array
  38591. var computeFacetNormals = false;
  38592. var computeFacetPositions = false;
  38593. var computeFacetPartitioning = false;
  38594. if (options) {
  38595. computeFacetNormals = (options.facetNormals) ? true : false;
  38596. computeFacetPositions = (options.facetPositions) ? true : false;
  38597. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38598. }
  38599. // facetPartitioning reinit if needed
  38600. if (computeFacetPartitioning) {
  38601. var ox = 0; // X partitioning index for facet position
  38602. var oy = 0; // Y partinioning index for facet position
  38603. var oz = 0; // Z partinioning index for facet position
  38604. var b1x = 0; // X partitioning index for facet v1 vertex
  38605. var b1y = 0; // Y partitioning index for facet v1 vertex
  38606. var b1z = 0; // z partitioning index for facet v1 vertex
  38607. var b2x = 0; // X partitioning index for facet v2 vertex
  38608. var b2y = 0; // Y partitioning index for facet v2 vertex
  38609. var b2z = 0; // Z partitioning index for facet v2 vertex
  38610. var b3x = 0; // X partitioning index for facet v3 vertex
  38611. var b3y = 0; // Y partitioning index for facet v3 vertex
  38612. var b3z = 0; // Z partitioning index for facet v3 vertex
  38613. var block_idx_o = 0; // facet barycenter block index
  38614. var block_idx_v1 = 0; // v1 vertex block index
  38615. var block_idx_v2 = 0; // v2 vertex block index
  38616. var block_idx_v3 = 0; // v3 vertex block index
  38617. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38618. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38619. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  38620. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  38621. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  38622. var subSq = options.subDiv.max * options.subDiv.max;
  38623. options.facetPartitioning.length = 0;
  38624. }
  38625. // reset the normals
  38626. for (index = 0; index < positions.length; index++) {
  38627. normals[index] = 0.0;
  38628. }
  38629. // Loop : 1 indice triplet = 1 facet
  38630. var nbFaces = indices.length / 3;
  38631. for (index = 0; index < nbFaces; index++) {
  38632. // get the indexes of the coordinates of each vertex of the facet
  38633. v1x = indices[index * 3] * 3;
  38634. v1y = v1x + 1;
  38635. v1z = v1x + 2;
  38636. v2x = indices[index * 3 + 1] * 3;
  38637. v2y = v2x + 1;
  38638. v2z = v2x + 2;
  38639. v3x = indices[index * 3 + 2] * 3;
  38640. v3y = v3x + 1;
  38641. v3z = v3x + 2;
  38642. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38643. p1p2y = positions[v1y] - positions[v2y];
  38644. p1p2z = positions[v1z] - positions[v2z];
  38645. p3p2x = positions[v3x] - positions[v2x];
  38646. p3p2y = positions[v3y] - positions[v2y];
  38647. p3p2z = positions[v3z] - positions[v2z];
  38648. // compute the face normal with the cross product
  38649. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  38650. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  38651. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  38652. // normalize this normal and store it in the array facetData
  38653. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38654. length = (length === 0) ? 1.0 : length;
  38655. faceNormalx /= length;
  38656. faceNormaly /= length;
  38657. faceNormalz /= length;
  38658. if (computeFacetNormals) {
  38659. options.facetNormals[index].x = faceNormalx;
  38660. options.facetNormals[index].y = faceNormaly;
  38661. options.facetNormals[index].z = faceNormalz;
  38662. }
  38663. if (computeFacetPositions) {
  38664. // compute and the facet barycenter coordinates in the array facetPositions
  38665. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38666. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38667. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38668. }
  38669. if (computeFacetPartitioning) {
  38670. // store the facet indexes in arrays in the main facetPartitioning array :
  38671. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38672. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38673. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38674. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38675. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38676. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38677. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38678. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38679. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38680. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38681. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  38682. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  38683. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  38684. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38685. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38686. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38687. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38688. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38689. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38690. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38691. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38692. // push each facet index in each block containing the vertex
  38693. options.facetPartitioning[block_idx_v1].push(index);
  38694. if (block_idx_v2 != block_idx_v1) {
  38695. options.facetPartitioning[block_idx_v2].push(index);
  38696. }
  38697. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38698. options.facetPartitioning[block_idx_v3].push(index);
  38699. }
  38700. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38701. options.facetPartitioning[block_idx_o].push(index);
  38702. }
  38703. }
  38704. // compute the normals anyway
  38705. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38706. normals[v1y] += faceNormaly;
  38707. normals[v1z] += faceNormalz;
  38708. normals[v2x] += faceNormalx;
  38709. normals[v2y] += faceNormaly;
  38710. normals[v2z] += faceNormalz;
  38711. normals[v3x] += faceNormalx;
  38712. normals[v3y] += faceNormaly;
  38713. normals[v3z] += faceNormalz;
  38714. }
  38715. // last normalization of each normal
  38716. for (index = 0; index < normals.length / 3; index++) {
  38717. faceNormalx = normals[index * 3];
  38718. faceNormaly = normals[index * 3 + 1];
  38719. faceNormalz = normals[index * 3 + 2];
  38720. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38721. length = (length === 0) ? 1.0 : length;
  38722. faceNormalx /= length;
  38723. faceNormaly /= length;
  38724. faceNormalz /= length;
  38725. normals[index * 3] = faceNormalx;
  38726. normals[index * 3 + 1] = faceNormaly;
  38727. normals[index * 3 + 2] = faceNormalz;
  38728. }
  38729. };
  38730. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  38731. var li = indices.length;
  38732. var ln = normals.length;
  38733. var i;
  38734. var n;
  38735. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38736. switch (sideOrientation) {
  38737. case BABYLON.Mesh.FRONTSIDE:
  38738. // nothing changed
  38739. break;
  38740. case BABYLON.Mesh.BACKSIDE:
  38741. var tmp;
  38742. // indices
  38743. for (i = 0; i < li; i += 3) {
  38744. tmp = indices[i];
  38745. indices[i] = indices[i + 2];
  38746. indices[i + 2] = tmp;
  38747. }
  38748. // normals
  38749. for (n = 0; n < ln; n++) {
  38750. normals[n] = -normals[n];
  38751. }
  38752. break;
  38753. case BABYLON.Mesh.DOUBLESIDE:
  38754. // positions
  38755. var lp = positions.length;
  38756. var l = lp / 3;
  38757. for (var p = 0; p < lp; p++) {
  38758. positions[lp + p] = positions[p];
  38759. }
  38760. // indices
  38761. for (i = 0; i < li; i += 3) {
  38762. indices[i + li] = indices[i + 2] + l;
  38763. indices[i + 1 + li] = indices[i + 1] + l;
  38764. indices[i + 2 + li] = indices[i] + l;
  38765. }
  38766. // normals
  38767. for (n = 0; n < ln; n++) {
  38768. normals[ln + n] = -normals[n];
  38769. }
  38770. // uvs
  38771. var lu = uvs.length;
  38772. for (var u = 0; u < lu; u++) {
  38773. uvs[u + lu] = uvs[u];
  38774. }
  38775. break;
  38776. }
  38777. };
  38778. /**
  38779. * Creates a new VertexData from the imported parameters.
  38780. */
  38781. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38782. var vertexData = new VertexData();
  38783. // positions
  38784. var positions = parsedVertexData.positions;
  38785. if (positions) {
  38786. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38787. }
  38788. // normals
  38789. var normals = parsedVertexData.normals;
  38790. if (normals) {
  38791. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38792. }
  38793. // tangents
  38794. var tangents = parsedVertexData.tangents;
  38795. if (tangents) {
  38796. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38797. }
  38798. // uvs
  38799. var uvs = parsedVertexData.uvs;
  38800. if (uvs) {
  38801. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38802. }
  38803. // uv2s
  38804. var uv2s = parsedVertexData.uv2s;
  38805. if (uv2s) {
  38806. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38807. }
  38808. // uv3s
  38809. var uv3s = parsedVertexData.uv3s;
  38810. if (uv3s) {
  38811. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38812. }
  38813. // uv4s
  38814. var uv4s = parsedVertexData.uv4s;
  38815. if (uv4s) {
  38816. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38817. }
  38818. // uv5s
  38819. var uv5s = parsedVertexData.uv5s;
  38820. if (uv5s) {
  38821. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38822. }
  38823. // uv6s
  38824. var uv6s = parsedVertexData.uv6s;
  38825. if (uv6s) {
  38826. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38827. }
  38828. // colors
  38829. var colors = parsedVertexData.colors;
  38830. if (colors) {
  38831. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38832. }
  38833. // matricesIndices
  38834. var matricesIndices = parsedVertexData.matricesIndices;
  38835. if (matricesIndices) {
  38836. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38837. }
  38838. // matricesWeights
  38839. var matricesWeights = parsedVertexData.matricesWeights;
  38840. if (matricesWeights) {
  38841. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38842. }
  38843. // indices
  38844. var indices = parsedVertexData.indices;
  38845. if (indices) {
  38846. vertexData.indices = indices;
  38847. }
  38848. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38849. };
  38850. return VertexData;
  38851. }());
  38852. BABYLON.VertexData = VertexData;
  38853. })(BABYLON || (BABYLON = {}));
  38854. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38855. var BABYLON;
  38856. (function (BABYLON) {
  38857. var Tags = (function () {
  38858. function Tags() {
  38859. }
  38860. Tags.EnableFor = function (obj) {
  38861. obj._tags = obj._tags || {};
  38862. obj.hasTags = function () {
  38863. return Tags.HasTags(obj);
  38864. };
  38865. obj.addTags = function (tagsString) {
  38866. return Tags.AddTagsTo(obj, tagsString);
  38867. };
  38868. obj.removeTags = function (tagsString) {
  38869. return Tags.RemoveTagsFrom(obj, tagsString);
  38870. };
  38871. obj.matchesTagsQuery = function (tagsQuery) {
  38872. return Tags.MatchesQuery(obj, tagsQuery);
  38873. };
  38874. };
  38875. Tags.DisableFor = function (obj) {
  38876. delete obj._tags;
  38877. delete obj.hasTags;
  38878. delete obj.addTags;
  38879. delete obj.removeTags;
  38880. delete obj.matchesTagsQuery;
  38881. };
  38882. Tags.HasTags = function (obj) {
  38883. if (!obj._tags) {
  38884. return false;
  38885. }
  38886. return !BABYLON.Tools.IsEmpty(obj._tags);
  38887. };
  38888. Tags.GetTags = function (obj, asString) {
  38889. if (asString === void 0) { asString = true; }
  38890. if (!obj._tags) {
  38891. return null;
  38892. }
  38893. if (asString) {
  38894. var tagsArray = [];
  38895. for (var tag in obj._tags) {
  38896. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  38897. tagsArray.push(tag);
  38898. }
  38899. }
  38900. return tagsArray.join(" ");
  38901. }
  38902. else {
  38903. return obj._tags;
  38904. }
  38905. };
  38906. // the tags 'true' and 'false' are reserved and cannot be used as tags
  38907. // a tag cannot start with '||', '&&', and '!'
  38908. // it cannot contain whitespaces
  38909. Tags.AddTagsTo = function (obj, tagsString) {
  38910. if (!tagsString) {
  38911. return;
  38912. }
  38913. if (typeof tagsString !== "string") {
  38914. return;
  38915. }
  38916. var tags = tagsString.split(" ");
  38917. tags.forEach(function (tag, index, array) {
  38918. Tags._AddTagTo(obj, tag);
  38919. });
  38920. };
  38921. Tags._AddTagTo = function (obj, tag) {
  38922. tag = tag.trim();
  38923. if (tag === "" || tag === "true" || tag === "false") {
  38924. return;
  38925. }
  38926. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  38927. return;
  38928. }
  38929. Tags.EnableFor(obj);
  38930. obj._tags[tag] = true;
  38931. };
  38932. Tags.RemoveTagsFrom = function (obj, tagsString) {
  38933. if (!Tags.HasTags(obj)) {
  38934. return;
  38935. }
  38936. var tags = tagsString.split(" ");
  38937. for (var t in tags) {
  38938. Tags._RemoveTagFrom(obj, tags[t]);
  38939. }
  38940. };
  38941. Tags._RemoveTagFrom = function (obj, tag) {
  38942. delete obj._tags[tag];
  38943. };
  38944. Tags.MatchesQuery = function (obj, tagsQuery) {
  38945. if (tagsQuery === undefined) {
  38946. return true;
  38947. }
  38948. if (tagsQuery === "") {
  38949. return Tags.HasTags(obj);
  38950. }
  38951. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  38952. };
  38953. return Tags;
  38954. }());
  38955. BABYLON.Tags = Tags;
  38956. })(BABYLON || (BABYLON = {}));
  38957. //# sourceMappingURL=babylon.tags.js.map
  38958. var BABYLON;
  38959. (function (BABYLON) {
  38960. var Internals;
  38961. (function (Internals) {
  38962. var AndOrNotEvaluator = (function () {
  38963. function AndOrNotEvaluator() {
  38964. }
  38965. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  38966. if (!query.match(/\([^\(\)]*\)/g)) {
  38967. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  38968. }
  38969. else {
  38970. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  38971. // remove parenthesis
  38972. r = r.slice(1, r.length - 1);
  38973. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  38974. });
  38975. }
  38976. if (query === "true") {
  38977. return true;
  38978. }
  38979. if (query === "false") {
  38980. return false;
  38981. }
  38982. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  38983. };
  38984. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  38985. evaluateCallback = evaluateCallback || (function (r) {
  38986. return r === "true" ? true : false;
  38987. });
  38988. var result;
  38989. var or = parenthesisContent.split("||");
  38990. for (var i in or) {
  38991. if (or.hasOwnProperty(i)) {
  38992. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  38993. var and = ori.split("&&");
  38994. if (and.length > 1) {
  38995. for (var j = 0; j < and.length; ++j) {
  38996. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  38997. if (andj !== "true" && andj !== "false") {
  38998. if (andj[0] === "!") {
  38999. result = !evaluateCallback(andj.substring(1));
  39000. }
  39001. else {
  39002. result = evaluateCallback(andj);
  39003. }
  39004. }
  39005. else {
  39006. result = andj === "true" ? true : false;
  39007. }
  39008. if (!result) {
  39009. ori = "false";
  39010. break;
  39011. }
  39012. }
  39013. }
  39014. if (result || ori === "true") {
  39015. result = true;
  39016. break;
  39017. }
  39018. // result equals false (or undefined)
  39019. if (ori !== "true" && ori !== "false") {
  39020. if (ori[0] === "!") {
  39021. result = !evaluateCallback(ori.substring(1));
  39022. }
  39023. else {
  39024. result = evaluateCallback(ori);
  39025. }
  39026. }
  39027. else {
  39028. result = ori === "true" ? true : false;
  39029. }
  39030. }
  39031. }
  39032. // the whole parenthesis scope is replaced by 'true' or 'false'
  39033. return result ? "true" : "false";
  39034. };
  39035. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  39036. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  39037. // remove whitespaces
  39038. r = r.replace(/[\s]/g, function () { return ""; });
  39039. return r.length % 2 ? "!" : "";
  39040. });
  39041. booleanString = booleanString.trim();
  39042. if (booleanString === "!true") {
  39043. booleanString = "false";
  39044. }
  39045. else if (booleanString === "!false") {
  39046. booleanString = "true";
  39047. }
  39048. return booleanString;
  39049. };
  39050. return AndOrNotEvaluator;
  39051. }());
  39052. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  39053. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39054. })(BABYLON || (BABYLON = {}));
  39055. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  39056. var BABYLON;
  39057. (function (BABYLON) {
  39058. var PostProcessRenderPass = (function () {
  39059. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  39060. this._enabled = true;
  39061. this._refCount = 0;
  39062. this._name = name;
  39063. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  39064. this.setRenderList(renderList);
  39065. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  39066. this._renderTexture.onAfterRenderObservable.add(afterRender);
  39067. this._scene = scene;
  39068. this._renderList = renderList;
  39069. }
  39070. // private
  39071. PostProcessRenderPass.prototype._incRefCount = function () {
  39072. if (this._refCount === 0) {
  39073. this._scene.customRenderTargets.push(this._renderTexture);
  39074. }
  39075. return ++this._refCount;
  39076. };
  39077. PostProcessRenderPass.prototype._decRefCount = function () {
  39078. this._refCount--;
  39079. if (this._refCount <= 0) {
  39080. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  39081. }
  39082. return this._refCount;
  39083. };
  39084. PostProcessRenderPass.prototype._update = function () {
  39085. this.setRenderList(this._renderList);
  39086. };
  39087. // public
  39088. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  39089. this._renderTexture.renderList = renderList;
  39090. };
  39091. PostProcessRenderPass.prototype.getRenderTexture = function () {
  39092. return this._renderTexture;
  39093. };
  39094. return PostProcessRenderPass;
  39095. }());
  39096. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  39097. })(BABYLON || (BABYLON = {}));
  39098. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  39099. var BABYLON;
  39100. (function (BABYLON) {
  39101. var PostProcessRenderEffect = (function () {
  39102. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  39103. this._engine = engine;
  39104. this._name = name;
  39105. this._singleInstance = singleInstance || true;
  39106. this._getPostProcess = getPostProcess;
  39107. this._cameras = [];
  39108. this._indicesForCamera = [];
  39109. this._postProcesses = {};
  39110. this._renderPasses = {};
  39111. this._renderEffectAsPasses = {};
  39112. }
  39113. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39114. get: function () {
  39115. for (var index in this._postProcesses) {
  39116. if (!this._postProcesses[index].isSupported) {
  39117. return false;
  39118. }
  39119. }
  39120. return true;
  39121. },
  39122. enumerable: true,
  39123. configurable: true
  39124. });
  39125. PostProcessRenderEffect.prototype._update = function () {
  39126. for (var renderPassName in this._renderPasses) {
  39127. this._renderPasses[renderPassName]._update();
  39128. }
  39129. };
  39130. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39131. this._renderPasses[renderPass._name] = renderPass;
  39132. this._linkParameters();
  39133. };
  39134. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39135. delete this._renderPasses[renderPass._name];
  39136. this._linkParameters();
  39137. };
  39138. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39139. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39140. this._linkParameters();
  39141. };
  39142. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39143. for (var renderPassName in this._renderPasses) {
  39144. if (renderPassName === passName) {
  39145. return this._renderPasses[passName];
  39146. }
  39147. }
  39148. };
  39149. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39150. this._renderPasses = {};
  39151. this._linkParameters();
  39152. };
  39153. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39154. var cameraKey;
  39155. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39156. for (var i = 0; i < _cam.length; i++) {
  39157. var camera = _cam[i];
  39158. var cameraName = camera.name;
  39159. if (this._singleInstance) {
  39160. cameraKey = 0;
  39161. }
  39162. else {
  39163. cameraKey = cameraName;
  39164. }
  39165. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39166. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39167. if (!this._indicesForCamera[cameraName]) {
  39168. this._indicesForCamera[cameraName] = [];
  39169. }
  39170. this._indicesForCamera[cameraName].push(index);
  39171. if (this._cameras.indexOf(camera) === -1) {
  39172. this._cameras[cameraName] = camera;
  39173. }
  39174. for (var passName in this._renderPasses) {
  39175. this._renderPasses[passName]._incRefCount();
  39176. }
  39177. }
  39178. this._linkParameters();
  39179. };
  39180. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39181. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39182. for (var i = 0; i < _cam.length; i++) {
  39183. var camera = _cam[i];
  39184. var cameraName = camera.name;
  39185. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39186. var index = this._cameras.indexOf(cameraName);
  39187. this._indicesForCamera.splice(index, 1);
  39188. this._cameras.splice(index, 1);
  39189. for (var passName in this._renderPasses) {
  39190. this._renderPasses[passName]._decRefCount();
  39191. }
  39192. }
  39193. };
  39194. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39195. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39196. for (var i = 0; i < _cam.length; i++) {
  39197. var camera = _cam[i];
  39198. var cameraName = camera.name;
  39199. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39200. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39201. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39202. }
  39203. }
  39204. for (var passName in this._renderPasses) {
  39205. this._renderPasses[passName]._incRefCount();
  39206. }
  39207. }
  39208. };
  39209. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39210. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39211. for (var i = 0; i < _cam.length; i++) {
  39212. var camera = _cam[i];
  39213. var cameraName = camera.Name;
  39214. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39215. for (var passName in this._renderPasses) {
  39216. this._renderPasses[passName]._decRefCount();
  39217. }
  39218. }
  39219. };
  39220. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39221. if (this._singleInstance) {
  39222. return this._postProcesses[0];
  39223. }
  39224. else {
  39225. return this._postProcesses[camera.name];
  39226. }
  39227. };
  39228. PostProcessRenderEffect.prototype._linkParameters = function () {
  39229. var _this = this;
  39230. for (var index in this._postProcesses) {
  39231. if (this.applyParameters) {
  39232. this.applyParameters(this._postProcesses[index]);
  39233. }
  39234. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39235. _this._linkTextures(effect);
  39236. });
  39237. }
  39238. };
  39239. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39240. for (var renderPassName in this._renderPasses) {
  39241. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39242. }
  39243. for (var renderEffectName in this._renderEffectAsPasses) {
  39244. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39245. }
  39246. };
  39247. return PostProcessRenderEffect;
  39248. }());
  39249. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39250. })(BABYLON || (BABYLON = {}));
  39251. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39252. var BABYLON;
  39253. (function (BABYLON) {
  39254. var PostProcessRenderPipeline = (function () {
  39255. function PostProcessRenderPipeline(engine, name) {
  39256. this._engine = engine;
  39257. this._name = name;
  39258. this._renderEffects = {};
  39259. this._renderEffectsForIsolatedPass = {};
  39260. this._cameras = [];
  39261. }
  39262. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39263. get: function () {
  39264. for (var renderEffectName in this._renderEffects) {
  39265. if (!this._renderEffects[renderEffectName].isSupported) {
  39266. return false;
  39267. }
  39268. }
  39269. return true;
  39270. },
  39271. enumerable: true,
  39272. configurable: true
  39273. });
  39274. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  39275. this._renderEffects[renderEffect._name] = renderEffect;
  39276. };
  39277. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  39278. var renderEffects = this._renderEffects[renderEffectName];
  39279. if (!renderEffects) {
  39280. return;
  39281. }
  39282. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39283. };
  39284. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  39285. var renderEffects = this._renderEffects[renderEffectName];
  39286. if (!renderEffects) {
  39287. return;
  39288. }
  39289. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39290. };
  39291. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  39292. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39293. var indicesToDelete = [];
  39294. var i;
  39295. for (i = 0; i < _cam.length; i++) {
  39296. var camera = _cam[i];
  39297. var cameraName = camera.name;
  39298. if (this._cameras.indexOf(camera) === -1) {
  39299. this._cameras[cameraName] = camera;
  39300. }
  39301. else if (unique) {
  39302. indicesToDelete.push(i);
  39303. }
  39304. }
  39305. for (i = 0; i < indicesToDelete.length; i++) {
  39306. cameras.splice(indicesToDelete[i], 1);
  39307. }
  39308. for (var renderEffectName in this._renderEffects) {
  39309. this._renderEffects[renderEffectName]._attachCameras(_cam);
  39310. }
  39311. };
  39312. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  39313. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39314. for (var renderEffectName in this._renderEffects) {
  39315. this._renderEffects[renderEffectName]._detachCameras(_cam);
  39316. }
  39317. for (var i = 0; i < _cam.length; i++) {
  39318. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  39319. }
  39320. };
  39321. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  39322. var _this = this;
  39323. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39324. var pass = null;
  39325. var renderEffectName;
  39326. for (renderEffectName in this._renderEffects) {
  39327. pass = this._renderEffects[renderEffectName].getPass(passName);
  39328. if (pass != null) {
  39329. break;
  39330. }
  39331. }
  39332. if (pass === null) {
  39333. return;
  39334. }
  39335. for (renderEffectName in this._renderEffects) {
  39336. this._renderEffects[renderEffectName]._disable(_cam);
  39337. }
  39338. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  39339. for (var i = 0; i < _cam.length; i++) {
  39340. var camera = _cam[i];
  39341. var cameraName = camera.name;
  39342. 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); });
  39343. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  39344. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  39345. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  39346. }
  39347. };
  39348. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  39349. var _this = this;
  39350. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39351. for (var i = 0; i < _cam.length; i++) {
  39352. var camera = _cam[i];
  39353. var cameraName = camera.name;
  39354. 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); });
  39355. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  39356. }
  39357. for (var renderEffectName in this._renderEffects) {
  39358. this._renderEffects[renderEffectName]._enable(_cam);
  39359. }
  39360. };
  39361. PostProcessRenderPipeline.prototype._update = function () {
  39362. for (var renderEffectName in this._renderEffects) {
  39363. this._renderEffects[renderEffectName]._update();
  39364. }
  39365. for (var i = 0; i < this._cameras.length; i++) {
  39366. var cameraName = this._cameras[i].name;
  39367. if (this._renderEffectsForIsolatedPass[cameraName]) {
  39368. this._renderEffectsForIsolatedPass[cameraName]._update();
  39369. }
  39370. }
  39371. };
  39372. PostProcessRenderPipeline.prototype.dispose = function () {
  39373. // Must be implemented by children
  39374. };
  39375. return PostProcessRenderPipeline;
  39376. }());
  39377. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  39378. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  39379. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  39380. })(BABYLON || (BABYLON = {}));
  39381. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  39382. var BABYLON;
  39383. (function (BABYLON) {
  39384. var PostProcessRenderPipelineManager = (function () {
  39385. function PostProcessRenderPipelineManager() {
  39386. this._renderPipelines = {};
  39387. }
  39388. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39389. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39390. };
  39391. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39392. var renderPipeline = this._renderPipelines[renderPipelineName];
  39393. if (!renderPipeline) {
  39394. return;
  39395. }
  39396. renderPipeline._attachCameras(cameras, unique);
  39397. };
  39398. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39399. var renderPipeline = this._renderPipelines[renderPipelineName];
  39400. if (!renderPipeline) {
  39401. return;
  39402. }
  39403. renderPipeline._detachCameras(cameras);
  39404. };
  39405. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39406. var renderPipeline = this._renderPipelines[renderPipelineName];
  39407. if (!renderPipeline) {
  39408. return;
  39409. }
  39410. renderPipeline._enableEffect(renderEffectName, cameras);
  39411. };
  39412. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39413. var renderPipeline = this._renderPipelines[renderPipelineName];
  39414. if (!renderPipeline) {
  39415. return;
  39416. }
  39417. renderPipeline._disableEffect(renderEffectName, cameras);
  39418. };
  39419. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39420. var renderPipeline = this._renderPipelines[renderPipelineName];
  39421. if (!renderPipeline) {
  39422. return;
  39423. }
  39424. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39425. };
  39426. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39427. var renderPipeline = this._renderPipelines[renderPipelineName];
  39428. if (!renderPipeline) {
  39429. return;
  39430. }
  39431. renderPipeline._disableDisplayOnlyPass(cameras);
  39432. };
  39433. PostProcessRenderPipelineManager.prototype.update = function () {
  39434. for (var renderPipelineName in this._renderPipelines) {
  39435. var pipeline = this._renderPipelines[renderPipelineName];
  39436. if (!pipeline.isSupported) {
  39437. pipeline.dispose();
  39438. delete this._renderPipelines[renderPipelineName];
  39439. }
  39440. else {
  39441. pipeline._update();
  39442. }
  39443. }
  39444. };
  39445. return PostProcessRenderPipelineManager;
  39446. }());
  39447. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39448. })(BABYLON || (BABYLON = {}));
  39449. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39450. var BABYLON;
  39451. (function (BABYLON) {
  39452. var BoundingBoxRenderer = (function () {
  39453. function BoundingBoxRenderer(scene) {
  39454. this.frontColor = new BABYLON.Color3(1, 1, 1);
  39455. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  39456. this.showBackLines = true;
  39457. this.renderList = new BABYLON.SmartArray(32);
  39458. this._vertexBuffers = {};
  39459. this._scene = scene;
  39460. }
  39461. BoundingBoxRenderer.prototype._prepareRessources = function () {
  39462. if (this._colorShader) {
  39463. return;
  39464. }
  39465. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  39466. attributes: [BABYLON.VertexBuffer.PositionKind],
  39467. uniforms: ["worldViewProjection", "color"]
  39468. });
  39469. var engine = this._scene.getEngine();
  39470. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  39471. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  39472. 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]);
  39473. };
  39474. BoundingBoxRenderer.prototype.reset = function () {
  39475. this.renderList.reset();
  39476. };
  39477. BoundingBoxRenderer.prototype.render = function () {
  39478. if (this.renderList.length === 0) {
  39479. return;
  39480. }
  39481. this._prepareRessources();
  39482. if (!this._colorShader.isReady()) {
  39483. return;
  39484. }
  39485. var engine = this._scene.getEngine();
  39486. engine.setDepthWrite(false);
  39487. this._colorShader._preBind();
  39488. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  39489. var boundingBox = this.renderList.data[boundingBoxIndex];
  39490. var min = boundingBox.minimum;
  39491. var max = boundingBox.maximum;
  39492. var diff = max.subtract(min);
  39493. var median = min.add(diff.scale(0.5));
  39494. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  39495. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  39496. .multiply(boundingBox.getWorldMatrix());
  39497. // VBOs
  39498. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  39499. if (this.showBackLines) {
  39500. // Back
  39501. engine.setDepthFunctionToGreaterOrEqual();
  39502. this._scene.resetCachedMaterial();
  39503. this._colorShader.setColor4("color", this.backColor.toColor4());
  39504. this._colorShader.bind(worldMatrix);
  39505. // Draw order
  39506. engine.draw(false, 0, 24);
  39507. }
  39508. // Front
  39509. engine.setDepthFunctionToLess();
  39510. this._scene.resetCachedMaterial();
  39511. this._colorShader.setColor4("color", this.frontColor.toColor4());
  39512. this._colorShader.bind(worldMatrix);
  39513. // Draw order
  39514. engine.draw(false, 0, 24);
  39515. }
  39516. this._colorShader.unbind();
  39517. engine.setDepthFunctionToLessOrEqual();
  39518. engine.setDepthWrite(true);
  39519. };
  39520. BoundingBoxRenderer.prototype.dispose = function () {
  39521. if (!this._colorShader) {
  39522. return;
  39523. }
  39524. this.renderList.dispose();
  39525. this._colorShader.dispose();
  39526. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39527. if (buffer) {
  39528. buffer.dispose();
  39529. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39530. }
  39531. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39532. };
  39533. return BoundingBoxRenderer;
  39534. }());
  39535. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  39536. })(BABYLON || (BABYLON = {}));
  39537. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  39538. var BABYLON;
  39539. (function (BABYLON) {
  39540. var Condition = (function () {
  39541. function Condition(actionManager) {
  39542. this._actionManager = actionManager;
  39543. }
  39544. Condition.prototype.isValid = function () {
  39545. return true;
  39546. };
  39547. Condition.prototype._getProperty = function (propertyPath) {
  39548. return this._actionManager._getProperty(propertyPath);
  39549. };
  39550. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  39551. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39552. };
  39553. Condition.prototype.serialize = function () {
  39554. };
  39555. Condition.prototype._serialize = function (serializedCondition) {
  39556. return {
  39557. type: 2,
  39558. children: [],
  39559. name: serializedCondition.name,
  39560. properties: serializedCondition.properties
  39561. };
  39562. };
  39563. return Condition;
  39564. }());
  39565. BABYLON.Condition = Condition;
  39566. var ValueCondition = (function (_super) {
  39567. __extends(ValueCondition, _super);
  39568. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  39569. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  39570. var _this = _super.call(this, actionManager) || this;
  39571. _this.propertyPath = propertyPath;
  39572. _this.value = value;
  39573. _this.operator = operator;
  39574. _this._target = target;
  39575. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  39576. _this._property = _this._getProperty(_this.propertyPath);
  39577. return _this;
  39578. }
  39579. Object.defineProperty(ValueCondition, "IsEqual", {
  39580. get: function () {
  39581. return ValueCondition._IsEqual;
  39582. },
  39583. enumerable: true,
  39584. configurable: true
  39585. });
  39586. Object.defineProperty(ValueCondition, "IsDifferent", {
  39587. get: function () {
  39588. return ValueCondition._IsDifferent;
  39589. },
  39590. enumerable: true,
  39591. configurable: true
  39592. });
  39593. Object.defineProperty(ValueCondition, "IsGreater", {
  39594. get: function () {
  39595. return ValueCondition._IsGreater;
  39596. },
  39597. enumerable: true,
  39598. configurable: true
  39599. });
  39600. Object.defineProperty(ValueCondition, "IsLesser", {
  39601. get: function () {
  39602. return ValueCondition._IsLesser;
  39603. },
  39604. enumerable: true,
  39605. configurable: true
  39606. });
  39607. // Methods
  39608. ValueCondition.prototype.isValid = function () {
  39609. switch (this.operator) {
  39610. case ValueCondition.IsGreater:
  39611. return this._effectiveTarget[this._property] > this.value;
  39612. case ValueCondition.IsLesser:
  39613. return this._effectiveTarget[this._property] < this.value;
  39614. case ValueCondition.IsEqual:
  39615. case ValueCondition.IsDifferent:
  39616. var check;
  39617. if (this.value.equals) {
  39618. check = this.value.equals(this._effectiveTarget[this._property]);
  39619. }
  39620. else {
  39621. check = this.value === this._effectiveTarget[this._property];
  39622. }
  39623. return this.operator === ValueCondition.IsEqual ? check : !check;
  39624. }
  39625. return false;
  39626. };
  39627. ValueCondition.prototype.serialize = function () {
  39628. return this._serialize({
  39629. name: "ValueCondition",
  39630. properties: [
  39631. BABYLON.Action._GetTargetProperty(this._target),
  39632. { name: "propertyPath", value: this.propertyPath },
  39633. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  39634. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  39635. ]
  39636. });
  39637. };
  39638. ValueCondition.GetOperatorName = function (operator) {
  39639. switch (operator) {
  39640. case ValueCondition._IsEqual: return "IsEqual";
  39641. case ValueCondition._IsDifferent: return "IsDifferent";
  39642. case ValueCondition._IsGreater: return "IsGreater";
  39643. case ValueCondition._IsLesser: return "IsLesser";
  39644. default: return "";
  39645. }
  39646. };
  39647. return ValueCondition;
  39648. }(Condition));
  39649. // Statics
  39650. ValueCondition._IsEqual = 0;
  39651. ValueCondition._IsDifferent = 1;
  39652. ValueCondition._IsGreater = 2;
  39653. ValueCondition._IsLesser = 3;
  39654. BABYLON.ValueCondition = ValueCondition;
  39655. var PredicateCondition = (function (_super) {
  39656. __extends(PredicateCondition, _super);
  39657. function PredicateCondition(actionManager, predicate) {
  39658. var _this = _super.call(this, actionManager) || this;
  39659. _this.predicate = predicate;
  39660. return _this;
  39661. }
  39662. PredicateCondition.prototype.isValid = function () {
  39663. return this.predicate();
  39664. };
  39665. return PredicateCondition;
  39666. }(Condition));
  39667. BABYLON.PredicateCondition = PredicateCondition;
  39668. var StateCondition = (function (_super) {
  39669. __extends(StateCondition, _super);
  39670. function StateCondition(actionManager, target, value) {
  39671. var _this = _super.call(this, actionManager) || this;
  39672. _this.value = value;
  39673. _this._target = target;
  39674. return _this;
  39675. }
  39676. // Methods
  39677. StateCondition.prototype.isValid = function () {
  39678. return this._target.state === this.value;
  39679. };
  39680. StateCondition.prototype.serialize = function () {
  39681. return this._serialize({
  39682. name: "StateCondition",
  39683. properties: [
  39684. BABYLON.Action._GetTargetProperty(this._target),
  39685. { name: "value", value: this.value }
  39686. ]
  39687. });
  39688. };
  39689. return StateCondition;
  39690. }(Condition));
  39691. BABYLON.StateCondition = StateCondition;
  39692. })(BABYLON || (BABYLON = {}));
  39693. //# sourceMappingURL=babylon.condition.js.map
  39694. var BABYLON;
  39695. (function (BABYLON) {
  39696. var Action = (function () {
  39697. function Action(triggerOptions, condition) {
  39698. this.triggerOptions = triggerOptions;
  39699. if (triggerOptions.parameter) {
  39700. this.trigger = triggerOptions.trigger;
  39701. this._triggerParameter = triggerOptions.parameter;
  39702. }
  39703. else {
  39704. this.trigger = triggerOptions;
  39705. }
  39706. this._nextActiveAction = this;
  39707. this._condition = condition;
  39708. }
  39709. // Methods
  39710. Action.prototype._prepare = function () {
  39711. };
  39712. Action.prototype.getTriggerParameter = function () {
  39713. return this._triggerParameter;
  39714. };
  39715. Action.prototype._executeCurrent = function (evt) {
  39716. if (this._nextActiveAction._condition) {
  39717. var condition = this._nextActiveAction._condition;
  39718. var currentRenderId = this._actionManager.getScene().getRenderId();
  39719. // We cache the current evaluation for the current frame
  39720. if (condition._evaluationId === currentRenderId) {
  39721. if (!condition._currentResult) {
  39722. return;
  39723. }
  39724. }
  39725. else {
  39726. condition._evaluationId = currentRenderId;
  39727. if (!condition.isValid()) {
  39728. condition._currentResult = false;
  39729. return;
  39730. }
  39731. condition._currentResult = true;
  39732. }
  39733. }
  39734. this._nextActiveAction.execute(evt);
  39735. this.skipToNextActiveAction();
  39736. };
  39737. Action.prototype.execute = function (evt) {
  39738. };
  39739. Action.prototype.skipToNextActiveAction = function () {
  39740. if (this._nextActiveAction._child) {
  39741. if (!this._nextActiveAction._child._actionManager) {
  39742. this._nextActiveAction._child._actionManager = this._actionManager;
  39743. }
  39744. this._nextActiveAction = this._nextActiveAction._child;
  39745. }
  39746. else {
  39747. this._nextActiveAction = this;
  39748. }
  39749. };
  39750. Action.prototype.then = function (action) {
  39751. this._child = action;
  39752. action._actionManager = this._actionManager;
  39753. action._prepare();
  39754. return action;
  39755. };
  39756. Action.prototype._getProperty = function (propertyPath) {
  39757. return this._actionManager._getProperty(propertyPath);
  39758. };
  39759. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  39760. return this._actionManager._getEffectiveTarget(target, propertyPath);
  39761. };
  39762. Action.prototype.serialize = function (parent) {
  39763. };
  39764. // Called by BABYLON.Action objects in serialize(...). Internal use
  39765. Action.prototype._serialize = function (serializedAction, parent) {
  39766. var serializationObject = {
  39767. type: 1,
  39768. children: [],
  39769. name: serializedAction.name,
  39770. properties: serializedAction.properties || []
  39771. };
  39772. // Serialize child
  39773. if (this._child) {
  39774. this._child.serialize(serializationObject);
  39775. }
  39776. // Check if "this" has a condition
  39777. if (this._condition) {
  39778. var serializedCondition = this._condition.serialize();
  39779. serializedCondition.children.push(serializationObject);
  39780. if (parent) {
  39781. parent.children.push(serializedCondition);
  39782. }
  39783. return serializedCondition;
  39784. }
  39785. if (parent) {
  39786. parent.children.push(serializationObject);
  39787. }
  39788. return serializationObject;
  39789. };
  39790. return Action;
  39791. }());
  39792. Action._SerializeValueAsString = function (value) {
  39793. if (typeof value === "number") {
  39794. return value.toString();
  39795. }
  39796. if (typeof value === "boolean") {
  39797. return value ? "true" : "false";
  39798. }
  39799. if (value instanceof BABYLON.Vector2) {
  39800. return value.x + ", " + value.y;
  39801. }
  39802. if (value instanceof BABYLON.Vector3) {
  39803. return value.x + ", " + value.y + ", " + value.z;
  39804. }
  39805. if (value instanceof BABYLON.Color3) {
  39806. return value.r + ", " + value.g + ", " + value.b;
  39807. }
  39808. if (value instanceof BABYLON.Color4) {
  39809. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  39810. }
  39811. return value; // string
  39812. };
  39813. Action._GetTargetProperty = function (target) {
  39814. return {
  39815. name: "target",
  39816. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  39817. : target instanceof BABYLON.Light ? "LightProperties"
  39818. : target instanceof BABYLON.Camera ? "CameraProperties"
  39819. : "SceneProperties",
  39820. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  39821. };
  39822. };
  39823. BABYLON.Action = Action;
  39824. })(BABYLON || (BABYLON = {}));
  39825. //# sourceMappingURL=babylon.action.js.map
  39826. var BABYLON;
  39827. (function (BABYLON) {
  39828. /**
  39829. * ActionEvent is the event beint sent when an action is triggered.
  39830. */
  39831. var ActionEvent = (function () {
  39832. /**
  39833. * @constructor
  39834. * @param source The mesh or sprite that triggered the action.
  39835. * @param pointerX The X mouse cursor position at the time of the event
  39836. * @param pointerY The Y mouse cursor position at the time of the event
  39837. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  39838. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  39839. */
  39840. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  39841. this.source = source;
  39842. this.pointerX = pointerX;
  39843. this.pointerY = pointerY;
  39844. this.meshUnderPointer = meshUnderPointer;
  39845. this.sourceEvent = sourceEvent;
  39846. this.additionalData = additionalData;
  39847. }
  39848. /**
  39849. * Helper function to auto-create an ActionEvent from a source mesh.
  39850. * @param source The source mesh that triggered the event
  39851. * @param evt {Event} The original (browser) event
  39852. */
  39853. ActionEvent.CreateNew = function (source, evt, additionalData) {
  39854. var scene = source.getScene();
  39855. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39856. };
  39857. /**
  39858. * Helper function to auto-create an ActionEvent from a source mesh.
  39859. * @param source The source sprite that triggered the event
  39860. * @param scene Scene associated with the sprite
  39861. * @param evt {Event} The original (browser) event
  39862. */
  39863. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  39864. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  39865. };
  39866. /**
  39867. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  39868. * @param scene the scene where the event occurred
  39869. * @param evt {Event} The original (browser) event
  39870. */
  39871. ActionEvent.CreateNewFromScene = function (scene, evt) {
  39872. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  39873. };
  39874. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  39875. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  39876. };
  39877. return ActionEvent;
  39878. }());
  39879. BABYLON.ActionEvent = ActionEvent;
  39880. /**
  39881. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  39882. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  39883. */
  39884. var ActionManager = (function () {
  39885. function ActionManager(scene) {
  39886. // Members
  39887. this.actions = new Array();
  39888. this.hoverCursor = '';
  39889. this._scene = scene;
  39890. scene._actionManagers.push(this);
  39891. }
  39892. Object.defineProperty(ActionManager, "NothingTrigger", {
  39893. get: function () {
  39894. return ActionManager._NothingTrigger;
  39895. },
  39896. enumerable: true,
  39897. configurable: true
  39898. });
  39899. Object.defineProperty(ActionManager, "OnPickTrigger", {
  39900. get: function () {
  39901. return ActionManager._OnPickTrigger;
  39902. },
  39903. enumerable: true,
  39904. configurable: true
  39905. });
  39906. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  39907. get: function () {
  39908. return ActionManager._OnLeftPickTrigger;
  39909. },
  39910. enumerable: true,
  39911. configurable: true
  39912. });
  39913. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  39914. get: function () {
  39915. return ActionManager._OnRightPickTrigger;
  39916. },
  39917. enumerable: true,
  39918. configurable: true
  39919. });
  39920. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  39921. get: function () {
  39922. return ActionManager._OnCenterPickTrigger;
  39923. },
  39924. enumerable: true,
  39925. configurable: true
  39926. });
  39927. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  39928. get: function () {
  39929. return ActionManager._OnPickDownTrigger;
  39930. },
  39931. enumerable: true,
  39932. configurable: true
  39933. });
  39934. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  39935. get: function () {
  39936. return ActionManager._OnDoublePickTrigger;
  39937. },
  39938. enumerable: true,
  39939. configurable: true
  39940. });
  39941. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  39942. get: function () {
  39943. return ActionManager._OnPickUpTrigger;
  39944. },
  39945. enumerable: true,
  39946. configurable: true
  39947. });
  39948. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  39949. /// This trigger will only be raised if you also declared a OnPickDown
  39950. get: function () {
  39951. return ActionManager._OnPickOutTrigger;
  39952. },
  39953. enumerable: true,
  39954. configurable: true
  39955. });
  39956. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  39957. get: function () {
  39958. return ActionManager._OnLongPressTrigger;
  39959. },
  39960. enumerable: true,
  39961. configurable: true
  39962. });
  39963. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  39964. get: function () {
  39965. return ActionManager._OnPointerOverTrigger;
  39966. },
  39967. enumerable: true,
  39968. configurable: true
  39969. });
  39970. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  39971. get: function () {
  39972. return ActionManager._OnPointerOutTrigger;
  39973. },
  39974. enumerable: true,
  39975. configurable: true
  39976. });
  39977. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  39978. get: function () {
  39979. return ActionManager._OnEveryFrameTrigger;
  39980. },
  39981. enumerable: true,
  39982. configurable: true
  39983. });
  39984. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  39985. get: function () {
  39986. return ActionManager._OnIntersectionEnterTrigger;
  39987. },
  39988. enumerable: true,
  39989. configurable: true
  39990. });
  39991. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  39992. get: function () {
  39993. return ActionManager._OnIntersectionExitTrigger;
  39994. },
  39995. enumerable: true,
  39996. configurable: true
  39997. });
  39998. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  39999. get: function () {
  40000. return ActionManager._OnKeyDownTrigger;
  40001. },
  40002. enumerable: true,
  40003. configurable: true
  40004. });
  40005. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  40006. get: function () {
  40007. return ActionManager._OnKeyUpTrigger;
  40008. },
  40009. enumerable: true,
  40010. configurable: true
  40011. });
  40012. // Methods
  40013. ActionManager.prototype.dispose = function () {
  40014. var index = this._scene._actionManagers.indexOf(this);
  40015. for (var i = 0; i < this.actions.length; i++) {
  40016. var action = this.actions[i];
  40017. ActionManager.Triggers[action.trigger]--;
  40018. if (ActionManager.Triggers[action.trigger] === 0) {
  40019. delete ActionManager.Triggers[action.trigger];
  40020. }
  40021. }
  40022. if (index > -1) {
  40023. this._scene._actionManagers.splice(index, 1);
  40024. }
  40025. };
  40026. ActionManager.prototype.getScene = function () {
  40027. return this._scene;
  40028. };
  40029. /**
  40030. * Does this action manager handles actions of any of the given triggers
  40031. * @param {number[]} triggers - the triggers to be tested
  40032. * @return {boolean} whether one (or more) of the triggers is handeled
  40033. */
  40034. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  40035. for (var index = 0; index < this.actions.length; index++) {
  40036. var action = this.actions[index];
  40037. if (triggers.indexOf(action.trigger) > -1) {
  40038. return true;
  40039. }
  40040. }
  40041. return false;
  40042. };
  40043. /**
  40044. * Does this action manager handles actions of a given trigger
  40045. * @param {number} trigger - the trigger to be tested
  40046. * @return {boolean} whether the trigger is handeled
  40047. */
  40048. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  40049. for (var index = 0; index < this.actions.length; index++) {
  40050. var action = this.actions[index];
  40051. if (action.trigger === trigger) {
  40052. return true;
  40053. }
  40054. }
  40055. return false;
  40056. };
  40057. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  40058. /**
  40059. * Does this action manager has pointer triggers
  40060. * @return {boolean} whether or not it has pointer triggers
  40061. */
  40062. get: function () {
  40063. for (var index = 0; index < this.actions.length; index++) {
  40064. var action = this.actions[index];
  40065. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  40066. return true;
  40067. }
  40068. }
  40069. return false;
  40070. },
  40071. enumerable: true,
  40072. configurable: true
  40073. });
  40074. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  40075. /**
  40076. * Does this action manager has pick triggers
  40077. * @return {boolean} whether or not it has pick triggers
  40078. */
  40079. get: function () {
  40080. for (var index = 0; index < this.actions.length; index++) {
  40081. var action = this.actions[index];
  40082. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  40083. return true;
  40084. }
  40085. }
  40086. return false;
  40087. },
  40088. enumerable: true,
  40089. configurable: true
  40090. });
  40091. Object.defineProperty(ActionManager, "HasTriggers", {
  40092. /**
  40093. * Does exist one action manager with at least one trigger
  40094. * @return {boolean} whether or not it exists one action manager with one trigger
  40095. **/
  40096. get: function () {
  40097. for (var t in ActionManager.Triggers) {
  40098. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40099. return true;
  40100. }
  40101. }
  40102. return false;
  40103. },
  40104. enumerable: true,
  40105. configurable: true
  40106. });
  40107. Object.defineProperty(ActionManager, "HasPickTriggers", {
  40108. /**
  40109. * Does exist one action manager with at least one pick trigger
  40110. * @return {boolean} whether or not it exists one action manager with one pick trigger
  40111. **/
  40112. get: function () {
  40113. for (var t in ActionManager.Triggers) {
  40114. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40115. var t_int = parseInt(t);
  40116. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  40117. return true;
  40118. }
  40119. }
  40120. }
  40121. return false;
  40122. },
  40123. enumerable: true,
  40124. configurable: true
  40125. });
  40126. /**
  40127. * Does exist one action manager that handles actions of a given trigger
  40128. * @param {number} trigger - the trigger to be tested
  40129. * @return {boolean} whether the trigger is handeled by at least one action manager
  40130. **/
  40131. ActionManager.HasSpecificTrigger = function (trigger) {
  40132. for (var t in ActionManager.Triggers) {
  40133. if (ActionManager.Triggers.hasOwnProperty(t)) {
  40134. var t_int = parseInt(t);
  40135. if (t_int === trigger) {
  40136. return true;
  40137. }
  40138. }
  40139. }
  40140. return false;
  40141. };
  40142. /**
  40143. * Registers an action to this action manager
  40144. * @param {BABYLON.Action} action - the action to be registered
  40145. * @return {BABYLON.Action} the action amended (prepared) after registration
  40146. */
  40147. ActionManager.prototype.registerAction = function (action) {
  40148. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  40149. if (this.getScene().actionManager !== this) {
  40150. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  40151. return null;
  40152. }
  40153. }
  40154. this.actions.push(action);
  40155. if (ActionManager.Triggers[action.trigger]) {
  40156. ActionManager.Triggers[action.trigger]++;
  40157. }
  40158. else {
  40159. ActionManager.Triggers[action.trigger] = 1;
  40160. }
  40161. action._actionManager = this;
  40162. action._prepare();
  40163. return action;
  40164. };
  40165. /**
  40166. * Process a specific trigger
  40167. * @param {number} trigger - the trigger to process
  40168. * @param evt {BABYLON.ActionEvent} the event details to be processed
  40169. */
  40170. ActionManager.prototype.processTrigger = function (trigger, evt) {
  40171. for (var index = 0; index < this.actions.length; index++) {
  40172. var action = this.actions[index];
  40173. if (action.trigger === trigger) {
  40174. if (trigger === ActionManager.OnKeyUpTrigger
  40175. || trigger === ActionManager.OnKeyDownTrigger) {
  40176. var parameter = action.getTriggerParameter();
  40177. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  40178. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  40179. var actualkey = String.fromCharCode(unicode).toLowerCase();
  40180. if (actualkey !== parameter.toLowerCase()) {
  40181. continue;
  40182. }
  40183. }
  40184. }
  40185. action._executeCurrent(evt);
  40186. }
  40187. }
  40188. };
  40189. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  40190. var properties = propertyPath.split(".");
  40191. for (var index = 0; index < properties.length - 1; index++) {
  40192. target = target[properties[index]];
  40193. }
  40194. return target;
  40195. };
  40196. ActionManager.prototype._getProperty = function (propertyPath) {
  40197. var properties = propertyPath.split(".");
  40198. return properties[properties.length - 1];
  40199. };
  40200. ActionManager.prototype.serialize = function (name) {
  40201. var root = {
  40202. children: [],
  40203. name: name,
  40204. type: 3,
  40205. properties: [] // Empty for root but required
  40206. };
  40207. for (var i = 0; i < this.actions.length; i++) {
  40208. var triggerObject = {
  40209. type: 0,
  40210. children: [],
  40211. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  40212. properties: []
  40213. };
  40214. var triggerOptions = this.actions[i].triggerOptions;
  40215. if (triggerOptions && typeof triggerOptions !== "number") {
  40216. if (triggerOptions.parameter instanceof BABYLON.Node) {
  40217. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  40218. }
  40219. else {
  40220. var parameter = {};
  40221. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  40222. if (triggerOptions.parameter.mesh) {
  40223. parameter._meshId = triggerOptions.parameter.mesh.id;
  40224. }
  40225. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  40226. }
  40227. }
  40228. // Serialize child action, recursively
  40229. this.actions[i].serialize(triggerObject);
  40230. // Add serialized trigger
  40231. root.children.push(triggerObject);
  40232. }
  40233. return root;
  40234. };
  40235. ActionManager.Parse = function (parsedActions, object, scene) {
  40236. var actionManager = new BABYLON.ActionManager(scene);
  40237. if (object === null)
  40238. scene.actionManager = actionManager;
  40239. else
  40240. object.actionManager = actionManager;
  40241. // instanciate a new object
  40242. var instanciate = function (name, params) {
  40243. var newInstance = Object.create(BABYLON[name].prototype);
  40244. newInstance.constructor.apply(newInstance, params);
  40245. return newInstance;
  40246. };
  40247. var parseParameter = function (name, value, target, propertyPath) {
  40248. if (propertyPath === null) {
  40249. // String, boolean or float
  40250. var floatValue = parseFloat(value);
  40251. if (value === "true" || value === "false")
  40252. return value === "true";
  40253. else
  40254. return isNaN(floatValue) ? value : floatValue;
  40255. }
  40256. var effectiveTarget = propertyPath.split(".");
  40257. var values = value.split(",");
  40258. // Get effective Target
  40259. for (var i = 0; i < effectiveTarget.length; i++) {
  40260. target = target[effectiveTarget[i]];
  40261. }
  40262. // Return appropriate value with its type
  40263. if (typeof (target) === "boolean")
  40264. return values[0] === "true";
  40265. if (typeof (target) === "string")
  40266. return values[0];
  40267. // Parameters with multiple values such as Vector3 etc.
  40268. var split = new Array();
  40269. for (var i = 0; i < values.length; i++)
  40270. split.push(parseFloat(values[i]));
  40271. if (target instanceof BABYLON.Vector3)
  40272. return BABYLON.Vector3.FromArray(split);
  40273. if (target instanceof BABYLON.Vector4)
  40274. return BABYLON.Vector4.FromArray(split);
  40275. if (target instanceof BABYLON.Color3)
  40276. return BABYLON.Color3.FromArray(split);
  40277. if (target instanceof BABYLON.Color4)
  40278. return BABYLON.Color4.FromArray(split);
  40279. return parseFloat(values[0]);
  40280. };
  40281. // traverse graph per trigger
  40282. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  40283. if (combineArray === void 0) { combineArray = null; }
  40284. if (parsedAction.detached)
  40285. return;
  40286. var parameters = new Array();
  40287. var target = null;
  40288. var propertyPath = null;
  40289. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  40290. // Parameters
  40291. if (parsedAction.type === 2)
  40292. parameters.push(actionManager);
  40293. else
  40294. parameters.push(trigger);
  40295. if (combine) {
  40296. var actions = new Array();
  40297. for (var j = 0; j < parsedAction.combine.length; j++) {
  40298. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  40299. }
  40300. parameters.push(actions);
  40301. }
  40302. else {
  40303. for (var i = 0; i < parsedAction.properties.length; i++) {
  40304. var value = parsedAction.properties[i].value;
  40305. var name = parsedAction.properties[i].name;
  40306. var targetType = parsedAction.properties[i].targetType;
  40307. if (name === "target")
  40308. if (targetType !== null && targetType === "SceneProperties")
  40309. value = target = scene;
  40310. else
  40311. value = target = scene.getNodeByName(value);
  40312. else if (name === "parent")
  40313. value = scene.getNodeByName(value);
  40314. else if (name === "sound")
  40315. value = scene.getSoundByName(value);
  40316. else if (name !== "propertyPath") {
  40317. if (parsedAction.type === 2 && name === "operator")
  40318. value = BABYLON.ValueCondition[value];
  40319. else
  40320. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  40321. }
  40322. else {
  40323. propertyPath = value;
  40324. }
  40325. parameters.push(value);
  40326. }
  40327. }
  40328. if (combineArray === null) {
  40329. parameters.push(condition);
  40330. }
  40331. else {
  40332. parameters.push(null);
  40333. }
  40334. // If interpolate value action
  40335. if (parsedAction.name === "InterpolateValueAction") {
  40336. var param = parameters[parameters.length - 2];
  40337. parameters[parameters.length - 1] = param;
  40338. parameters[parameters.length - 2] = condition;
  40339. }
  40340. // Action or condition(s) and not CombineAction
  40341. var newAction = instanciate(parsedAction.name, parameters);
  40342. if (newAction instanceof BABYLON.Condition && condition !== null) {
  40343. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  40344. if (action)
  40345. action.then(nothing);
  40346. else
  40347. actionManager.registerAction(nothing);
  40348. action = nothing;
  40349. }
  40350. if (combineArray === null) {
  40351. if (newAction instanceof BABYLON.Condition) {
  40352. condition = newAction;
  40353. newAction = action;
  40354. }
  40355. else {
  40356. condition = null;
  40357. if (action)
  40358. action.then(newAction);
  40359. else
  40360. actionManager.registerAction(newAction);
  40361. }
  40362. }
  40363. else {
  40364. combineArray.push(newAction);
  40365. }
  40366. for (var i = 0; i < parsedAction.children.length; i++)
  40367. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  40368. };
  40369. // triggers
  40370. for (var i = 0; i < parsedActions.children.length; i++) {
  40371. var triggerParams;
  40372. var trigger = parsedActions.children[i];
  40373. if (trigger.properties.length > 0) {
  40374. var param = trigger.properties[0].value;
  40375. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  40376. if (value._meshId) {
  40377. value.mesh = scene.getMeshByID(value._meshId);
  40378. }
  40379. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  40380. }
  40381. else
  40382. triggerParams = BABYLON.ActionManager[trigger.name];
  40383. for (var j = 0; j < trigger.children.length; j++) {
  40384. if (!trigger.detached)
  40385. traverse(trigger.children[j], triggerParams, null, null);
  40386. }
  40387. }
  40388. };
  40389. ActionManager.GetTriggerName = function (trigger) {
  40390. switch (trigger) {
  40391. case 0: return "NothingTrigger";
  40392. case 1: return "OnPickTrigger";
  40393. case 2: return "OnLeftPickTrigger";
  40394. case 3: return "OnRightPickTrigger";
  40395. case 4: return "OnCenterPickTrigger";
  40396. case 5: return "OnPickDownTrigger";
  40397. case 6: return "OnPickUpTrigger";
  40398. case 7: return "OnLongPressTrigger";
  40399. case 8: return "OnPointerOverTrigger";
  40400. case 9: return "OnPointerOutTrigger";
  40401. case 10: return "OnEveryFrameTrigger";
  40402. case 11: return "OnIntersectionEnterTrigger";
  40403. case 12: return "OnIntersectionExitTrigger";
  40404. case 13: return "OnKeyDownTrigger";
  40405. case 14: return "OnKeyUpTrigger";
  40406. case 15: return "OnPickOutTrigger";
  40407. default: return "";
  40408. }
  40409. };
  40410. return ActionManager;
  40411. }());
  40412. // Statics
  40413. ActionManager._NothingTrigger = 0;
  40414. ActionManager._OnPickTrigger = 1;
  40415. ActionManager._OnLeftPickTrigger = 2;
  40416. ActionManager._OnRightPickTrigger = 3;
  40417. ActionManager._OnCenterPickTrigger = 4;
  40418. ActionManager._OnPickDownTrigger = 5;
  40419. ActionManager._OnDoublePickTrigger = 6;
  40420. ActionManager._OnPickUpTrigger = 7;
  40421. ActionManager._OnLongPressTrigger = 8;
  40422. ActionManager._OnPointerOverTrigger = 9;
  40423. ActionManager._OnPointerOutTrigger = 10;
  40424. ActionManager._OnEveryFrameTrigger = 11;
  40425. ActionManager._OnIntersectionEnterTrigger = 12;
  40426. ActionManager._OnIntersectionExitTrigger = 13;
  40427. ActionManager._OnKeyDownTrigger = 14;
  40428. ActionManager._OnKeyUpTrigger = 15;
  40429. ActionManager._OnPickOutTrigger = 16;
  40430. ActionManager.Triggers = {};
  40431. BABYLON.ActionManager = ActionManager;
  40432. })(BABYLON || (BABYLON = {}));
  40433. //# sourceMappingURL=babylon.actionManager.js.map
  40434. var BABYLON;
  40435. (function (BABYLON) {
  40436. var InterpolateValueAction = (function (_super) {
  40437. __extends(InterpolateValueAction, _super);
  40438. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  40439. if (duration === void 0) { duration = 1000; }
  40440. var _this = _super.call(this, triggerOptions, condition) || this;
  40441. _this.propertyPath = propertyPath;
  40442. _this.value = value;
  40443. _this.duration = duration;
  40444. _this.stopOtherAnimations = stopOtherAnimations;
  40445. _this.onInterpolationDone = onInterpolationDone;
  40446. _this._target = _this._effectiveTarget = target;
  40447. return _this;
  40448. }
  40449. InterpolateValueAction.prototype._prepare = function () {
  40450. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40451. this._property = this._getProperty(this.propertyPath);
  40452. };
  40453. InterpolateValueAction.prototype.execute = function () {
  40454. var scene = this._actionManager.getScene();
  40455. var keys = [
  40456. {
  40457. frame: 0,
  40458. value: this._effectiveTarget[this._property]
  40459. }, {
  40460. frame: 100,
  40461. value: this.value
  40462. }
  40463. ];
  40464. var dataType;
  40465. if (typeof this.value === "number") {
  40466. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  40467. }
  40468. else if (this.value instanceof BABYLON.Color3) {
  40469. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  40470. }
  40471. else if (this.value instanceof BABYLON.Vector3) {
  40472. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  40473. }
  40474. else if (this.value instanceof BABYLON.Matrix) {
  40475. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  40476. }
  40477. else if (this.value instanceof BABYLON.Quaternion) {
  40478. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  40479. }
  40480. else {
  40481. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  40482. return;
  40483. }
  40484. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40485. animation.setKeys(keys);
  40486. if (this.stopOtherAnimations) {
  40487. scene.stopAnimation(this._effectiveTarget);
  40488. }
  40489. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  40490. };
  40491. InterpolateValueAction.prototype.serialize = function (parent) {
  40492. return _super.prototype._serialize.call(this, {
  40493. name: "InterpolateValueAction",
  40494. properties: [
  40495. BABYLON.Action._GetTargetProperty(this._target),
  40496. { name: "propertyPath", value: this.propertyPath },
  40497. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  40498. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  40499. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  40500. ]
  40501. }, parent);
  40502. };
  40503. return InterpolateValueAction;
  40504. }(BABYLON.Action));
  40505. BABYLON.InterpolateValueAction = InterpolateValueAction;
  40506. })(BABYLON || (BABYLON = {}));
  40507. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  40508. var BABYLON;
  40509. (function (BABYLON) {
  40510. var SwitchBooleanAction = (function (_super) {
  40511. __extends(SwitchBooleanAction, _super);
  40512. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  40513. var _this = _super.call(this, triggerOptions, condition) || this;
  40514. _this.propertyPath = propertyPath;
  40515. _this._target = _this._effectiveTarget = target;
  40516. return _this;
  40517. }
  40518. SwitchBooleanAction.prototype._prepare = function () {
  40519. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40520. this._property = this._getProperty(this.propertyPath);
  40521. };
  40522. SwitchBooleanAction.prototype.execute = function () {
  40523. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  40524. };
  40525. SwitchBooleanAction.prototype.serialize = function (parent) {
  40526. return _super.prototype._serialize.call(this, {
  40527. name: "SwitchBooleanAction",
  40528. properties: [
  40529. BABYLON.Action._GetTargetProperty(this._target),
  40530. { name: "propertyPath", value: this.propertyPath }
  40531. ]
  40532. }, parent);
  40533. };
  40534. return SwitchBooleanAction;
  40535. }(BABYLON.Action));
  40536. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  40537. var SetStateAction = (function (_super) {
  40538. __extends(SetStateAction, _super);
  40539. function SetStateAction(triggerOptions, target, value, condition) {
  40540. var _this = _super.call(this, triggerOptions, condition) || this;
  40541. _this.value = value;
  40542. _this._target = target;
  40543. return _this;
  40544. }
  40545. SetStateAction.prototype.execute = function () {
  40546. this._target.state = this.value;
  40547. };
  40548. SetStateAction.prototype.serialize = function (parent) {
  40549. return _super.prototype._serialize.call(this, {
  40550. name: "SetStateAction",
  40551. properties: [
  40552. BABYLON.Action._GetTargetProperty(this._target),
  40553. { name: "value", value: this.value }
  40554. ]
  40555. }, parent);
  40556. };
  40557. return SetStateAction;
  40558. }(BABYLON.Action));
  40559. BABYLON.SetStateAction = SetStateAction;
  40560. var SetValueAction = (function (_super) {
  40561. __extends(SetValueAction, _super);
  40562. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  40563. var _this = _super.call(this, triggerOptions, condition) || this;
  40564. _this.propertyPath = propertyPath;
  40565. _this.value = value;
  40566. _this._target = _this._effectiveTarget = target;
  40567. return _this;
  40568. }
  40569. SetValueAction.prototype._prepare = function () {
  40570. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40571. this._property = this._getProperty(this.propertyPath);
  40572. };
  40573. SetValueAction.prototype.execute = function () {
  40574. this._effectiveTarget[this._property] = this.value;
  40575. if (this._target.markAsDirty) {
  40576. this._target.markAsDirty(this._property);
  40577. }
  40578. };
  40579. SetValueAction.prototype.serialize = function (parent) {
  40580. return _super.prototype._serialize.call(this, {
  40581. name: "SetValueAction",
  40582. properties: [
  40583. BABYLON.Action._GetTargetProperty(this._target),
  40584. { name: "propertyPath", value: this.propertyPath },
  40585. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40586. ]
  40587. }, parent);
  40588. };
  40589. return SetValueAction;
  40590. }(BABYLON.Action));
  40591. BABYLON.SetValueAction = SetValueAction;
  40592. var IncrementValueAction = (function (_super) {
  40593. __extends(IncrementValueAction, _super);
  40594. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  40595. var _this = _super.call(this, triggerOptions, condition) || this;
  40596. _this.propertyPath = propertyPath;
  40597. _this.value = value;
  40598. _this._target = _this._effectiveTarget = target;
  40599. return _this;
  40600. }
  40601. IncrementValueAction.prototype._prepare = function () {
  40602. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  40603. this._property = this._getProperty(this.propertyPath);
  40604. if (typeof this._effectiveTarget[this._property] !== "number") {
  40605. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  40606. }
  40607. };
  40608. IncrementValueAction.prototype.execute = function () {
  40609. this._effectiveTarget[this._property] += this.value;
  40610. if (this._target.markAsDirty) {
  40611. this._target.markAsDirty(this._property);
  40612. }
  40613. };
  40614. IncrementValueAction.prototype.serialize = function (parent) {
  40615. return _super.prototype._serialize.call(this, {
  40616. name: "IncrementValueAction",
  40617. properties: [
  40618. BABYLON.Action._GetTargetProperty(this._target),
  40619. { name: "propertyPath", value: this.propertyPath },
  40620. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  40621. ]
  40622. }, parent);
  40623. };
  40624. return IncrementValueAction;
  40625. }(BABYLON.Action));
  40626. BABYLON.IncrementValueAction = IncrementValueAction;
  40627. var PlayAnimationAction = (function (_super) {
  40628. __extends(PlayAnimationAction, _super);
  40629. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  40630. var _this = _super.call(this, triggerOptions, condition) || this;
  40631. _this.from = from;
  40632. _this.to = to;
  40633. _this.loop = loop;
  40634. _this._target = target;
  40635. return _this;
  40636. }
  40637. PlayAnimationAction.prototype._prepare = function () {
  40638. };
  40639. PlayAnimationAction.prototype.execute = function () {
  40640. var scene = this._actionManager.getScene();
  40641. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  40642. };
  40643. PlayAnimationAction.prototype.serialize = function (parent) {
  40644. return _super.prototype._serialize.call(this, {
  40645. name: "PlayAnimationAction",
  40646. properties: [
  40647. BABYLON.Action._GetTargetProperty(this._target),
  40648. { name: "from", value: String(this.from) },
  40649. { name: "to", value: String(this.to) },
  40650. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  40651. ]
  40652. }, parent);
  40653. };
  40654. return PlayAnimationAction;
  40655. }(BABYLON.Action));
  40656. BABYLON.PlayAnimationAction = PlayAnimationAction;
  40657. var StopAnimationAction = (function (_super) {
  40658. __extends(StopAnimationAction, _super);
  40659. function StopAnimationAction(triggerOptions, target, condition) {
  40660. var _this = _super.call(this, triggerOptions, condition) || this;
  40661. _this._target = target;
  40662. return _this;
  40663. }
  40664. StopAnimationAction.prototype._prepare = function () {
  40665. };
  40666. StopAnimationAction.prototype.execute = function () {
  40667. var scene = this._actionManager.getScene();
  40668. scene.stopAnimation(this._target);
  40669. };
  40670. StopAnimationAction.prototype.serialize = function (parent) {
  40671. return _super.prototype._serialize.call(this, {
  40672. name: "StopAnimationAction",
  40673. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  40674. }, parent);
  40675. };
  40676. return StopAnimationAction;
  40677. }(BABYLON.Action));
  40678. BABYLON.StopAnimationAction = StopAnimationAction;
  40679. var DoNothingAction = (function (_super) {
  40680. __extends(DoNothingAction, _super);
  40681. function DoNothingAction(triggerOptions, condition) {
  40682. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  40683. return _super.call(this, triggerOptions, condition) || this;
  40684. }
  40685. DoNothingAction.prototype.execute = function () {
  40686. };
  40687. DoNothingAction.prototype.serialize = function (parent) {
  40688. return _super.prototype._serialize.call(this, {
  40689. name: "DoNothingAction",
  40690. properties: []
  40691. }, parent);
  40692. };
  40693. return DoNothingAction;
  40694. }(BABYLON.Action));
  40695. BABYLON.DoNothingAction = DoNothingAction;
  40696. var CombineAction = (function (_super) {
  40697. __extends(CombineAction, _super);
  40698. function CombineAction(triggerOptions, children, condition) {
  40699. var _this = _super.call(this, triggerOptions, condition) || this;
  40700. _this.children = children;
  40701. return _this;
  40702. }
  40703. CombineAction.prototype._prepare = function () {
  40704. for (var index = 0; index < this.children.length; index++) {
  40705. this.children[index]._actionManager = this._actionManager;
  40706. this.children[index]._prepare();
  40707. }
  40708. };
  40709. CombineAction.prototype.execute = function (evt) {
  40710. for (var index = 0; index < this.children.length; index++) {
  40711. this.children[index].execute(evt);
  40712. }
  40713. };
  40714. CombineAction.prototype.serialize = function (parent) {
  40715. var serializationObject = _super.prototype._serialize.call(this, {
  40716. name: "CombineAction",
  40717. properties: [],
  40718. combine: []
  40719. }, parent);
  40720. for (var i = 0; i < this.children.length; i++) {
  40721. serializationObject.combine.push(this.children[i].serialize(null));
  40722. }
  40723. return serializationObject;
  40724. };
  40725. return CombineAction;
  40726. }(BABYLON.Action));
  40727. BABYLON.CombineAction = CombineAction;
  40728. var ExecuteCodeAction = (function (_super) {
  40729. __extends(ExecuteCodeAction, _super);
  40730. function ExecuteCodeAction(triggerOptions, func, condition) {
  40731. var _this = _super.call(this, triggerOptions, condition) || this;
  40732. _this.func = func;
  40733. return _this;
  40734. }
  40735. ExecuteCodeAction.prototype.execute = function (evt) {
  40736. this.func(evt);
  40737. };
  40738. return ExecuteCodeAction;
  40739. }(BABYLON.Action));
  40740. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  40741. var SetParentAction = (function (_super) {
  40742. __extends(SetParentAction, _super);
  40743. function SetParentAction(triggerOptions, target, parent, condition) {
  40744. var _this = _super.call(this, triggerOptions, condition) || this;
  40745. _this._target = target;
  40746. _this._parent = parent;
  40747. return _this;
  40748. }
  40749. SetParentAction.prototype._prepare = function () {
  40750. };
  40751. SetParentAction.prototype.execute = function () {
  40752. if (this._target.parent === this._parent) {
  40753. return;
  40754. }
  40755. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  40756. invertParentWorldMatrix.invert();
  40757. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  40758. this._target.parent = this._parent;
  40759. };
  40760. SetParentAction.prototype.serialize = function (parent) {
  40761. return _super.prototype._serialize.call(this, {
  40762. name: "SetParentAction",
  40763. properties: [
  40764. BABYLON.Action._GetTargetProperty(this._target),
  40765. BABYLON.Action._GetTargetProperty(this._parent),
  40766. ]
  40767. }, parent);
  40768. };
  40769. return SetParentAction;
  40770. }(BABYLON.Action));
  40771. BABYLON.SetParentAction = SetParentAction;
  40772. var PlaySoundAction = (function (_super) {
  40773. __extends(PlaySoundAction, _super);
  40774. function PlaySoundAction(triggerOptions, sound, condition) {
  40775. var _this = _super.call(this, triggerOptions, condition) || this;
  40776. _this._sound = sound;
  40777. return _this;
  40778. }
  40779. PlaySoundAction.prototype._prepare = function () {
  40780. };
  40781. PlaySoundAction.prototype.execute = function () {
  40782. if (this._sound !== undefined)
  40783. this._sound.play();
  40784. };
  40785. PlaySoundAction.prototype.serialize = function (parent) {
  40786. return _super.prototype._serialize.call(this, {
  40787. name: "PlaySoundAction",
  40788. properties: [{ name: "sound", value: this._sound.name }]
  40789. }, parent);
  40790. };
  40791. return PlaySoundAction;
  40792. }(BABYLON.Action));
  40793. BABYLON.PlaySoundAction = PlaySoundAction;
  40794. var StopSoundAction = (function (_super) {
  40795. __extends(StopSoundAction, _super);
  40796. function StopSoundAction(triggerOptions, sound, condition) {
  40797. var _this = _super.call(this, triggerOptions, condition) || this;
  40798. _this._sound = sound;
  40799. return _this;
  40800. }
  40801. StopSoundAction.prototype._prepare = function () {
  40802. };
  40803. StopSoundAction.prototype.execute = function () {
  40804. if (this._sound !== undefined)
  40805. this._sound.stop();
  40806. };
  40807. StopSoundAction.prototype.serialize = function (parent) {
  40808. return _super.prototype._serialize.call(this, {
  40809. name: "StopSoundAction",
  40810. properties: [{ name: "sound", value: this._sound.name }]
  40811. }, parent);
  40812. };
  40813. return StopSoundAction;
  40814. }(BABYLON.Action));
  40815. BABYLON.StopSoundAction = StopSoundAction;
  40816. })(BABYLON || (BABYLON = {}));
  40817. //# sourceMappingURL=babylon.directActions.js.map
  40818. var BABYLON;
  40819. (function (BABYLON) {
  40820. var Geometry = (function () {
  40821. function Geometry(id, scene, vertexData, updatable, mesh) {
  40822. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40823. this._totalVertices = 0;
  40824. this._isDisposed = false;
  40825. this.id = id;
  40826. this._engine = scene.getEngine();
  40827. this._meshes = [];
  40828. this._scene = scene;
  40829. //Init vertex buffer cache
  40830. this._vertexBuffers = {};
  40831. this._indices = [];
  40832. // vertexData
  40833. if (vertexData) {
  40834. this.setAllVerticesData(vertexData, updatable);
  40835. }
  40836. else {
  40837. this._totalVertices = 0;
  40838. this._indices = [];
  40839. }
  40840. if (this._engine.getCaps().vertexArrayObject) {
  40841. this._vertexArrayObjects = {};
  40842. }
  40843. // applyToMesh
  40844. if (mesh) {
  40845. if (mesh instanceof BABYLON.LinesMesh) {
  40846. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40847. this.updateExtend();
  40848. }
  40849. this.applyToMesh(mesh);
  40850. mesh.computeWorldMatrix(true);
  40851. }
  40852. }
  40853. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40854. /**
  40855. * 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
  40856. * @returns The Bias Vector
  40857. */
  40858. get: function () {
  40859. return this._boundingBias;
  40860. },
  40861. set: function (value) {
  40862. if (this._boundingBias && this._boundingBias.equals(value)) {
  40863. return;
  40864. }
  40865. this._boundingBias = value.clone();
  40866. this.updateBoundingInfo(true, null);
  40867. },
  40868. enumerable: true,
  40869. configurable: true
  40870. });
  40871. Object.defineProperty(Geometry.prototype, "extend", {
  40872. get: function () {
  40873. return this._extend;
  40874. },
  40875. enumerable: true,
  40876. configurable: true
  40877. });
  40878. Geometry.prototype.getScene = function () {
  40879. return this._scene;
  40880. };
  40881. Geometry.prototype.getEngine = function () {
  40882. return this._engine;
  40883. };
  40884. Geometry.prototype.isReady = function () {
  40885. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40886. };
  40887. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40888. get: function () {
  40889. for (var index = 0; index < this._meshes.length; index++) {
  40890. if (!this._meshes[index].doNotSerialize) {
  40891. return false;
  40892. }
  40893. }
  40894. return true;
  40895. },
  40896. enumerable: true,
  40897. configurable: true
  40898. });
  40899. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40900. vertexData.applyToGeometry(this, updatable);
  40901. this.notifyUpdate();
  40902. };
  40903. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40904. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40905. this.setVerticesBuffer(buffer);
  40906. };
  40907. Geometry.prototype.setVerticesBuffer = function (buffer) {
  40908. var kind = buffer.getKind();
  40909. if (this._vertexBuffers[kind]) {
  40910. this._vertexBuffers[kind].dispose();
  40911. }
  40912. this._vertexBuffers[kind] = buffer;
  40913. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40914. var data = buffer.getData();
  40915. var stride = buffer.getStrideSize();
  40916. this._totalVertices = data.length / stride;
  40917. this.updateExtend(data, stride);
  40918. var meshes = this._meshes;
  40919. var numOfMeshes = meshes.length;
  40920. for (var index = 0; index < numOfMeshes; index++) {
  40921. var mesh = meshes[index];
  40922. mesh._resetPointsArrayCache();
  40923. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40924. mesh._createGlobalSubMesh();
  40925. mesh.computeWorldMatrix(true);
  40926. }
  40927. }
  40928. this.notifyUpdate(kind);
  40929. if (this._vertexArrayObjects) {
  40930. this._disposeVertexArrayObjects();
  40931. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40932. }
  40933. };
  40934. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  40935. var vertexBuffer = this.getVertexBuffer(kind);
  40936. if (!vertexBuffer) {
  40937. return;
  40938. }
  40939. vertexBuffer.updateDirectly(data, offset);
  40940. this.notifyUpdate(kind);
  40941. };
  40942. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40943. var vertexBuffer = this.getVertexBuffer(kind);
  40944. if (!vertexBuffer) {
  40945. return;
  40946. }
  40947. vertexBuffer.update(data);
  40948. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40949. var stride = vertexBuffer.getStrideSize();
  40950. this._totalVertices = data.length / stride;
  40951. this.updateBoundingInfo(updateExtends, data);
  40952. }
  40953. this.notifyUpdate(kind);
  40954. };
  40955. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  40956. if (updateExtends) {
  40957. this.updateExtend(data);
  40958. }
  40959. var meshes = this._meshes;
  40960. var numOfMeshes = meshes.length;
  40961. for (var index = 0; index < numOfMeshes; index++) {
  40962. var mesh = meshes[index];
  40963. mesh._resetPointsArrayCache();
  40964. if (updateExtends) {
  40965. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40966. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40967. var subMesh = mesh.subMeshes[subIndex];
  40968. subMesh.refreshBoundingInfo();
  40969. }
  40970. }
  40971. }
  40972. };
  40973. Geometry.prototype._bind = function (effect, indexToBind) {
  40974. if (indexToBind === void 0) { indexToBind = undefined; }
  40975. if (indexToBind === undefined) {
  40976. indexToBind = this._indexBuffer;
  40977. }
  40978. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40979. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  40980. return;
  40981. }
  40982. // Using VAO
  40983. if (!this._vertexArrayObjects[effect.key]) {
  40984. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  40985. }
  40986. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40987. };
  40988. Geometry.prototype.getTotalVertices = function () {
  40989. if (!this.isReady()) {
  40990. return 0;
  40991. }
  40992. return this._totalVertices;
  40993. };
  40994. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  40995. var vertexBuffer = this.getVertexBuffer(kind);
  40996. if (!vertexBuffer) {
  40997. return null;
  40998. }
  40999. var orig = vertexBuffer.getData();
  41000. if (!copyWhenShared || this._meshes.length === 1) {
  41001. return orig;
  41002. }
  41003. else {
  41004. var len = orig.length;
  41005. var copy = [];
  41006. for (var i = 0; i < len; i++) {
  41007. copy.push(orig[i]);
  41008. }
  41009. return copy;
  41010. }
  41011. };
  41012. Geometry.prototype.getVertexBuffer = function (kind) {
  41013. if (!this.isReady()) {
  41014. return null;
  41015. }
  41016. return this._vertexBuffers[kind];
  41017. };
  41018. Geometry.prototype.getVertexBuffers = function () {
  41019. if (!this.isReady()) {
  41020. return null;
  41021. }
  41022. return this._vertexBuffers;
  41023. };
  41024. Geometry.prototype.isVerticesDataPresent = function (kind) {
  41025. if (!this._vertexBuffers) {
  41026. if (this._delayInfo) {
  41027. return this._delayInfo.indexOf(kind) !== -1;
  41028. }
  41029. return false;
  41030. }
  41031. return this._vertexBuffers[kind] !== undefined;
  41032. };
  41033. Geometry.prototype.getVerticesDataKinds = function () {
  41034. var result = [];
  41035. var kind;
  41036. if (!this._vertexBuffers && this._delayInfo) {
  41037. for (kind in this._delayInfo) {
  41038. result.push(kind);
  41039. }
  41040. }
  41041. else {
  41042. for (kind in this._vertexBuffers) {
  41043. result.push(kind);
  41044. }
  41045. }
  41046. return result;
  41047. };
  41048. Geometry.prototype.setIndices = function (indices, totalVertices) {
  41049. if (this._indexBuffer) {
  41050. this._engine._releaseBuffer(this._indexBuffer);
  41051. }
  41052. this._disposeVertexArrayObjects();
  41053. this._indices = indices;
  41054. if (this._meshes.length !== 0 && this._indices) {
  41055. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41056. }
  41057. if (totalVertices !== undefined) {
  41058. this._totalVertices = totalVertices;
  41059. }
  41060. var meshes = this._meshes;
  41061. var numOfMeshes = meshes.length;
  41062. for (var index = 0; index < numOfMeshes; index++) {
  41063. meshes[index]._createGlobalSubMesh();
  41064. }
  41065. this.notifyUpdate();
  41066. };
  41067. Geometry.prototype.getTotalIndices = function () {
  41068. if (!this.isReady()) {
  41069. return 0;
  41070. }
  41071. return this._indices.length;
  41072. };
  41073. Geometry.prototype.getIndices = function (copyWhenShared) {
  41074. if (!this.isReady()) {
  41075. return null;
  41076. }
  41077. var orig = this._indices;
  41078. if (!copyWhenShared || this._meshes.length === 1) {
  41079. return orig;
  41080. }
  41081. else {
  41082. var len = orig.length;
  41083. var copy = [];
  41084. for (var i = 0; i < len; i++) {
  41085. copy.push(orig[i]);
  41086. }
  41087. return copy;
  41088. }
  41089. };
  41090. Geometry.prototype.getIndexBuffer = function () {
  41091. if (!this.isReady()) {
  41092. return null;
  41093. }
  41094. return this._indexBuffer;
  41095. };
  41096. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  41097. var meshes = this._meshes;
  41098. var index = meshes.indexOf(mesh);
  41099. if (index === -1) {
  41100. return;
  41101. }
  41102. meshes.splice(index, 1);
  41103. mesh._geometry = null;
  41104. if (meshes.length === 0 && shouldDispose) {
  41105. this.dispose();
  41106. }
  41107. };
  41108. Geometry.prototype.applyToMesh = function (mesh) {
  41109. if (mesh._geometry === this) {
  41110. return;
  41111. }
  41112. var previousGeometry = mesh._geometry;
  41113. if (previousGeometry) {
  41114. previousGeometry.releaseForMesh(mesh);
  41115. }
  41116. var meshes = this._meshes;
  41117. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  41118. mesh._geometry = this;
  41119. this._scene.pushGeometry(this);
  41120. meshes.push(mesh);
  41121. if (this.isReady()) {
  41122. this._applyToMesh(mesh);
  41123. }
  41124. else {
  41125. mesh._boundingInfo = this._boundingInfo;
  41126. }
  41127. };
  41128. Geometry.prototype.updateExtend = function (data, stride) {
  41129. if (data === void 0) { data = null; }
  41130. if (!data) {
  41131. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  41132. }
  41133. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  41134. };
  41135. Geometry.prototype._applyToMesh = function (mesh) {
  41136. var numOfMeshes = this._meshes.length;
  41137. // vertexBuffers
  41138. for (var kind in this._vertexBuffers) {
  41139. if (numOfMeshes === 1) {
  41140. this._vertexBuffers[kind].create();
  41141. }
  41142. var buffer = this._vertexBuffers[kind].getBuffer();
  41143. if (buffer)
  41144. buffer.references = numOfMeshes;
  41145. if (kind === BABYLON.VertexBuffer.PositionKind) {
  41146. mesh._resetPointsArrayCache();
  41147. if (!this._extend) {
  41148. this.updateExtend(this._vertexBuffers[kind].getData());
  41149. }
  41150. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41151. mesh._createGlobalSubMesh();
  41152. //bounding info was just created again, world matrix should be applied again.
  41153. mesh._updateBoundingInfo();
  41154. }
  41155. }
  41156. // indexBuffer
  41157. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  41158. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  41159. }
  41160. if (this._indexBuffer) {
  41161. this._indexBuffer.references = numOfMeshes;
  41162. }
  41163. };
  41164. Geometry.prototype.notifyUpdate = function (kind) {
  41165. if (this.onGeometryUpdated) {
  41166. this.onGeometryUpdated(this, kind);
  41167. }
  41168. };
  41169. Geometry.prototype.load = function (scene, onLoaded) {
  41170. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  41171. return;
  41172. }
  41173. if (this.isReady()) {
  41174. if (onLoaded) {
  41175. onLoaded();
  41176. }
  41177. return;
  41178. }
  41179. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  41180. this._queueLoad(scene, onLoaded);
  41181. };
  41182. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  41183. var _this = this;
  41184. scene._addPendingData(this);
  41185. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  41186. _this._delayLoadingFunction(JSON.parse(data), _this);
  41187. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41188. _this._delayInfo = [];
  41189. scene._removePendingData(_this);
  41190. var meshes = _this._meshes;
  41191. var numOfMeshes = meshes.length;
  41192. for (var index = 0; index < numOfMeshes; index++) {
  41193. _this._applyToMesh(meshes[index]);
  41194. }
  41195. if (onLoaded) {
  41196. onLoaded();
  41197. }
  41198. }, function () { }, scene.database);
  41199. };
  41200. /**
  41201. * Invert the geometry to move from a right handed system to a left handed one.
  41202. */
  41203. Geometry.prototype.toLeftHanded = function () {
  41204. // Flip faces
  41205. var tIndices = this.getIndices(false);
  41206. if (tIndices != null && tIndices.length > 0) {
  41207. for (var i = 0; i < tIndices.length; i += 3) {
  41208. var tTemp = tIndices[i + 0];
  41209. tIndices[i + 0] = tIndices[i + 2];
  41210. tIndices[i + 2] = tTemp;
  41211. }
  41212. this.setIndices(tIndices);
  41213. }
  41214. // Negate position.z
  41215. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  41216. if (tPositions != null && tPositions.length > 0) {
  41217. for (var i = 0; i < tPositions.length; i += 3) {
  41218. tPositions[i + 2] = -tPositions[i + 2];
  41219. }
  41220. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  41221. }
  41222. // Negate normal.z
  41223. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  41224. if (tNormals != null && tNormals.length > 0) {
  41225. for (var i = 0; i < tNormals.length; i += 3) {
  41226. tNormals[i + 2] = -tNormals[i + 2];
  41227. }
  41228. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  41229. }
  41230. };
  41231. Geometry.prototype.isDisposed = function () {
  41232. return this._isDisposed;
  41233. };
  41234. Geometry.prototype._disposeVertexArrayObjects = function () {
  41235. if (this._vertexArrayObjects) {
  41236. for (var kind in this._vertexArrayObjects) {
  41237. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  41238. }
  41239. this._vertexArrayObjects = {};
  41240. }
  41241. };
  41242. Geometry.prototype.dispose = function () {
  41243. var meshes = this._meshes;
  41244. var numOfMeshes = meshes.length;
  41245. var index;
  41246. for (index = 0; index < numOfMeshes; index++) {
  41247. this.releaseForMesh(meshes[index]);
  41248. }
  41249. this._meshes = [];
  41250. this._disposeVertexArrayObjects();
  41251. for (var kind in this._vertexBuffers) {
  41252. this._vertexBuffers[kind].dispose();
  41253. }
  41254. this._vertexBuffers = {};
  41255. this._totalVertices = 0;
  41256. if (this._indexBuffer) {
  41257. this._engine._releaseBuffer(this._indexBuffer);
  41258. }
  41259. this._indexBuffer = null;
  41260. this._indices = [];
  41261. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  41262. this.delayLoadingFile = null;
  41263. this._delayLoadingFunction = null;
  41264. this._delayInfo = [];
  41265. this._boundingInfo = null;
  41266. this._scene.removeGeometry(this);
  41267. this._isDisposed = true;
  41268. };
  41269. Geometry.prototype.copy = function (id) {
  41270. var vertexData = new BABYLON.VertexData();
  41271. vertexData.indices = [];
  41272. var indices = this.getIndices();
  41273. for (var index = 0; index < indices.length; index++) {
  41274. vertexData.indices.push(indices[index]);
  41275. }
  41276. var updatable = false;
  41277. var stopChecking = false;
  41278. var kind;
  41279. for (kind in this._vertexBuffers) {
  41280. // using slice() to make a copy of the array and not just reference it
  41281. var data = this.getVerticesData(kind);
  41282. if (data instanceof Float32Array) {
  41283. vertexData.set(new Float32Array(data), kind);
  41284. }
  41285. else {
  41286. vertexData.set(data.slice(0), kind);
  41287. }
  41288. if (!stopChecking) {
  41289. updatable = this.getVertexBuffer(kind).isUpdatable();
  41290. stopChecking = !updatable;
  41291. }
  41292. }
  41293. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  41294. geometry.delayLoadState = this.delayLoadState;
  41295. geometry.delayLoadingFile = this.delayLoadingFile;
  41296. geometry._delayLoadingFunction = this._delayLoadingFunction;
  41297. for (kind in this._delayInfo) {
  41298. geometry._delayInfo = geometry._delayInfo || [];
  41299. geometry._delayInfo.push(kind);
  41300. }
  41301. // Bounding info
  41302. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  41303. return geometry;
  41304. };
  41305. Geometry.prototype.serialize = function () {
  41306. var serializationObject = {};
  41307. serializationObject.id = this.id;
  41308. if (BABYLON.Tags.HasTags(this)) {
  41309. serializationObject.tags = BABYLON.Tags.GetTags(this);
  41310. }
  41311. return serializationObject;
  41312. };
  41313. Geometry.prototype.serializeVerticeData = function () {
  41314. var serializationObject = this.serialize();
  41315. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  41316. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41317. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  41318. serializationObject.positions._updatable = true;
  41319. }
  41320. }
  41321. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41322. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41323. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  41324. serializationObject.normals._updatable = true;
  41325. }
  41326. }
  41327. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  41328. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41329. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  41330. serializationObject.uvs._updatable = true;
  41331. }
  41332. }
  41333. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  41334. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  41335. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  41336. serializationObject.uv2s._updatable = true;
  41337. }
  41338. }
  41339. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  41340. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  41341. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  41342. serializationObject.uv3s._updatable = true;
  41343. }
  41344. }
  41345. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  41346. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  41347. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  41348. serializationObject.uv4s._updatable = true;
  41349. }
  41350. }
  41351. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  41352. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  41353. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  41354. serializationObject.uv5s._updatable = true;
  41355. }
  41356. }
  41357. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  41358. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  41359. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  41360. serializationObject.uv6s._updatable = true;
  41361. }
  41362. }
  41363. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  41364. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41365. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  41366. serializationObject.colors._updatable = true;
  41367. }
  41368. }
  41369. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  41370. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41371. serializationObject.matricesIndices._isExpanded = true;
  41372. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  41373. serializationObject.matricesIndices._updatable = true;
  41374. }
  41375. }
  41376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  41377. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  41378. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  41379. serializationObject.matricesWeights._updatable = true;
  41380. }
  41381. }
  41382. serializationObject.indices = this.getIndices();
  41383. return serializationObject;
  41384. };
  41385. // Statics
  41386. Geometry.ExtractFromMesh = function (mesh, id) {
  41387. var geometry = mesh._geometry;
  41388. if (!geometry) {
  41389. return null;
  41390. }
  41391. return geometry.copy(id);
  41392. };
  41393. /**
  41394. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  41395. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  41396. * Be aware Math.random() could cause collisions, but:
  41397. * "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"
  41398. */
  41399. Geometry.RandomId = function () {
  41400. return BABYLON.Tools.RandomId();
  41401. };
  41402. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  41403. var scene = mesh.getScene();
  41404. // Geometry
  41405. var geometryId = parsedGeometry.geometryId;
  41406. if (geometryId) {
  41407. var geometry = scene.getGeometryByID(geometryId);
  41408. if (geometry) {
  41409. geometry.applyToMesh(mesh);
  41410. }
  41411. }
  41412. else if (parsedGeometry instanceof ArrayBuffer) {
  41413. var binaryInfo = mesh._binaryInfo;
  41414. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  41415. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  41416. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  41417. }
  41418. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  41419. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  41420. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  41421. }
  41422. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  41423. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  41424. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  41425. }
  41426. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  41427. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  41428. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  41429. }
  41430. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  41431. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  41432. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  41433. }
  41434. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  41435. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  41436. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  41437. }
  41438. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  41439. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41440. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41441. }
  41442. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41443. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41444. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41445. }
  41446. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41447. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41448. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41449. }
  41450. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41451. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41452. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  41453. }
  41454. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41455. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41456. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41457. }
  41458. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41459. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41460. mesh.setIndices(indicesData);
  41461. }
  41462. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41463. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41464. mesh.subMeshes = [];
  41465. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41466. var materialIndex = subMeshesData[(i * 5) + 0];
  41467. var verticesStart = subMeshesData[(i * 5) + 1];
  41468. var verticesCount = subMeshesData[(i * 5) + 2];
  41469. var indexStart = subMeshesData[(i * 5) + 3];
  41470. var indexCount = subMeshesData[(i * 5) + 4];
  41471. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41472. }
  41473. }
  41474. }
  41475. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41476. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41477. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41478. if (parsedGeometry.uvs) {
  41479. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41480. }
  41481. if (parsedGeometry.uvs2) {
  41482. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41483. }
  41484. if (parsedGeometry.uvs3) {
  41485. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41486. }
  41487. if (parsedGeometry.uvs4) {
  41488. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41489. }
  41490. if (parsedGeometry.uvs5) {
  41491. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41492. }
  41493. if (parsedGeometry.uvs6) {
  41494. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41495. }
  41496. if (parsedGeometry.colors) {
  41497. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41498. }
  41499. if (parsedGeometry.matricesIndices) {
  41500. if (!parsedGeometry.matricesIndices._isExpanded) {
  41501. var floatIndices = [];
  41502. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41503. var matricesIndex = parsedGeometry.matricesIndices[i];
  41504. floatIndices.push(matricesIndex & 0x000000FF);
  41505. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41506. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41507. floatIndices.push(matricesIndex >> 24);
  41508. }
  41509. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41510. }
  41511. else {
  41512. delete parsedGeometry.matricesIndices._isExpanded;
  41513. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41514. }
  41515. }
  41516. if (parsedGeometry.matricesIndicesExtra) {
  41517. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41518. var floatIndices = [];
  41519. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41520. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41521. floatIndices.push(matricesIndex & 0x000000FF);
  41522. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41523. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41524. floatIndices.push(matricesIndex >> 24);
  41525. }
  41526. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41527. }
  41528. else {
  41529. delete parsedGeometry.matricesIndices._isExpanded;
  41530. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41531. }
  41532. }
  41533. if (parsedGeometry.matricesWeights) {
  41534. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41535. }
  41536. if (parsedGeometry.matricesWeightsExtra) {
  41537. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41538. }
  41539. mesh.setIndices(parsedGeometry.indices);
  41540. }
  41541. // SubMeshes
  41542. if (parsedGeometry.subMeshes) {
  41543. mesh.subMeshes = [];
  41544. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41545. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41546. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41547. }
  41548. }
  41549. // Flat shading
  41550. if (mesh._shouldGenerateFlatShading) {
  41551. mesh.convertToFlatShadedMesh();
  41552. delete mesh._shouldGenerateFlatShading;
  41553. }
  41554. // Update
  41555. mesh.computeWorldMatrix(true);
  41556. // Octree
  41557. if (scene['_selectionOctree']) {
  41558. scene['_selectionOctree'].addMesh(mesh);
  41559. }
  41560. };
  41561. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41562. if (scene.getGeometryByID(parsedVertexData.id)) {
  41563. return null; // null since geometry could be something else than a box...
  41564. }
  41565. var geometry = new Geometry(parsedVertexData.id, scene);
  41566. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41567. if (parsedVertexData.delayLoadingFile) {
  41568. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41569. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41570. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41571. geometry._delayInfo = [];
  41572. if (parsedVertexData.hasUVs) {
  41573. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41574. }
  41575. if (parsedVertexData.hasUVs2) {
  41576. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41577. }
  41578. if (parsedVertexData.hasUVs3) {
  41579. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41580. }
  41581. if (parsedVertexData.hasUVs4) {
  41582. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41583. }
  41584. if (parsedVertexData.hasUVs5) {
  41585. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41586. }
  41587. if (parsedVertexData.hasUVs6) {
  41588. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41589. }
  41590. if (parsedVertexData.hasColors) {
  41591. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41592. }
  41593. if (parsedVertexData.hasMatricesIndices) {
  41594. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41595. }
  41596. if (parsedVertexData.hasMatricesWeights) {
  41597. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41598. }
  41599. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41600. }
  41601. else {
  41602. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41603. }
  41604. scene.pushGeometry(geometry, true);
  41605. return geometry;
  41606. };
  41607. return Geometry;
  41608. }());
  41609. BABYLON.Geometry = Geometry;
  41610. /////// Primitives //////////////////////////////////////////////
  41611. (function (Geometry) {
  41612. var Primitives;
  41613. (function (Primitives) {
  41614. /// Abstract class
  41615. var _Primitive = (function (_super) {
  41616. __extends(_Primitive, _super);
  41617. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  41618. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  41619. _this._canBeRegenerated = _canBeRegenerated;
  41620. _this._beingRegenerated = true;
  41621. _this.regenerate();
  41622. _this._beingRegenerated = false;
  41623. return _this;
  41624. }
  41625. _Primitive.prototype.canBeRegenerated = function () {
  41626. return this._canBeRegenerated;
  41627. };
  41628. _Primitive.prototype.regenerate = function () {
  41629. if (!this._canBeRegenerated) {
  41630. return;
  41631. }
  41632. this._beingRegenerated = true;
  41633. this.setAllVerticesData(this._regenerateVertexData(), false);
  41634. this._beingRegenerated = false;
  41635. };
  41636. _Primitive.prototype.asNewGeometry = function (id) {
  41637. return _super.prototype.copy.call(this, id);
  41638. };
  41639. // overrides
  41640. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  41641. if (!this._beingRegenerated) {
  41642. return;
  41643. }
  41644. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41645. };
  41646. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  41647. if (!this._beingRegenerated) {
  41648. return;
  41649. }
  41650. _super.prototype.setVerticesData.call(this, kind, data, false);
  41651. };
  41652. // to override
  41653. // protected
  41654. _Primitive.prototype._regenerateVertexData = function () {
  41655. throw new Error("Abstract method");
  41656. };
  41657. _Primitive.prototype.copy = function (id) {
  41658. throw new Error("Must be overriden in sub-classes.");
  41659. };
  41660. _Primitive.prototype.serialize = function () {
  41661. var serializationObject = _super.prototype.serialize.call(this);
  41662. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41663. return serializationObject;
  41664. };
  41665. return _Primitive;
  41666. }(Geometry));
  41667. Primitives._Primitive = _Primitive;
  41668. var Ribbon = (function (_super) {
  41669. __extends(Ribbon, _super);
  41670. // Members
  41671. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  41672. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41673. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41674. _this.pathArray = pathArray;
  41675. _this.closeArray = closeArray;
  41676. _this.closePath = closePath;
  41677. _this.offset = offset;
  41678. _this.side = side;
  41679. return _this;
  41680. }
  41681. Ribbon.prototype._regenerateVertexData = function () {
  41682. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41683. };
  41684. Ribbon.prototype.copy = function (id) {
  41685. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  41686. };
  41687. return Ribbon;
  41688. }(_Primitive));
  41689. Primitives.Ribbon = Ribbon;
  41690. var Box = (function (_super) {
  41691. __extends(Box, _super);
  41692. // Members
  41693. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  41694. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41695. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41696. _this.size = size;
  41697. _this.side = side;
  41698. return _this;
  41699. }
  41700. Box.prototype._regenerateVertexData = function () {
  41701. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41702. };
  41703. Box.prototype.copy = function (id) {
  41704. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41705. };
  41706. Box.prototype.serialize = function () {
  41707. var serializationObject = _super.prototype.serialize.call(this);
  41708. serializationObject.size = this.size;
  41709. return serializationObject;
  41710. };
  41711. Box.Parse = function (parsedBox, scene) {
  41712. if (scene.getGeometryByID(parsedBox.id)) {
  41713. return null; // null since geometry could be something else than a box...
  41714. }
  41715. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41716. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41717. scene.pushGeometry(box, true);
  41718. return box;
  41719. };
  41720. return Box;
  41721. }(_Primitive));
  41722. Primitives.Box = Box;
  41723. var Sphere = (function (_super) {
  41724. __extends(Sphere, _super);
  41725. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  41726. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41727. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41728. _this.segments = segments;
  41729. _this.diameter = diameter;
  41730. _this.side = side;
  41731. return _this;
  41732. }
  41733. Sphere.prototype._regenerateVertexData = function () {
  41734. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41735. };
  41736. Sphere.prototype.copy = function (id) {
  41737. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41738. };
  41739. Sphere.prototype.serialize = function () {
  41740. var serializationObject = _super.prototype.serialize.call(this);
  41741. serializationObject.segments = this.segments;
  41742. serializationObject.diameter = this.diameter;
  41743. return serializationObject;
  41744. };
  41745. Sphere.Parse = function (parsedSphere, scene) {
  41746. if (scene.getGeometryByID(parsedSphere.id)) {
  41747. return null; // null since geometry could be something else than a sphere...
  41748. }
  41749. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41750. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41751. scene.pushGeometry(sphere, true);
  41752. return sphere;
  41753. };
  41754. return Sphere;
  41755. }(_Primitive));
  41756. Primitives.Sphere = Sphere;
  41757. var Disc = (function (_super) {
  41758. __extends(Disc, _super);
  41759. // Members
  41760. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  41761. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41762. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41763. _this.radius = radius;
  41764. _this.tessellation = tessellation;
  41765. _this.side = side;
  41766. return _this;
  41767. }
  41768. Disc.prototype._regenerateVertexData = function () {
  41769. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41770. };
  41771. Disc.prototype.copy = function (id) {
  41772. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41773. };
  41774. return Disc;
  41775. }(_Primitive));
  41776. Primitives.Disc = Disc;
  41777. var Cylinder = (function (_super) {
  41778. __extends(Cylinder, _super);
  41779. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  41780. if (subdivisions === void 0) { subdivisions = 1; }
  41781. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41782. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41783. _this.height = height;
  41784. _this.diameterTop = diameterTop;
  41785. _this.diameterBottom = diameterBottom;
  41786. _this.tessellation = tessellation;
  41787. _this.subdivisions = subdivisions;
  41788. _this.side = side;
  41789. return _this;
  41790. }
  41791. Cylinder.prototype._regenerateVertexData = function () {
  41792. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41793. };
  41794. Cylinder.prototype.copy = function (id) {
  41795. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41796. };
  41797. Cylinder.prototype.serialize = function () {
  41798. var serializationObject = _super.prototype.serialize.call(this);
  41799. serializationObject.height = this.height;
  41800. serializationObject.diameterTop = this.diameterTop;
  41801. serializationObject.diameterBottom = this.diameterBottom;
  41802. serializationObject.tessellation = this.tessellation;
  41803. return serializationObject;
  41804. };
  41805. Cylinder.Parse = function (parsedCylinder, scene) {
  41806. if (scene.getGeometryByID(parsedCylinder.id)) {
  41807. return null; // null since geometry could be something else than a cylinder...
  41808. }
  41809. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41810. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41811. scene.pushGeometry(cylinder, true);
  41812. return cylinder;
  41813. };
  41814. return Cylinder;
  41815. }(_Primitive));
  41816. Primitives.Cylinder = Cylinder;
  41817. var Torus = (function (_super) {
  41818. __extends(Torus, _super);
  41819. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  41820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41821. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41822. _this.diameter = diameter;
  41823. _this.thickness = thickness;
  41824. _this.tessellation = tessellation;
  41825. _this.side = side;
  41826. return _this;
  41827. }
  41828. Torus.prototype._regenerateVertexData = function () {
  41829. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41830. };
  41831. Torus.prototype.copy = function (id) {
  41832. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41833. };
  41834. Torus.prototype.serialize = function () {
  41835. var serializationObject = _super.prototype.serialize.call(this);
  41836. serializationObject.diameter = this.diameter;
  41837. serializationObject.thickness = this.thickness;
  41838. serializationObject.tessellation = this.tessellation;
  41839. return serializationObject;
  41840. };
  41841. Torus.Parse = function (parsedTorus, scene) {
  41842. if (scene.getGeometryByID(parsedTorus.id)) {
  41843. return null; // null since geometry could be something else than a torus...
  41844. }
  41845. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41846. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41847. scene.pushGeometry(torus, true);
  41848. return torus;
  41849. };
  41850. return Torus;
  41851. }(_Primitive));
  41852. Primitives.Torus = Torus;
  41853. var Ground = (function (_super) {
  41854. __extends(Ground, _super);
  41855. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  41856. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41857. _this.width = width;
  41858. _this.height = height;
  41859. _this.subdivisions = subdivisions;
  41860. return _this;
  41861. }
  41862. Ground.prototype._regenerateVertexData = function () {
  41863. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41864. };
  41865. Ground.prototype.copy = function (id) {
  41866. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41867. };
  41868. Ground.prototype.serialize = function () {
  41869. var serializationObject = _super.prototype.serialize.call(this);
  41870. serializationObject.width = this.width;
  41871. serializationObject.height = this.height;
  41872. serializationObject.subdivisions = this.subdivisions;
  41873. return serializationObject;
  41874. };
  41875. Ground.Parse = function (parsedGround, scene) {
  41876. if (scene.getGeometryByID(parsedGround.id)) {
  41877. return null; // null since geometry could be something else than a ground...
  41878. }
  41879. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41880. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41881. scene.pushGeometry(ground, true);
  41882. return ground;
  41883. };
  41884. return Ground;
  41885. }(_Primitive));
  41886. Primitives.Ground = Ground;
  41887. var TiledGround = (function (_super) {
  41888. __extends(TiledGround, _super);
  41889. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  41890. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41891. _this.xmin = xmin;
  41892. _this.zmin = zmin;
  41893. _this.xmax = xmax;
  41894. _this.zmax = zmax;
  41895. _this.subdivisions = subdivisions;
  41896. _this.precision = precision;
  41897. return _this;
  41898. }
  41899. TiledGround.prototype._regenerateVertexData = function () {
  41900. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41901. };
  41902. TiledGround.prototype.copy = function (id) {
  41903. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41904. };
  41905. return TiledGround;
  41906. }(_Primitive));
  41907. Primitives.TiledGround = TiledGround;
  41908. var Plane = (function (_super) {
  41909. __extends(Plane, _super);
  41910. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  41911. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41912. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41913. _this.size = size;
  41914. _this.side = side;
  41915. return _this;
  41916. }
  41917. Plane.prototype._regenerateVertexData = function () {
  41918. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41919. };
  41920. Plane.prototype.copy = function (id) {
  41921. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41922. };
  41923. Plane.prototype.serialize = function () {
  41924. var serializationObject = _super.prototype.serialize.call(this);
  41925. serializationObject.size = this.size;
  41926. return serializationObject;
  41927. };
  41928. Plane.Parse = function (parsedPlane, scene) {
  41929. if (scene.getGeometryByID(parsedPlane.id)) {
  41930. return null; // null since geometry could be something else than a ground...
  41931. }
  41932. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41933. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41934. scene.pushGeometry(plane, true);
  41935. return plane;
  41936. };
  41937. return Plane;
  41938. }(_Primitive));
  41939. Primitives.Plane = Plane;
  41940. var TorusKnot = (function (_super) {
  41941. __extends(TorusKnot, _super);
  41942. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  41943. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41944. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41945. _this.radius = radius;
  41946. _this.tube = tube;
  41947. _this.radialSegments = radialSegments;
  41948. _this.tubularSegments = tubularSegments;
  41949. _this.p = p;
  41950. _this.q = q;
  41951. _this.side = side;
  41952. return _this;
  41953. }
  41954. TorusKnot.prototype._regenerateVertexData = function () {
  41955. 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 });
  41956. };
  41957. TorusKnot.prototype.copy = function (id) {
  41958. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41959. };
  41960. TorusKnot.prototype.serialize = function () {
  41961. var serializationObject = _super.prototype.serialize.call(this);
  41962. serializationObject.radius = this.radius;
  41963. serializationObject.tube = this.tube;
  41964. serializationObject.radialSegments = this.radialSegments;
  41965. serializationObject.tubularSegments = this.tubularSegments;
  41966. serializationObject.p = this.p;
  41967. serializationObject.q = this.q;
  41968. return serializationObject;
  41969. };
  41970. ;
  41971. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  41972. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41973. return null; // null since geometry could be something else than a ground...
  41974. }
  41975. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41976. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41977. scene.pushGeometry(torusKnot, true);
  41978. return torusKnot;
  41979. };
  41980. return TorusKnot;
  41981. }(_Primitive));
  41982. Primitives.TorusKnot = TorusKnot;
  41983. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  41984. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  41985. })(BABYLON || (BABYLON = {}));
  41986. //# sourceMappingURL=babylon.geometry.js.map
  41987. /// <reference path="babylon.mesh.ts" />
  41988. var BABYLON;
  41989. (function (BABYLON) {
  41990. var GroundMesh = (function (_super) {
  41991. __extends(GroundMesh, _super);
  41992. function GroundMesh(name, scene) {
  41993. var _this = _super.call(this, name, scene) || this;
  41994. _this.generateOctree = false;
  41995. _this._worldInverse = new BABYLON.Matrix();
  41996. return _this;
  41997. }
  41998. GroundMesh.prototype.getClassName = function () {
  41999. return "GroundMesh";
  42000. };
  42001. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  42002. get: function () {
  42003. return Math.min(this._subdivisionsX, this._subdivisionsY);
  42004. },
  42005. enumerable: true,
  42006. configurable: true
  42007. });
  42008. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  42009. get: function () {
  42010. return this._subdivisionsX;
  42011. },
  42012. enumerable: true,
  42013. configurable: true
  42014. });
  42015. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  42016. get: function () {
  42017. return this._subdivisionsY;
  42018. },
  42019. enumerable: true,
  42020. configurable: true
  42021. });
  42022. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  42023. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  42024. this._subdivisionsX = chunksCount;
  42025. this._subdivisionsY = chunksCount;
  42026. this.subdivide(chunksCount);
  42027. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  42028. };
  42029. /**
  42030. * Returns a height (y) value in the Worl system :
  42031. * the ground altitude at the coordinates (x, z) expressed in the World system.
  42032. * Returns the ground y position if (x, z) are outside the ground surface.
  42033. */
  42034. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  42035. var world = this.getWorldMatrix();
  42036. var invMat = BABYLON.Tmp.Matrix[5];
  42037. world.invertToRef(invMat);
  42038. var tmpVect = BABYLON.Tmp.Vector3[8];
  42039. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  42040. x = tmpVect.x;
  42041. z = tmpVect.z;
  42042. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42043. return this.position.y;
  42044. }
  42045. if (!this._heightQuads || this._heightQuads.length == 0) {
  42046. this._initHeightQuads();
  42047. this._computeHeightQuads();
  42048. }
  42049. var facet = this._getFacetAt(x, z);
  42050. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  42051. // return y in the World system
  42052. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  42053. return tmpVect.y;
  42054. };
  42055. /**
  42056. * Returns a normalized vector (Vector3) orthogonal to the ground
  42057. * at the ground coordinates (x, z) expressed in the World system.
  42058. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  42059. */
  42060. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  42061. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  42062. this.getNormalAtCoordinatesToRef(x, z, normal);
  42063. return normal;
  42064. };
  42065. /**
  42066. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  42067. * at the ground coordinates (x, z) expressed in the World system.
  42068. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  42069. * Returns the GroundMesh.
  42070. */
  42071. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  42072. var world = this.getWorldMatrix();
  42073. var tmpMat = BABYLON.Tmp.Matrix[5];
  42074. world.invertToRef(tmpMat);
  42075. var tmpVect = BABYLON.Tmp.Vector3[8];
  42076. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  42077. x = tmpVect.x;
  42078. z = tmpVect.z;
  42079. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  42080. return this;
  42081. }
  42082. if (!this._heightQuads || this._heightQuads.length == 0) {
  42083. this._initHeightQuads();
  42084. this._computeHeightQuads();
  42085. }
  42086. var facet = this._getFacetAt(x, z);
  42087. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  42088. return this;
  42089. };
  42090. /**
  42091. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  42092. * if the ground has been updated.
  42093. * This can be used in the render loop.
  42094. * Returns the GroundMesh.
  42095. */
  42096. GroundMesh.prototype.updateCoordinateHeights = function () {
  42097. if (!this._heightQuads || this._heightQuads.length == 0) {
  42098. this._initHeightQuads();
  42099. }
  42100. this._computeHeightQuads();
  42101. return this;
  42102. };
  42103. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  42104. GroundMesh.prototype._getFacetAt = function (x, z) {
  42105. // retrieve col and row from x, z coordinates in the ground local system
  42106. var subdivisionsX = this._subdivisionsX;
  42107. var subdivisionsY = this._subdivisionsY;
  42108. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  42109. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  42110. var quad = this._heightQuads[row * this._subdivisionsX + col];
  42111. var facet;
  42112. if (z < quad.slope.x * x + quad.slope.y) {
  42113. facet = quad.facet1;
  42114. }
  42115. else {
  42116. facet = quad.facet2;
  42117. }
  42118. return facet;
  42119. };
  42120. // Creates and populates the heightMap array with "facet" elements :
  42121. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  42122. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42123. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42124. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42125. // Returns the GroundMesh.
  42126. GroundMesh.prototype._initHeightQuads = function () {
  42127. var subdivisionsX = this._subdivisionsX;
  42128. var subdivisionsY = this._subdivisionsY;
  42129. this._heightQuads = new Array();
  42130. for (var row = 0; row < subdivisionsY; row++) {
  42131. for (var col = 0; col < subdivisionsX; col++) {
  42132. 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) };
  42133. this._heightQuads[row * subdivisionsX + col] = quad;
  42134. }
  42135. }
  42136. return this;
  42137. };
  42138. // Compute each quad element values and update the the heightMap array :
  42139. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  42140. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  42141. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  42142. // Returns the GroundMesh.
  42143. GroundMesh.prototype._computeHeightQuads = function () {
  42144. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42145. var v1 = BABYLON.Tmp.Vector3[3];
  42146. var v2 = BABYLON.Tmp.Vector3[2];
  42147. var v3 = BABYLON.Tmp.Vector3[1];
  42148. var v4 = BABYLON.Tmp.Vector3[0];
  42149. var v1v2 = BABYLON.Tmp.Vector3[4];
  42150. var v1v3 = BABYLON.Tmp.Vector3[5];
  42151. var v1v4 = BABYLON.Tmp.Vector3[6];
  42152. var norm1 = BABYLON.Tmp.Vector3[7];
  42153. var norm2 = BABYLON.Tmp.Vector3[8];
  42154. var i = 0;
  42155. var j = 0;
  42156. var k = 0;
  42157. var cd = 0; // 2D slope coefficient : z = cd * x + h
  42158. var h = 0;
  42159. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  42160. var d2 = 0;
  42161. var subdivisionsX = this._subdivisionsX;
  42162. var subdivisionsY = this._subdivisionsY;
  42163. for (var row = 0; row < subdivisionsY; row++) {
  42164. for (var col = 0; col < subdivisionsX; col++) {
  42165. i = col * 3;
  42166. j = row * (subdivisionsX + 1) * 3;
  42167. k = (row + 1) * (subdivisionsX + 1) * 3;
  42168. v1.x = positions[j + i];
  42169. v1.y = positions[j + i + 1];
  42170. v1.z = positions[j + i + 2];
  42171. v2.x = positions[j + i + 3];
  42172. v2.y = positions[j + i + 4];
  42173. v2.z = positions[j + i + 5];
  42174. v3.x = positions[k + i];
  42175. v3.y = positions[k + i + 1];
  42176. v3.z = positions[k + i + 2];
  42177. v4.x = positions[k + i + 3];
  42178. v4.y = positions[k + i + 4];
  42179. v4.z = positions[k + i + 5];
  42180. // 2D slope V1V4
  42181. cd = (v4.z - v1.z) / (v4.x - v1.x);
  42182. h = v1.z - cd * v1.x; // v1 belongs to the slope
  42183. // facet equations :
  42184. // we compute each facet normal vector
  42185. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  42186. // we compute the value d by applying the equation to v1 which belongs to the plane
  42187. // then we store the facet equation in a Vector4
  42188. v2.subtractToRef(v1, v1v2);
  42189. v3.subtractToRef(v1, v1v3);
  42190. v4.subtractToRef(v1, v1v4);
  42191. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  42192. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  42193. norm1.normalize();
  42194. norm2.normalize();
  42195. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  42196. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  42197. var quad = this._heightQuads[row * subdivisionsX + col];
  42198. quad.slope.copyFromFloats(cd, h);
  42199. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  42200. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  42201. }
  42202. }
  42203. return this;
  42204. };
  42205. GroundMesh.prototype.serialize = function (serializationObject) {
  42206. _super.prototype.serialize.call(this, serializationObject);
  42207. serializationObject.subdivisionsX = this._subdivisionsX;
  42208. serializationObject.subdivisionsY = this._subdivisionsY;
  42209. serializationObject.minX = this._minX;
  42210. serializationObject.maxX = this._maxX;
  42211. serializationObject.minZ = this._minZ;
  42212. serializationObject.maxZ = this._maxZ;
  42213. serializationObject.width = this._width;
  42214. serializationObject.height = this._height;
  42215. };
  42216. GroundMesh.Parse = function (parsedMesh, scene) {
  42217. var result = new GroundMesh(parsedMesh.name, scene);
  42218. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  42219. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  42220. result._minX = parsedMesh.minX;
  42221. result._maxX = parsedMesh.maxX;
  42222. result._minZ = parsedMesh.minZ;
  42223. result._maxZ = parsedMesh.maxZ;
  42224. result._width = parsedMesh.width;
  42225. result._height = parsedMesh.height;
  42226. return result;
  42227. };
  42228. return GroundMesh;
  42229. }(BABYLON.Mesh));
  42230. BABYLON.GroundMesh = GroundMesh;
  42231. })(BABYLON || (BABYLON = {}));
  42232. //# sourceMappingURL=babylon.groundMesh.js.map
  42233. /// <reference path="babylon.mesh.ts" />
  42234. var BABYLON;
  42235. (function (BABYLON) {
  42236. var LinesMesh = (function (_super) {
  42237. __extends(LinesMesh, _super);
  42238. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  42239. if (parent === void 0) { parent = null; }
  42240. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42241. _this.color = new BABYLON.Color3(1, 1, 1);
  42242. _this.alpha = 1;
  42243. _this._positionBuffer = {};
  42244. if (source) {
  42245. _this.color = source.color.clone();
  42246. _this.alpha = source.alpha;
  42247. }
  42248. _this._intersectionThreshold = 0.1;
  42249. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  42250. attributes: [BABYLON.VertexBuffer.PositionKind],
  42251. uniforms: ["worldViewProjection", "color"],
  42252. needAlphaBlending: true
  42253. });
  42254. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  42255. return _this;
  42256. }
  42257. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42258. /**
  42259. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42260. * This margin is expressed in world space coordinates, so its value may vary.
  42261. * Default value is 0.1
  42262. * @returns the intersection Threshold value.
  42263. */
  42264. get: function () {
  42265. return this._intersectionThreshold;
  42266. },
  42267. /**
  42268. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42269. * This margin is expressed in world space coordinates, so its value may vary.
  42270. * @param value the new threshold to apply
  42271. */
  42272. set: function (value) {
  42273. if (this._intersectionThreshold === value) {
  42274. return;
  42275. }
  42276. this._intersectionThreshold = value;
  42277. if (this.geometry) {
  42278. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42279. }
  42280. },
  42281. enumerable: true,
  42282. configurable: true
  42283. });
  42284. /**
  42285. * Returns the string "LineMesh"
  42286. */
  42287. LinesMesh.prototype.getClassName = function () {
  42288. return "LinesMesh";
  42289. };
  42290. Object.defineProperty(LinesMesh.prototype, "material", {
  42291. get: function () {
  42292. return this._colorShader;
  42293. },
  42294. enumerable: true,
  42295. configurable: true
  42296. });
  42297. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42298. get: function () {
  42299. return false;
  42300. },
  42301. enumerable: true,
  42302. configurable: true
  42303. });
  42304. LinesMesh.prototype.createInstance = function (name) {
  42305. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42306. return null;
  42307. };
  42308. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42309. var engine = this.getScene().getEngine();
  42310. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  42311. // VBOs
  42312. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  42313. // Color
  42314. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42315. return this;
  42316. };
  42317. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42318. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42319. return this;
  42320. }
  42321. var engine = this.getScene().getEngine();
  42322. // Draw order
  42323. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42324. return this;
  42325. };
  42326. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42327. this._colorShader.dispose();
  42328. _super.prototype.dispose.call(this, doNotRecurse);
  42329. };
  42330. /**
  42331. * Returns a new LineMesh object cloned from the current one.
  42332. */
  42333. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42334. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42335. };
  42336. return LinesMesh;
  42337. }(BABYLON.Mesh));
  42338. BABYLON.LinesMesh = LinesMesh;
  42339. })(BABYLON || (BABYLON = {}));
  42340. //# sourceMappingURL=babylon.linesMesh.js.map
  42341. var BABYLON;
  42342. (function (BABYLON) {
  42343. var DefaultLoadingScreen = (function () {
  42344. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42345. if (_loadingText === void 0) { _loadingText = ""; }
  42346. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42347. var _this = this;
  42348. this._renderingCanvas = _renderingCanvas;
  42349. this._loadingText = _loadingText;
  42350. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42351. // Resize
  42352. this._resizeLoadingUI = function () {
  42353. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42354. _this._loadingDiv.style.position = "absolute";
  42355. _this._loadingDiv.style.left = canvasRect.left + "px";
  42356. _this._loadingDiv.style.top = canvasRect.top + "px";
  42357. _this._loadingDiv.style.width = canvasRect.width + "px";
  42358. _this._loadingDiv.style.height = canvasRect.height + "px";
  42359. };
  42360. }
  42361. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42362. var _this = this;
  42363. if (this._loadingDiv) {
  42364. // Do not add a loading screen if there is already one
  42365. return;
  42366. }
  42367. this._loadingDiv = document.createElement("div");
  42368. this._loadingDiv.id = "babylonjsLoadingDiv";
  42369. this._loadingDiv.style.opacity = "0";
  42370. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42371. // Loading text
  42372. this._loadingTextDiv = document.createElement("div");
  42373. this._loadingTextDiv.style.position = "absolute";
  42374. this._loadingTextDiv.style.left = "0";
  42375. this._loadingTextDiv.style.top = "50%";
  42376. this._loadingTextDiv.style.marginTop = "80px";
  42377. this._loadingTextDiv.style.width = "100%";
  42378. this._loadingTextDiv.style.height = "20px";
  42379. this._loadingTextDiv.style.fontFamily = "Arial";
  42380. this._loadingTextDiv.style.fontSize = "14px";
  42381. this._loadingTextDiv.style.color = "white";
  42382. this._loadingTextDiv.style.textAlign = "center";
  42383. this._loadingTextDiv.innerHTML = "Loading";
  42384. this._loadingDiv.appendChild(this._loadingTextDiv);
  42385. //set the predefined text
  42386. this._loadingTextDiv.innerHTML = this._loadingText;
  42387. // Loading img
  42388. var imgBack = new Image();
  42389. 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==";
  42390. imgBack.style.position = "absolute";
  42391. imgBack.style.left = "50%";
  42392. imgBack.style.top = "50%";
  42393. imgBack.style.marginLeft = "-50px";
  42394. imgBack.style.marginTop = "-50px";
  42395. imgBack.style.transition = "transform 1.0s ease";
  42396. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42397. var deg = 360;
  42398. var onTransitionEnd = function () {
  42399. deg += 360;
  42400. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42401. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42402. };
  42403. imgBack.addEventListener("transitionend", onTransitionEnd);
  42404. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42405. this._loadingDiv.appendChild(imgBack);
  42406. // front image
  42407. var imgFront = new Image();
  42408. 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=";
  42409. imgFront.style.position = "absolute";
  42410. imgFront.style.left = "50%";
  42411. imgFront.style.top = "50%";
  42412. imgFront.style.marginLeft = "-50px";
  42413. imgFront.style.marginTop = "-50px";
  42414. this._loadingDiv.appendChild(imgFront);
  42415. this._resizeLoadingUI();
  42416. window.addEventListener("resize", this._resizeLoadingUI);
  42417. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42418. document.body.appendChild(this._loadingDiv);
  42419. setTimeout(function () {
  42420. _this._loadingDiv.style.opacity = "1";
  42421. imgBack.style.transform = "rotateZ(360deg)";
  42422. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42423. }, 0);
  42424. };
  42425. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42426. var _this = this;
  42427. if (!this._loadingDiv) {
  42428. return;
  42429. }
  42430. var onTransitionEnd = function () {
  42431. if (!_this._loadingDiv) {
  42432. return;
  42433. }
  42434. document.body.removeChild(_this._loadingDiv);
  42435. window.removeEventListener("resize", _this._resizeLoadingUI);
  42436. _this._loadingDiv = null;
  42437. };
  42438. this._loadingDiv.style.opacity = "0";
  42439. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42440. };
  42441. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42442. set: function (text) {
  42443. this._loadingText = text;
  42444. if (this._loadingTextDiv) {
  42445. this._loadingTextDiv.innerHTML = this._loadingText;
  42446. }
  42447. },
  42448. enumerable: true,
  42449. configurable: true
  42450. });
  42451. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42452. get: function () {
  42453. return this._loadingDivBackgroundColor;
  42454. },
  42455. set: function (color) {
  42456. this._loadingDivBackgroundColor = color;
  42457. if (!this._loadingDiv) {
  42458. return;
  42459. }
  42460. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42461. },
  42462. enumerable: true,
  42463. configurable: true
  42464. });
  42465. return DefaultLoadingScreen;
  42466. }());
  42467. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42468. })(BABYLON || (BABYLON = {}));
  42469. //# sourceMappingURL=babylon.loadingScreen.js.map
  42470. var BABYLON;
  42471. (function (BABYLON) {
  42472. var AudioEngine = (function () {
  42473. function AudioEngine() {
  42474. this._audioContext = null;
  42475. this._audioContextInitialized = false;
  42476. this.canUseWebAudio = false;
  42477. this.WarnedWebAudioUnsupported = false;
  42478. this.unlocked = false;
  42479. this.isMP3supported = false;
  42480. this.isOGGsupported = false;
  42481. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  42482. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  42483. this.canUseWebAudio = true;
  42484. }
  42485. var audioElem = document.createElement('audio');
  42486. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  42487. this.isMP3supported = true;
  42488. }
  42489. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  42490. this.isOGGsupported = true;
  42491. }
  42492. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  42493. this._unlockiOSaudio();
  42494. }
  42495. else {
  42496. this.unlocked = true;
  42497. }
  42498. }
  42499. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  42500. get: function () {
  42501. if (!this._audioContextInitialized) {
  42502. this._initializeAudioContext();
  42503. }
  42504. return this._audioContext;
  42505. },
  42506. enumerable: true,
  42507. configurable: true
  42508. });
  42509. AudioEngine.prototype._unlockiOSaudio = function () {
  42510. var _this = this;
  42511. var unlockaudio = function () {
  42512. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  42513. var source = _this.audioContext.createBufferSource();
  42514. source.buffer = buffer;
  42515. source.connect(_this.audioContext.destination);
  42516. source.start(0);
  42517. setTimeout(function () {
  42518. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  42519. _this.unlocked = true;
  42520. window.removeEventListener('touchend', unlockaudio, false);
  42521. if (_this.onAudioUnlocked) {
  42522. _this.onAudioUnlocked();
  42523. }
  42524. }
  42525. }, 0);
  42526. };
  42527. window.addEventListener('touchend', unlockaudio, false);
  42528. };
  42529. AudioEngine.prototype._initializeAudioContext = function () {
  42530. try {
  42531. if (this.canUseWebAudio) {
  42532. this._audioContext = new AudioContext();
  42533. // create a global volume gain node
  42534. this.masterGain = this._audioContext.createGain();
  42535. this.masterGain.gain.value = 1;
  42536. this.masterGain.connect(this._audioContext.destination);
  42537. this._audioContextInitialized = true;
  42538. }
  42539. }
  42540. catch (e) {
  42541. this.canUseWebAudio = false;
  42542. BABYLON.Tools.Error("Web Audio: " + e.message);
  42543. }
  42544. };
  42545. AudioEngine.prototype.dispose = function () {
  42546. if (this.canUseWebAudio && this._audioContextInitialized) {
  42547. if (this._connectedAnalyser) {
  42548. this._connectedAnalyser.stopDebugCanvas();
  42549. this._connectedAnalyser.dispose();
  42550. this.masterGain.disconnect();
  42551. this.masterGain.connect(this._audioContext.destination);
  42552. this._connectedAnalyser = null;
  42553. }
  42554. this.masterGain.gain.value = 1;
  42555. }
  42556. this.WarnedWebAudioUnsupported = false;
  42557. };
  42558. AudioEngine.prototype.getGlobalVolume = function () {
  42559. if (this.canUseWebAudio && this._audioContextInitialized) {
  42560. return this.masterGain.gain.value;
  42561. }
  42562. else {
  42563. return -1;
  42564. }
  42565. };
  42566. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  42567. if (this.canUseWebAudio && this._audioContextInitialized) {
  42568. this.masterGain.gain.value = newVolume;
  42569. }
  42570. };
  42571. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  42572. if (this._connectedAnalyser) {
  42573. this._connectedAnalyser.stopDebugCanvas();
  42574. }
  42575. if (this.canUseWebAudio && this._audioContextInitialized) {
  42576. this._connectedAnalyser = analyser;
  42577. this.masterGain.disconnect();
  42578. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  42579. }
  42580. };
  42581. return AudioEngine;
  42582. }());
  42583. BABYLON.AudioEngine = AudioEngine;
  42584. })(BABYLON || (BABYLON = {}));
  42585. //# sourceMappingURL=babylon.audioEngine.js.map
  42586. var BABYLON;
  42587. (function (BABYLON) {
  42588. var Sound = (function () {
  42589. /**
  42590. * Create a sound and attach it to a scene
  42591. * @param name Name of your sound
  42592. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  42593. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  42594. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  42595. */
  42596. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  42597. var _this = this;
  42598. this.autoplay = false;
  42599. this.loop = false;
  42600. this.useCustomAttenuation = false;
  42601. this.spatialSound = false;
  42602. this.refDistance = 1;
  42603. this.rolloffFactor = 1;
  42604. this.maxDistance = 100;
  42605. this.distanceModel = "linear";
  42606. this._panningModel = "equalpower";
  42607. this._playbackRate = 1;
  42608. this._streaming = false;
  42609. this._startTime = 0;
  42610. this._startOffset = 0;
  42611. this._position = BABYLON.Vector3.Zero();
  42612. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  42613. this._volume = 1;
  42614. this._isLoaded = false;
  42615. this._isReadyToPlay = false;
  42616. this.isPlaying = false;
  42617. this.isPaused = false;
  42618. this._isDirectional = false;
  42619. // Used if you'd like to create a directional sound.
  42620. // If not set, the sound will be omnidirectional
  42621. this._coneInnerAngle = 360;
  42622. this._coneOuterAngle = 360;
  42623. this._coneOuterGain = 0;
  42624. this._isOutputConnected = false;
  42625. this._urlType = "Unknown";
  42626. this.name = name;
  42627. this._scene = scene;
  42628. this._readyToPlayCallback = readyToPlayCallback;
  42629. // Default custom attenuation function is a linear attenuation
  42630. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  42631. if (currentDistance < maxDistance) {
  42632. return currentVolume * (1 - currentDistance / maxDistance);
  42633. }
  42634. else {
  42635. return 0;
  42636. }
  42637. };
  42638. if (options) {
  42639. this.autoplay = options.autoplay || false;
  42640. this.loop = options.loop || false;
  42641. // if volume === 0, we need another way to check this option
  42642. if (options.volume !== undefined) {
  42643. this._volume = options.volume;
  42644. }
  42645. this.spatialSound = options.spatialSound || false;
  42646. this.maxDistance = options.maxDistance || 100;
  42647. this.useCustomAttenuation = options.useCustomAttenuation || false;
  42648. this.rolloffFactor = options.rolloffFactor || 1;
  42649. this.refDistance = options.refDistance || 1;
  42650. this.distanceModel = options.distanceModel || "linear";
  42651. this._playbackRate = options.playbackRate || 1;
  42652. this._streaming = options.streaming || false;
  42653. }
  42654. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42655. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  42656. this._soundGain.gain.value = this._volume;
  42657. this._inputAudioNode = this._soundGain;
  42658. this._ouputAudioNode = this._soundGain;
  42659. if (this.spatialSound) {
  42660. this._createSpatialParameters();
  42661. }
  42662. this._scene.mainSoundTrack.AddSound(this);
  42663. var validParameter = true;
  42664. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  42665. if (urlOrArrayBuffer) {
  42666. if (typeof (urlOrArrayBuffer) === "string")
  42667. this._urlType = "String";
  42668. if (Array.isArray(urlOrArrayBuffer))
  42669. this._urlType = "Array";
  42670. if (urlOrArrayBuffer instanceof ArrayBuffer)
  42671. this._urlType = "ArrayBuffer";
  42672. var urls = [];
  42673. var codecSupportedFound = false;
  42674. switch (this._urlType) {
  42675. case "ArrayBuffer":
  42676. if (urlOrArrayBuffer.byteLength > 0) {
  42677. codecSupportedFound = true;
  42678. this._soundLoaded(urlOrArrayBuffer);
  42679. }
  42680. break;
  42681. case "String":
  42682. urls.push(urlOrArrayBuffer);
  42683. case "Array":
  42684. if (urls.length === 0)
  42685. urls = urlOrArrayBuffer;
  42686. // If we found a supported format, we load it immediately and stop the loop
  42687. for (var i = 0; i < urls.length; i++) {
  42688. var url = urls[i];
  42689. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  42690. codecSupportedFound = true;
  42691. }
  42692. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  42693. codecSupportedFound = true;
  42694. }
  42695. if (url.indexOf(".wav", url.length - 4) !== -1) {
  42696. codecSupportedFound = true;
  42697. }
  42698. if (codecSupportedFound) {
  42699. // Loading sound using XHR2
  42700. if (!this._streaming) {
  42701. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  42702. }
  42703. else {
  42704. this._htmlAudioElement = new Audio(url);
  42705. this._htmlAudioElement.controls = false;
  42706. this._htmlAudioElement.loop = this.loop;
  42707. this._htmlAudioElement.crossOrigin = "anonymous";
  42708. this._htmlAudioElement.preload = "auto";
  42709. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  42710. _this._isReadyToPlay = true;
  42711. if (_this.autoplay) {
  42712. _this.play();
  42713. }
  42714. if (_this._readyToPlayCallback) {
  42715. _this._readyToPlayCallback();
  42716. }
  42717. });
  42718. document.body.appendChild(this._htmlAudioElement);
  42719. }
  42720. break;
  42721. }
  42722. }
  42723. break;
  42724. default:
  42725. validParameter = false;
  42726. break;
  42727. }
  42728. if (!validParameter) {
  42729. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  42730. }
  42731. else {
  42732. if (!codecSupportedFound) {
  42733. this._isReadyToPlay = true;
  42734. // Simulating a ready to play event to avoid breaking code path
  42735. if (this._readyToPlayCallback) {
  42736. window.setTimeout(function () {
  42737. _this._readyToPlayCallback();
  42738. }, 1000);
  42739. }
  42740. }
  42741. }
  42742. }
  42743. }
  42744. else {
  42745. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  42746. this._scene.mainSoundTrack.AddSound(this);
  42747. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  42748. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  42749. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  42750. }
  42751. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  42752. if (this._readyToPlayCallback) {
  42753. window.setTimeout(function () {
  42754. _this._readyToPlayCallback();
  42755. }, 1000);
  42756. }
  42757. }
  42758. }
  42759. Sound.prototype.dispose = function () {
  42760. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  42761. if (this.isPlaying) {
  42762. this.stop();
  42763. }
  42764. this._isReadyToPlay = false;
  42765. if (this.soundTrackId === -1) {
  42766. this._scene.mainSoundTrack.RemoveSound(this);
  42767. }
  42768. else {
  42769. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  42770. }
  42771. if (this._soundGain) {
  42772. this._soundGain.disconnect();
  42773. this._soundGain = null;
  42774. }
  42775. if (this._soundPanner) {
  42776. this._soundPanner.disconnect();
  42777. this._soundPanner = null;
  42778. }
  42779. if (this._soundSource) {
  42780. this._soundSource.disconnect();
  42781. this._soundSource = null;
  42782. }
  42783. this._audioBuffer = null;
  42784. if (this._htmlAudioElement) {
  42785. this._htmlAudioElement.pause();
  42786. this._htmlAudioElement.src = "";
  42787. document.body.removeChild(this._htmlAudioElement);
  42788. }
  42789. if (this._connectedMesh) {
  42790. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  42791. this._connectedMesh = null;
  42792. }
  42793. }
  42794. };
  42795. Sound.prototype.isReady = function () {
  42796. return this._isReadyToPlay;
  42797. };
  42798. Sound.prototype._soundLoaded = function (audioData) {
  42799. var _this = this;
  42800. this._isLoaded = true;
  42801. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  42802. _this._audioBuffer = buffer;
  42803. _this._isReadyToPlay = true;
  42804. if (_this.autoplay) {
  42805. _this.play();
  42806. }
  42807. if (_this._readyToPlayCallback) {
  42808. _this._readyToPlayCallback();
  42809. }
  42810. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  42811. };
  42812. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  42813. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42814. this._audioBuffer = audioBuffer;
  42815. this._isReadyToPlay = true;
  42816. }
  42817. };
  42818. Sound.prototype.updateOptions = function (options) {
  42819. if (options) {
  42820. this.loop = options.loop || this.loop;
  42821. this.maxDistance = options.maxDistance || this.maxDistance;
  42822. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  42823. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  42824. this.refDistance = options.refDistance || this.refDistance;
  42825. this.distanceModel = options.distanceModel || this.distanceModel;
  42826. this._playbackRate = options.playbackRate || this._playbackRate;
  42827. this._updateSpatialParameters();
  42828. if (this.isPlaying) {
  42829. if (this._streaming) {
  42830. this._htmlAudioElement.playbackRate = this._playbackRate;
  42831. }
  42832. else {
  42833. this._soundSource.playbackRate.value = this._playbackRate;
  42834. }
  42835. }
  42836. }
  42837. };
  42838. Sound.prototype._createSpatialParameters = function () {
  42839. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42840. if (this._scene.headphone) {
  42841. this._panningModel = "HRTF";
  42842. }
  42843. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  42844. this._updateSpatialParameters();
  42845. this._soundPanner.connect(this._ouputAudioNode);
  42846. this._inputAudioNode = this._soundPanner;
  42847. }
  42848. };
  42849. Sound.prototype._updateSpatialParameters = function () {
  42850. if (this.spatialSound) {
  42851. if (this.useCustomAttenuation) {
  42852. // Tricks to disable in a way embedded Web Audio attenuation
  42853. this._soundPanner.distanceModel = "linear";
  42854. this._soundPanner.maxDistance = Number.MAX_VALUE;
  42855. this._soundPanner.refDistance = 1;
  42856. this._soundPanner.rolloffFactor = 1;
  42857. this._soundPanner.panningModel = this._panningModel;
  42858. }
  42859. else {
  42860. this._soundPanner.distanceModel = this.distanceModel;
  42861. this._soundPanner.maxDistance = this.maxDistance;
  42862. this._soundPanner.refDistance = this.refDistance;
  42863. this._soundPanner.rolloffFactor = this.rolloffFactor;
  42864. this._soundPanner.panningModel = this._panningModel;
  42865. }
  42866. }
  42867. };
  42868. Sound.prototype.switchPanningModelToHRTF = function () {
  42869. this._panningModel = "HRTF";
  42870. this._switchPanningModel();
  42871. };
  42872. Sound.prototype.switchPanningModelToEqualPower = function () {
  42873. this._panningModel = "equalpower";
  42874. this._switchPanningModel();
  42875. };
  42876. Sound.prototype._switchPanningModel = function () {
  42877. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42878. this._soundPanner.panningModel = this._panningModel;
  42879. }
  42880. };
  42881. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  42882. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  42883. if (this._isOutputConnected) {
  42884. this._ouputAudioNode.disconnect();
  42885. }
  42886. this._ouputAudioNode.connect(soundTrackAudioNode);
  42887. this._isOutputConnected = true;
  42888. }
  42889. };
  42890. /**
  42891. * Transform this sound into a directional source
  42892. * @param coneInnerAngle Size of the inner cone in degree
  42893. * @param coneOuterAngle Size of the outer cone in degree
  42894. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  42895. */
  42896. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  42897. if (coneOuterAngle < coneInnerAngle) {
  42898. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  42899. return;
  42900. }
  42901. this._coneInnerAngle = coneInnerAngle;
  42902. this._coneOuterAngle = coneOuterAngle;
  42903. this._coneOuterGain = coneOuterGain;
  42904. this._isDirectional = true;
  42905. if (this.isPlaying && this.loop) {
  42906. this.stop();
  42907. this.play();
  42908. }
  42909. };
  42910. Sound.prototype.setPosition = function (newPosition) {
  42911. this._position = newPosition;
  42912. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  42913. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42914. }
  42915. };
  42916. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  42917. this._localDirection = newLocalDirection;
  42918. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  42919. this._updateDirection();
  42920. }
  42921. };
  42922. Sound.prototype._updateDirection = function () {
  42923. var mat = this._connectedMesh.getWorldMatrix();
  42924. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  42925. direction.normalize();
  42926. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  42927. };
  42928. Sound.prototype.updateDistanceFromListener = function () {
  42929. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  42930. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  42931. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  42932. }
  42933. };
  42934. Sound.prototype.setAttenuationFunction = function (callback) {
  42935. this._customAttenuationFunction = callback;
  42936. };
  42937. /**
  42938. * Play the sound
  42939. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  42940. * @param offset (optional) Start the sound setting it at a specific time
  42941. */
  42942. Sound.prototype.play = function (time, offset) {
  42943. var _this = this;
  42944. if (this._isReadyToPlay && this._scene.audioEnabled) {
  42945. try {
  42946. if (this._startOffset < 0) {
  42947. time = -this._startOffset;
  42948. this._startOffset = 0;
  42949. }
  42950. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  42951. if (!this._soundSource || !this._streamingSource) {
  42952. if (this.spatialSound) {
  42953. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  42954. if (this._isDirectional) {
  42955. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  42956. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  42957. this._soundPanner.coneOuterGain = this._coneOuterGain;
  42958. if (this._connectedMesh) {
  42959. this._updateDirection();
  42960. }
  42961. else {
  42962. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  42963. }
  42964. }
  42965. }
  42966. }
  42967. if (this._streaming) {
  42968. if (!this._streamingSource) {
  42969. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  42970. this._htmlAudioElement.onended = function () { _this._onended(); };
  42971. this._htmlAudioElement.playbackRate = this._playbackRate;
  42972. }
  42973. this._streamingSource.disconnect();
  42974. this._streamingSource.connect(this._inputAudioNode);
  42975. this._htmlAudioElement.play();
  42976. }
  42977. else {
  42978. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  42979. this._soundSource.buffer = this._audioBuffer;
  42980. this._soundSource.connect(this._inputAudioNode);
  42981. this._soundSource.loop = this.loop;
  42982. this._soundSource.playbackRate.value = this._playbackRate;
  42983. this._soundSource.onended = function () { _this._onended(); };
  42984. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  42985. }
  42986. this._startTime = startTime;
  42987. this.isPlaying = true;
  42988. this.isPaused = false;
  42989. }
  42990. catch (ex) {
  42991. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  42992. }
  42993. }
  42994. };
  42995. Sound.prototype._onended = function () {
  42996. this.isPlaying = false;
  42997. if (this.onended) {
  42998. this.onended();
  42999. }
  43000. };
  43001. /**
  43002. * Stop the sound
  43003. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  43004. */
  43005. Sound.prototype.stop = function (time) {
  43006. if (this.isPlaying) {
  43007. if (this._streaming) {
  43008. this._htmlAudioElement.pause();
  43009. // Test needed for Firefox or it will generate an Invalid State Error
  43010. if (this._htmlAudioElement.currentTime > 0) {
  43011. this._htmlAudioElement.currentTime = 0;
  43012. }
  43013. }
  43014. else {
  43015. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  43016. this._soundSource.stop(stopTime);
  43017. this._soundSource.onended = null;
  43018. if (!this.isPaused) {
  43019. this._startOffset = 0;
  43020. }
  43021. }
  43022. this.isPlaying = false;
  43023. }
  43024. };
  43025. Sound.prototype.pause = function () {
  43026. if (this.isPlaying) {
  43027. this.isPaused = true;
  43028. if (this._streaming) {
  43029. this._htmlAudioElement.pause();
  43030. }
  43031. else {
  43032. this.stop(0);
  43033. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  43034. }
  43035. }
  43036. };
  43037. Sound.prototype.setVolume = function (newVolume, time) {
  43038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43039. if (time) {
  43040. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  43041. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  43042. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  43043. }
  43044. else {
  43045. this._soundGain.gain.value = newVolume;
  43046. }
  43047. }
  43048. this._volume = newVolume;
  43049. };
  43050. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  43051. this._playbackRate = newPlaybackRate;
  43052. if (this.isPlaying) {
  43053. if (this._streaming) {
  43054. this._htmlAudioElement.playbackRate = this._playbackRate;
  43055. }
  43056. else {
  43057. this._soundSource.playbackRate.value = this._playbackRate;
  43058. }
  43059. }
  43060. };
  43061. Sound.prototype.getVolume = function () {
  43062. return this._volume;
  43063. };
  43064. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  43065. var _this = this;
  43066. if (this._connectedMesh) {
  43067. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43068. this._registerFunc = null;
  43069. }
  43070. this._connectedMesh = meshToConnectTo;
  43071. if (!this.spatialSound) {
  43072. this.spatialSound = true;
  43073. this._createSpatialParameters();
  43074. if (this.isPlaying && this.loop) {
  43075. this.stop();
  43076. this.play();
  43077. }
  43078. }
  43079. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  43080. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  43081. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  43082. };
  43083. Sound.prototype.detachFromMesh = function () {
  43084. if (this._connectedMesh) {
  43085. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  43086. this._registerFunc = null;
  43087. this._connectedMesh = null;
  43088. }
  43089. };
  43090. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  43091. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  43092. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  43093. this._updateDirection();
  43094. }
  43095. };
  43096. Sound.prototype.clone = function () {
  43097. var _this = this;
  43098. if (!this._streaming) {
  43099. var setBufferAndRun = function () {
  43100. if (_this._isReadyToPlay) {
  43101. clonedSound._audioBuffer = _this.getAudioBuffer();
  43102. clonedSound._isReadyToPlay = true;
  43103. if (clonedSound.autoplay) {
  43104. clonedSound.play();
  43105. }
  43106. }
  43107. else {
  43108. window.setTimeout(setBufferAndRun, 300);
  43109. }
  43110. };
  43111. var currentOptions = {
  43112. autoplay: this.autoplay, loop: this.loop,
  43113. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  43114. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  43115. refDistance: this.refDistance, distanceModel: this.distanceModel
  43116. };
  43117. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  43118. if (this.useCustomAttenuation) {
  43119. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  43120. }
  43121. clonedSound.setPosition(this._position);
  43122. clonedSound.setPlaybackRate(this._playbackRate);
  43123. setBufferAndRun();
  43124. return clonedSound;
  43125. }
  43126. else {
  43127. return null;
  43128. }
  43129. };
  43130. Sound.prototype.getAudioBuffer = function () {
  43131. return this._audioBuffer;
  43132. };
  43133. Sound.prototype.serialize = function () {
  43134. var serializationObject = {
  43135. name: this.name,
  43136. url: this.name,
  43137. autoplay: this.autoplay,
  43138. loop: this.loop,
  43139. volume: this._volume,
  43140. spatialSound: this.spatialSound,
  43141. maxDistance: this.maxDistance,
  43142. rolloffFactor: this.rolloffFactor,
  43143. refDistance: this.refDistance,
  43144. distanceModel: this.distanceModel,
  43145. playbackRate: this._playbackRate,
  43146. panningModel: this._panningModel,
  43147. soundTrackId: this.soundTrackId
  43148. };
  43149. if (this.spatialSound) {
  43150. if (this._connectedMesh)
  43151. serializationObject.connectedMeshId = this._connectedMesh.id;
  43152. serializationObject.position = this._position.asArray();
  43153. serializationObject.refDistance = this.refDistance;
  43154. serializationObject.distanceModel = this.distanceModel;
  43155. serializationObject.isDirectional = this._isDirectional;
  43156. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  43157. serializationObject.coneInnerAngle = this._coneInnerAngle;
  43158. serializationObject.coneOuterAngle = this._coneOuterAngle;
  43159. serializationObject.coneOuterGain = this._coneOuterGain;
  43160. }
  43161. return serializationObject;
  43162. };
  43163. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  43164. var soundName = parsedSound.name;
  43165. var soundUrl;
  43166. if (parsedSound.url) {
  43167. soundUrl = rootUrl + parsedSound.url;
  43168. }
  43169. else {
  43170. soundUrl = rootUrl + soundName;
  43171. }
  43172. var options = {
  43173. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  43174. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  43175. rolloffFactor: parsedSound.rolloffFactor,
  43176. refDistance: parsedSound.refDistance,
  43177. distanceModel: parsedSound.distanceModel,
  43178. playbackRate: parsedSound.playbackRate
  43179. };
  43180. var newSound;
  43181. if (!sourceSound) {
  43182. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  43183. scene._addPendingData(newSound);
  43184. }
  43185. else {
  43186. var setBufferAndRun = function () {
  43187. if (sourceSound._isReadyToPlay) {
  43188. newSound._audioBuffer = sourceSound.getAudioBuffer();
  43189. newSound._isReadyToPlay = true;
  43190. if (newSound.autoplay) {
  43191. newSound.play();
  43192. }
  43193. }
  43194. else {
  43195. window.setTimeout(setBufferAndRun, 300);
  43196. }
  43197. };
  43198. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  43199. setBufferAndRun();
  43200. }
  43201. if (parsedSound.position) {
  43202. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  43203. newSound.setPosition(soundPosition);
  43204. }
  43205. if (parsedSound.isDirectional) {
  43206. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  43207. if (parsedSound.localDirectionToMesh) {
  43208. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  43209. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  43210. }
  43211. }
  43212. if (parsedSound.connectedMeshId) {
  43213. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  43214. if (connectedMesh) {
  43215. newSound.attachToMesh(connectedMesh);
  43216. }
  43217. }
  43218. return newSound;
  43219. };
  43220. return Sound;
  43221. }());
  43222. BABYLON.Sound = Sound;
  43223. })(BABYLON || (BABYLON = {}));
  43224. //# sourceMappingURL=babylon.sound.js.map
  43225. var BABYLON;
  43226. (function (BABYLON) {
  43227. var SoundTrack = (function () {
  43228. function SoundTrack(scene, options) {
  43229. this.id = -1;
  43230. this._isMainTrack = false;
  43231. this._isInitialized = false;
  43232. this._scene = scene;
  43233. this.soundCollection = new Array();
  43234. this._options = options;
  43235. if (!this._isMainTrack) {
  43236. this._scene.soundTracks.push(this);
  43237. this.id = this._scene.soundTracks.length - 1;
  43238. }
  43239. }
  43240. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  43241. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43242. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  43243. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  43244. if (this._options) {
  43245. if (this._options.volume) {
  43246. this._outputAudioNode.gain.value = this._options.volume;
  43247. }
  43248. if (this._options.mainTrack) {
  43249. this._isMainTrack = this._options.mainTrack;
  43250. }
  43251. }
  43252. this._isInitialized = true;
  43253. }
  43254. };
  43255. SoundTrack.prototype.dispose = function () {
  43256. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43257. if (this._connectedAnalyser) {
  43258. this._connectedAnalyser.stopDebugCanvas();
  43259. }
  43260. while (this.soundCollection.length) {
  43261. this.soundCollection[0].dispose();
  43262. }
  43263. if (this._outputAudioNode) {
  43264. this._outputAudioNode.disconnect();
  43265. }
  43266. this._outputAudioNode = null;
  43267. }
  43268. };
  43269. SoundTrack.prototype.AddSound = function (sound) {
  43270. if (!this._isInitialized) {
  43271. this._initializeSoundTrackAudioGraph();
  43272. }
  43273. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43274. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  43275. }
  43276. if (sound.soundTrackId) {
  43277. if (sound.soundTrackId === -1) {
  43278. this._scene.mainSoundTrack.RemoveSound(sound);
  43279. }
  43280. else {
  43281. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  43282. }
  43283. }
  43284. this.soundCollection.push(sound);
  43285. sound.soundTrackId = this.id;
  43286. };
  43287. SoundTrack.prototype.RemoveSound = function (sound) {
  43288. var index = this.soundCollection.indexOf(sound);
  43289. if (index !== -1) {
  43290. this.soundCollection.splice(index, 1);
  43291. }
  43292. };
  43293. SoundTrack.prototype.setVolume = function (newVolume) {
  43294. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43295. this._outputAudioNode.gain.value = newVolume;
  43296. }
  43297. };
  43298. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  43299. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43300. for (var i = 0; i < this.soundCollection.length; i++) {
  43301. this.soundCollection[i].switchPanningModelToHRTF();
  43302. }
  43303. }
  43304. };
  43305. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  43306. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43307. for (var i = 0; i < this.soundCollection.length; i++) {
  43308. this.soundCollection[i].switchPanningModelToEqualPower();
  43309. }
  43310. }
  43311. };
  43312. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  43313. if (this._connectedAnalyser) {
  43314. this._connectedAnalyser.stopDebugCanvas();
  43315. }
  43316. this._connectedAnalyser = analyser;
  43317. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43318. this._outputAudioNode.disconnect();
  43319. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  43320. }
  43321. };
  43322. return SoundTrack;
  43323. }());
  43324. BABYLON.SoundTrack = SoundTrack;
  43325. })(BABYLON || (BABYLON = {}));
  43326. //# sourceMappingURL=babylon.soundtrack.js.map
  43327. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  43328. /// <reference path="..\Math\babylon.math.ts" />
  43329. var BABYLON;
  43330. (function (BABYLON) {
  43331. /**
  43332. * Special Glow Blur post process only blurring the alpha channel
  43333. * It enforces keeping the most luminous color in the color channel.
  43334. */
  43335. var GlowBlurPostProcess = (function (_super) {
  43336. __extends(GlowBlurPostProcess, _super);
  43337. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  43338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  43339. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  43340. _this.direction = direction;
  43341. _this.blurWidth = blurWidth;
  43342. _this.onApplyObservable.add(function (effect) {
  43343. effect.setFloat2("screenSize", _this.width, _this.height);
  43344. effect.setVector2("direction", _this.direction);
  43345. effect.setFloat("blurWidth", _this.blurWidth);
  43346. });
  43347. return _this;
  43348. }
  43349. return GlowBlurPostProcess;
  43350. }(BABYLON.PostProcess));
  43351. /**
  43352. * The highlight layer Helps adding a glow effect around a mesh.
  43353. *
  43354. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  43355. * glowy meshes to your scene.
  43356. *
  43357. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  43358. */
  43359. var HighlightLayer = (function () {
  43360. /**
  43361. * Instantiates a new highlight Layer and references it to the scene..
  43362. * @param name The name of the layer
  43363. * @param scene The scene to use the layer in
  43364. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  43365. */
  43366. function HighlightLayer(name, scene, options) {
  43367. this.name = name;
  43368. this._vertexBuffers = {};
  43369. this._mainTextureDesiredSize = { width: 0, height: 0 };
  43370. this._meshes = {};
  43371. this._maxSize = 0;
  43372. this._shouldRender = false;
  43373. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  43374. this._excludedMeshes = {};
  43375. /**
  43376. * Specifies whether or not the inner glow is ACTIVE in the layer.
  43377. */
  43378. this.innerGlow = true;
  43379. /**
  43380. * Specifies whether or not the outer glow is ACTIVE in the layer.
  43381. */
  43382. this.outerGlow = true;
  43383. /**
  43384. * Specifies wether the highlight layer is enabled or not.
  43385. */
  43386. this.isEnabled = true;
  43387. /**
  43388. * An event triggered when the highlight layer has been disposed.
  43389. * @type {BABYLON.Observable}
  43390. */
  43391. this.onDisposeObservable = new BABYLON.Observable();
  43392. /**
  43393. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  43394. * @type {BABYLON.Observable}
  43395. */
  43396. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  43397. /**
  43398. * An event triggered when the highlight layer is being blurred.
  43399. * @type {BABYLON.Observable}
  43400. */
  43401. this.onBeforeBlurObservable = new BABYLON.Observable();
  43402. /**
  43403. * An event triggered when the highlight layer has been blurred.
  43404. * @type {BABYLON.Observable}
  43405. */
  43406. this.onAfterBlurObservable = new BABYLON.Observable();
  43407. /**
  43408. * An event triggered when the glowing blurred texture is being merged in the scene.
  43409. * @type {BABYLON.Observable}
  43410. */
  43411. this.onBeforeComposeObservable = new BABYLON.Observable();
  43412. /**
  43413. * An event triggered when the glowing blurred texture has been merged in the scene.
  43414. * @type {BABYLON.Observable}
  43415. */
  43416. this.onAfterComposeObservable = new BABYLON.Observable();
  43417. /**
  43418. * An event triggered when the highlight layer changes its size.
  43419. * @type {BABYLON.Observable}
  43420. */
  43421. this.onSizeChangedObservable = new BABYLON.Observable();
  43422. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43423. var engine = scene.getEngine();
  43424. this._engine = engine;
  43425. this._maxSize = this._engine.getCaps().maxTextureSize;
  43426. this._scene.highlightLayers.push(this);
  43427. // Warn on stencil.
  43428. if (!this._engine.isStencilEnable) {
  43429. 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 }");
  43430. }
  43431. // Adapt options
  43432. this._options = options || {
  43433. mainTextureRatio: 0.25,
  43434. blurTextureSizeRatio: 0.5,
  43435. blurHorizontalSize: 1,
  43436. blurVerticalSize: 1,
  43437. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  43438. };
  43439. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  43440. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  43441. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  43442. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  43443. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  43444. // VBO
  43445. var vertices = [];
  43446. vertices.push(1, 1);
  43447. vertices.push(-1, 1);
  43448. vertices.push(-1, -1);
  43449. vertices.push(1, -1);
  43450. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  43451. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  43452. // Indices
  43453. var indices = [];
  43454. indices.push(0);
  43455. indices.push(1);
  43456. indices.push(2);
  43457. indices.push(0);
  43458. indices.push(2);
  43459. indices.push(3);
  43460. this._indexBuffer = engine.createIndexBuffer(indices);
  43461. // Effect
  43462. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  43463. // Render target
  43464. this.setMainTextureSize();
  43465. // Create Textures and post processes
  43466. this.createTextureAndPostProcesses();
  43467. }
  43468. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  43469. /**
  43470. * Gets the horizontal size of the blur.
  43471. */
  43472. get: function () {
  43473. return this._horizontalBlurPostprocess.blurWidth;
  43474. },
  43475. /**
  43476. * Specifies the horizontal size of the blur.
  43477. */
  43478. set: function (value) {
  43479. this._horizontalBlurPostprocess.blurWidth = value;
  43480. },
  43481. enumerable: true,
  43482. configurable: true
  43483. });
  43484. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  43485. /**
  43486. * Gets the vertical size of the blur.
  43487. */
  43488. get: function () {
  43489. return this._verticalBlurPostprocess.blurWidth;
  43490. },
  43491. /**
  43492. * Specifies the vertical size of the blur.
  43493. */
  43494. set: function (value) {
  43495. this._verticalBlurPostprocess.blurWidth = value;
  43496. },
  43497. enumerable: true,
  43498. configurable: true
  43499. });
  43500. Object.defineProperty(HighlightLayer.prototype, "camera", {
  43501. /**
  43502. * Gets the camera attached to the layer.
  43503. */
  43504. get: function () {
  43505. return this._options.camera;
  43506. },
  43507. enumerable: true,
  43508. configurable: true
  43509. });
  43510. /**
  43511. * Creates the render target textures and post processes used in the highlight layer.
  43512. */
  43513. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  43514. var _this = this;
  43515. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  43516. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  43517. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  43518. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  43519. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  43520. width: this._mainTextureDesiredSize.width,
  43521. height: this._mainTextureDesiredSize.height
  43522. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43523. this._mainTexture.activeCamera = this._options.camera;
  43524. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43525. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43526. this._mainTexture.anisotropicFilteringLevel = 1;
  43527. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  43528. this._mainTexture.renderParticles = false;
  43529. this._mainTexture.renderList = null;
  43530. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  43531. width: blurTextureWidth,
  43532. height: blurTextureHeight
  43533. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  43534. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43535. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43536. this._blurTexture.anisotropicFilteringLevel = 16;
  43537. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  43538. this._blurTexture.renderParticles = false;
  43539. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43540. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  43541. effect.setTexture("textureSampler", _this._mainTexture);
  43542. });
  43543. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  43544. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43545. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43546. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43547. });
  43548. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43549. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43550. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43551. });
  43552. }
  43553. else {
  43554. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43555. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  43556. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43557. });
  43558. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  43559. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  43560. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  43561. });
  43562. }
  43563. this._mainTexture.onAfterUnbindObservable.add(function () {
  43564. _this.onBeforeBlurObservable.notifyObservers(_this);
  43565. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  43566. _this.onAfterBlurObservable.notifyObservers(_this);
  43567. });
  43568. // Custom render function
  43569. var renderSubMesh = function (subMesh) {
  43570. var mesh = subMesh.getRenderingMesh();
  43571. var scene = _this._scene;
  43572. var engine = scene.getEngine();
  43573. // Culling
  43574. engine.setState(subMesh.getMaterial().backFaceCulling);
  43575. // Managing instances
  43576. var batch = mesh._getInstancesRenderList(subMesh._id);
  43577. if (batch.mustReturn) {
  43578. return;
  43579. }
  43580. // Excluded Mesh
  43581. if (_this._excludedMeshes[mesh.uniqueId]) {
  43582. return;
  43583. }
  43584. ;
  43585. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43586. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  43587. var material = subMesh.getMaterial();
  43588. var emissiveTexture = null;
  43589. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  43590. emissiveTexture = material.emissiveTexture;
  43591. }
  43592. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  43593. engine.enableEffect(_this._glowMapGenerationEffect);
  43594. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  43595. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  43596. if (highlightLayerMesh) {
  43597. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  43598. }
  43599. else {
  43600. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  43601. }
  43602. // Alpha test
  43603. if (material && material.needAlphaTesting()) {
  43604. var alphaTexture = material.getAlphaTestTexture();
  43605. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  43606. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43607. }
  43608. // Glow emissive only
  43609. if (emissiveTexture) {
  43610. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  43611. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  43612. }
  43613. // Bones
  43614. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43615. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43616. }
  43617. // Draw
  43618. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  43619. }
  43620. else {
  43621. // Need to reset refresh rate of the shadowMap
  43622. _this._mainTexture.resetRefreshCounter();
  43623. }
  43624. };
  43625. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  43626. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  43627. var index;
  43628. for (index = 0; index < opaqueSubMeshes.length; index++) {
  43629. renderSubMesh(opaqueSubMeshes.data[index]);
  43630. }
  43631. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  43632. renderSubMesh(alphaTestSubMeshes.data[index]);
  43633. }
  43634. for (index = 0; index < transparentSubMeshes.length; index++) {
  43635. renderSubMesh(transparentSubMeshes.data[index]);
  43636. }
  43637. };
  43638. this._mainTexture.onClearObservable.add(function (engine) {
  43639. engine.clear(HighlightLayer.neutralColor, true, true, true);
  43640. });
  43641. };
  43642. /**
  43643. * Checks for the readiness of the element composing the layer.
  43644. * @param subMesh the mesh to check for
  43645. * @param useInstances specify wether or not to use instances to render the mesh
  43646. * @param emissiveTexture the associated emissive texture used to generate the glow
  43647. * @return true if ready otherwise, false
  43648. */
  43649. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  43650. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  43651. return false;
  43652. }
  43653. var defines = [];
  43654. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43655. var mesh = subMesh.getMesh();
  43656. var material = subMesh.getMaterial();
  43657. var uv1 = false;
  43658. var uv2 = false;
  43659. // Alpha test
  43660. if (material && material.needAlphaTesting()) {
  43661. var alphaTexture = material.getAlphaTestTexture();
  43662. if (alphaTexture) {
  43663. defines.push("#define ALPHATEST");
  43664. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43665. alphaTexture.coordinatesIndex === 1) {
  43666. defines.push("#define DIFFUSEUV2");
  43667. uv2 = true;
  43668. }
  43669. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43670. defines.push("#define DIFFUSEUV1");
  43671. uv1 = true;
  43672. }
  43673. }
  43674. }
  43675. // Emissive
  43676. if (emissiveTexture) {
  43677. defines.push("#define EMISSIVE");
  43678. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  43679. emissiveTexture.coordinatesIndex === 1) {
  43680. defines.push("#define EMISSIVEUV2");
  43681. uv2 = true;
  43682. }
  43683. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43684. defines.push("#define EMISSIVEUV1");
  43685. uv1 = true;
  43686. }
  43687. }
  43688. if (uv1) {
  43689. attribs.push(BABYLON.VertexBuffer.UVKind);
  43690. defines.push("#define UV1");
  43691. }
  43692. if (uv2) {
  43693. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43694. defines.push("#define UV2");
  43695. }
  43696. // Bones
  43697. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43698. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43699. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43700. if (mesh.numBoneInfluencers > 4) {
  43701. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43702. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43703. }
  43704. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43705. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43706. }
  43707. else {
  43708. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43709. }
  43710. // Instances
  43711. if (useInstances) {
  43712. defines.push("#define INSTANCES");
  43713. attribs.push("world0");
  43714. attribs.push("world1");
  43715. attribs.push("world2");
  43716. attribs.push("world3");
  43717. }
  43718. // Get correct effect
  43719. var join = defines.join("\n");
  43720. if (this._cachedDefines !== join) {
  43721. this._cachedDefines = join;
  43722. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  43723. }
  43724. return this._glowMapGenerationEffect.isReady();
  43725. };
  43726. /**
  43727. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  43728. */
  43729. HighlightLayer.prototype.render = function () {
  43730. var currentEffect = this._glowMapMergeEffect;
  43731. // Check
  43732. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  43733. return;
  43734. var engine = this._scene.getEngine();
  43735. this.onBeforeComposeObservable.notifyObservers(this);
  43736. // Render
  43737. engine.enableEffect(currentEffect);
  43738. engine.setState(false);
  43739. // Cache
  43740. var previousStencilBuffer = engine.getStencilBuffer();
  43741. var previousStencilFunction = engine.getStencilFunction();
  43742. var previousStencilMask = engine.getStencilMask();
  43743. var previousAlphaMode = engine.getAlphaMode();
  43744. // Texture
  43745. currentEffect.setTexture("textureSampler", this._blurTexture);
  43746. // VBOs
  43747. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  43748. // Draw order
  43749. engine.setAlphaMode(this._options.alphaBlendingMode);
  43750. engine.setStencilMask(0x00);
  43751. engine.setStencilBuffer(true);
  43752. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  43753. if (this.outerGlow) {
  43754. currentEffect.setFloat("offset", 0);
  43755. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  43756. engine.draw(true, 0, 6);
  43757. }
  43758. if (this.innerGlow) {
  43759. currentEffect.setFloat("offset", 1);
  43760. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  43761. engine.draw(true, 0, 6);
  43762. }
  43763. // Restore Cache
  43764. engine.setStencilFunction(previousStencilFunction);
  43765. engine.setStencilMask(previousStencilMask);
  43766. engine.setAlphaMode(previousAlphaMode);
  43767. engine.setStencilBuffer(previousStencilBuffer);
  43768. this.onAfterComposeObservable.notifyObservers(this);
  43769. // Handle size changes.
  43770. var size = this._mainTexture.getSize();
  43771. this.setMainTextureSize();
  43772. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  43773. // Recreate RTT and post processes on size change.
  43774. this.onSizeChangedObservable.notifyObservers(this);
  43775. this.disposeTextureAndPostProcesses();
  43776. this.createTextureAndPostProcesses();
  43777. }
  43778. };
  43779. /**
  43780. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  43781. * @param mesh The mesh to exclude from the highlight layer
  43782. */
  43783. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  43784. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43785. if (!meshExcluded) {
  43786. this._excludedMeshes[mesh.uniqueId] = {
  43787. mesh: mesh,
  43788. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  43789. mesh.getEngine().setStencilBuffer(false);
  43790. }),
  43791. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  43792. mesh.getEngine().setStencilBuffer(true);
  43793. }),
  43794. };
  43795. }
  43796. };
  43797. /**
  43798. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  43799. * @param mesh The mesh to highlight
  43800. */
  43801. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  43802. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  43803. if (meshExcluded) {
  43804. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  43805. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  43806. }
  43807. this._excludedMeshes[mesh.uniqueId] = undefined;
  43808. };
  43809. /**
  43810. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  43811. * @param mesh The mesh to highlight
  43812. * @param color The color of the highlight
  43813. * @param glowEmissiveOnly Extract the glow from the emissive texture
  43814. */
  43815. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  43816. var _this = this;
  43817. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  43818. var meshHighlight = this._meshes[mesh.uniqueId];
  43819. if (meshHighlight) {
  43820. meshHighlight.color = color;
  43821. }
  43822. else {
  43823. this._meshes[mesh.uniqueId] = {
  43824. mesh: mesh,
  43825. color: color,
  43826. // Lambda required for capture due to Observable this context
  43827. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  43828. if (_this._excludedMeshes[mesh.uniqueId]) {
  43829. _this.defaultStencilReference(mesh);
  43830. }
  43831. else {
  43832. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  43833. }
  43834. }),
  43835. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  43836. glowEmissiveOnly: glowEmissiveOnly
  43837. };
  43838. }
  43839. this._shouldRender = true;
  43840. };
  43841. /**
  43842. * Remove a mesh from the highlight layer in order to make it stop glowing.
  43843. * @param mesh The mesh to highlight
  43844. */
  43845. HighlightLayer.prototype.removeMesh = function (mesh) {
  43846. var meshHighlight = this._meshes[mesh.uniqueId];
  43847. if (meshHighlight) {
  43848. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43849. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43850. }
  43851. this._meshes[mesh.uniqueId] = undefined;
  43852. this._shouldRender = false;
  43853. for (var meshHighlightToCheck in this._meshes) {
  43854. if (meshHighlightToCheck) {
  43855. this._shouldRender = true;
  43856. break;
  43857. }
  43858. }
  43859. };
  43860. /**
  43861. * Returns true if the layer contains information to display, otherwise false.
  43862. */
  43863. HighlightLayer.prototype.shouldRender = function () {
  43864. return this.isEnabled && this._shouldRender;
  43865. };
  43866. /**
  43867. * Sets the main texture desired size which is the closest power of two
  43868. * of the engine canvas size.
  43869. */
  43870. HighlightLayer.prototype.setMainTextureSize = function () {
  43871. if (this._options.mainTextureFixedSize) {
  43872. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  43873. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  43874. }
  43875. else {
  43876. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  43877. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  43878. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  43879. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  43880. }
  43881. };
  43882. /**
  43883. * Force the stencil to the normal expected value for none glowing parts
  43884. */
  43885. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  43886. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  43887. };
  43888. /**
  43889. * Dispose only the render target textures and post process.
  43890. */
  43891. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  43892. this._blurTexture.dispose();
  43893. this._mainTexture.dispose();
  43894. this._downSamplePostprocess.dispose();
  43895. this._horizontalBlurPostprocess.dispose();
  43896. this._verticalBlurPostprocess.dispose();
  43897. };
  43898. /**
  43899. * Dispose the highlight layer and free resources.
  43900. */
  43901. HighlightLayer.prototype.dispose = function () {
  43902. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  43903. if (vertexBuffer) {
  43904. vertexBuffer.dispose();
  43905. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  43906. }
  43907. if (this._indexBuffer) {
  43908. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43909. this._indexBuffer = null;
  43910. }
  43911. // Clean textures and post processes
  43912. this.disposeTextureAndPostProcesses();
  43913. // Clean mesh references
  43914. for (var id in this._meshes) {
  43915. var meshHighlight = this._meshes[id];
  43916. if (meshHighlight && meshHighlight.mesh) {
  43917. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  43918. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  43919. }
  43920. }
  43921. this._meshes = null;
  43922. for (var id in this._excludedMeshes) {
  43923. var meshHighlight = this._excludedMeshes[id];
  43924. if (meshHighlight) {
  43925. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  43926. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  43927. }
  43928. }
  43929. this._excludedMeshes = null;
  43930. // Remove from scene
  43931. var index = this._scene.highlightLayers.indexOf(this, 0);
  43932. if (index > -1) {
  43933. this._scene.highlightLayers.splice(index, 1);
  43934. }
  43935. // Callback
  43936. this.onDisposeObservable.notifyObservers(this);
  43937. this.onDisposeObservable.clear();
  43938. this.onBeforeRenderMainTextureObservable.clear();
  43939. this.onBeforeBlurObservable.clear();
  43940. this.onBeforeComposeObservable.clear();
  43941. this.onAfterComposeObservable.clear();
  43942. this.onSizeChangedObservable.clear();
  43943. };
  43944. return HighlightLayer;
  43945. }());
  43946. /**
  43947. * The neutral color used during the preparation of the glow effect.
  43948. * This is black by default as the blend operation is a blend operation.
  43949. */
  43950. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  43951. /**
  43952. * Stencil value used for glowing meshes.
  43953. */
  43954. HighlightLayer.glowingMeshStencilReference = 0x02;
  43955. /**
  43956. * Stencil value used for the other meshes in the scene.
  43957. */
  43958. HighlightLayer.normalMeshStencilReference = 0x01;
  43959. BABYLON.HighlightLayer = HighlightLayer;
  43960. })(BABYLON || (BABYLON = {}));
  43961. //# sourceMappingURL=babylon.highlightlayer.js.map
  43962. var BABYLON;
  43963. (function (BABYLON) {
  43964. var SIMDVector3 = (function () {
  43965. function SIMDVector3() {
  43966. }
  43967. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  43968. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  43969. };
  43970. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  43971. var m = transformation.m;
  43972. var m0 = SIMD.Float32x4.load(m, 0);
  43973. var m1 = SIMD.Float32x4.load(m, 4);
  43974. var m2 = SIMD.Float32x4.load(m, 8);
  43975. var m3 = SIMD.Float32x4.load(m, 12);
  43976. 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));
  43977. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  43978. result.x = SIMD.Float32x4.extractLane(r, 0);
  43979. result.y = SIMD.Float32x4.extractLane(r, 1);
  43980. result.z = SIMD.Float32x4.extractLane(r, 2);
  43981. };
  43982. return SIMDVector3;
  43983. }());
  43984. var SIMDMatrix = (function () {
  43985. function SIMDMatrix() {
  43986. }
  43987. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  43988. var tm = this.m;
  43989. var om = other.m;
  43990. var m0 = SIMD.Float32x4.load(om, 0);
  43991. var m1 = SIMD.Float32x4.load(om, 4);
  43992. var m2 = SIMD.Float32x4.load(om, 8);
  43993. var m3 = SIMD.Float32x4.load(om, 12);
  43994. for (var i = 0; i < 16; i += 4) {
  43995. 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)))));
  43996. }
  43997. return this;
  43998. };
  43999. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  44000. var src = this.m;
  44001. var dest = other.m;
  44002. // Load the 4 rows
  44003. var src0 = SIMD.Float32x4.load(src, 0);
  44004. var src1 = SIMD.Float32x4.load(src, 4);
  44005. var src2 = SIMD.Float32x4.load(src, 8);
  44006. var src3 = SIMD.Float32x4.load(src, 12);
  44007. // Transpose the source matrix. Sort of. Not a true transpose operation
  44008. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  44009. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  44010. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  44011. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  44012. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  44013. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  44014. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  44015. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  44016. // This is a true transposition, but it will lead to an incorrect result
  44017. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  44018. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  44019. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  44020. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  44021. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  44022. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  44023. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  44024. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  44025. // ----
  44026. tmp1 = SIMD.Float32x4.mul(row2, row3);
  44027. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44028. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  44029. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  44030. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44031. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  44032. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  44033. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  44034. // ----
  44035. tmp1 = SIMD.Float32x4.mul(row1, row2);
  44036. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44037. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  44038. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  44039. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44040. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  44041. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  44042. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  44043. // ----
  44044. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  44045. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44046. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  44047. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  44048. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  44049. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44050. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  44051. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  44052. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  44053. // ----
  44054. tmp1 = SIMD.Float32x4.mul(row0, row1);
  44055. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44056. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  44057. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  44058. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44059. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  44060. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  44061. // ----
  44062. tmp1 = SIMD.Float32x4.mul(row0, row3);
  44063. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44064. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  44065. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  44066. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44067. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  44068. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  44069. // ----
  44070. tmp1 = SIMD.Float32x4.mul(row0, row2);
  44071. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  44072. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  44073. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  44074. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  44075. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  44076. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  44077. // Compute determinant
  44078. var det = SIMD.Float32x4.mul(row0, minor0);
  44079. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  44080. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  44081. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  44082. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  44083. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  44084. // These shuffles aren't necessary if the faulty transposition is done
  44085. // up at the top of this function.
  44086. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  44087. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  44088. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  44089. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  44090. // Compute final values by multiplying with 1/det
  44091. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  44092. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  44093. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  44094. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  44095. return this;
  44096. };
  44097. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  44098. var out = result.m;
  44099. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  44100. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  44101. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  44102. // cc.kmVec3Subtract(f, pCenter, pEye);
  44103. var f = SIMD.Float32x4.sub(center, eye);
  44104. // cc.kmVec3Normalize(f, f);
  44105. var tmp = SIMD.Float32x4.mul(f, f);
  44106. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44107. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44108. // cc.kmVec3Assign(up, pUp);
  44109. // cc.kmVec3Normalize(up, up);
  44110. tmp = SIMD.Float32x4.mul(up, up);
  44111. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44112. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44113. // cc.kmVec3Cross(s, f, up);
  44114. 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)));
  44115. // cc.kmVec3Normalize(s, s);
  44116. tmp = SIMD.Float32x4.mul(s, s);
  44117. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44118. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44119. // cc.kmVec3Cross(u, s, f);
  44120. 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)));
  44121. // cc.kmVec3Normalize(s, s);
  44122. tmp = SIMD.Float32x4.mul(s, s);
  44123. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  44124. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  44125. var zero = SIMD.Float32x4.splat(0.0);
  44126. s = SIMD.Float32x4.neg(s);
  44127. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  44128. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  44129. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  44130. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  44131. 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);
  44132. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  44133. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  44134. 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)))));
  44135. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  44136. 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)))));
  44137. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  44138. 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)))));
  44139. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  44140. 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)))));
  44141. };
  44142. return SIMDMatrix;
  44143. }());
  44144. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  44145. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  44146. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  44147. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  44148. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  44149. var SIMDHelper = (function () {
  44150. function SIMDHelper() {
  44151. }
  44152. Object.defineProperty(SIMDHelper, "IsEnabled", {
  44153. get: function () {
  44154. return SIMDHelper._isEnabled;
  44155. },
  44156. enumerable: true,
  44157. configurable: true
  44158. });
  44159. SIMDHelper.DisableSIMD = function () {
  44160. // Replace functions
  44161. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  44162. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  44163. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  44164. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  44165. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  44166. SIMDHelper._isEnabled = false;
  44167. };
  44168. SIMDHelper.EnableSIMD = function () {
  44169. if (self.SIMD === undefined) {
  44170. return;
  44171. }
  44172. // check if polyfills needed
  44173. if (!self.Math.fround) {
  44174. self.Math.fround = (function (array) { return function (x) {
  44175. return array[0] = x, array[0];
  44176. }; })(new Float32Array(1));
  44177. }
  44178. if (!self.Math.imul) {
  44179. self.Math.imul = function (a, b) {
  44180. var ah = (a >>> 16) & 0xffff;
  44181. var al = a & 0xffff;
  44182. var bh = (b >>> 16) & 0xffff;
  44183. var bl = b & 0xffff;
  44184. // the shift by 0 fixes the sign on the high part
  44185. // the final |0 converts the unsigned value into a signed value
  44186. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  44187. };
  44188. }
  44189. // Replace functions
  44190. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  44191. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  44192. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  44193. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  44194. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  44195. SIMDHelper._isEnabled = true;
  44196. };
  44197. return SIMDHelper;
  44198. }());
  44199. SIMDHelper._isEnabled = false;
  44200. BABYLON.SIMDHelper = SIMDHelper;
  44201. })(BABYLON || (BABYLON = {}));
  44202. //# sourceMappingURL=babylon.math.SIMD.js.map
  44203. var BABYLON;
  44204. (function (BABYLON) {
  44205. /**
  44206. * This class describe a rectangle that were added to the map.
  44207. * You have access to its coordinates either in pixel or normalized (UV)
  44208. */
  44209. var PackedRect = (function () {
  44210. function PackedRect(root, parent, pos, size) {
  44211. this._pos = pos;
  44212. this._size = size;
  44213. this._root = root;
  44214. this._parent = parent;
  44215. this._contentSize = null;
  44216. this._bottomNode = null;
  44217. this._leftNode = null;
  44218. this._initialSize = null;
  44219. this._rightNode = null;
  44220. }
  44221. Object.defineProperty(PackedRect.prototype, "pos", {
  44222. /**
  44223. * @returns the position of this node into the map
  44224. */
  44225. get: function () {
  44226. return this._pos;
  44227. },
  44228. enumerable: true,
  44229. configurable: true
  44230. });
  44231. Object.defineProperty(PackedRect.prototype, "contentSize", {
  44232. /**
  44233. * @returns the size of the rectangle this node handles
  44234. */
  44235. get: function () {
  44236. return this._contentSize;
  44237. },
  44238. enumerable: true,
  44239. configurable: true
  44240. });
  44241. /**
  44242. * Retrieve the inner position (considering the margin) and stores it into the res object
  44243. * @param res must be a valid Vector2 that will contain the inner position after this call
  44244. */
  44245. PackedRect.prototype.getInnerPosToRef = function (res) {
  44246. var m = this._root._margin;
  44247. res.x = this._pos.x + m;
  44248. res.y = this._pos.y + m;
  44249. };
  44250. /**
  44251. * Retrieve the inner size (considering the margin) and stores it into the res object
  44252. * @param res must be a valid Size that will contain the inner size after this call
  44253. */
  44254. PackedRect.prototype.getInnerSizeToRef = function (res) {
  44255. var m = this._root._margin;
  44256. res.width = this._contentSize.width - (m * 2);
  44257. res.height = this._contentSize.height - (m * 2);
  44258. };
  44259. Object.defineProperty(PackedRect.prototype, "UVs", {
  44260. /**
  44261. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  44262. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  44263. */
  44264. get: function () {
  44265. if (!this._contentSize) {
  44266. throw new Error("Can't compute UVs for this object because it's nor allocated");
  44267. }
  44268. return this.getUVsForCustomSize(this._contentSize);
  44269. },
  44270. enumerable: true,
  44271. configurable: true
  44272. });
  44273. /**
  44274. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  44275. * and then using only a part of the PackRect.
  44276. * This method will return the UVs for this part by given the custom size of what you really use
  44277. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  44278. */
  44279. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  44280. var mainWidth = this._root._size.width;
  44281. var mainHeight = this._root._size.height;
  44282. var margin = this._root._margin;
  44283. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  44284. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  44285. var uvs = new Array();
  44286. uvs.push(topLeft);
  44287. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  44288. uvs.push(rightBottom);
  44289. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  44290. return uvs;
  44291. };
  44292. /**
  44293. * Free this rectangle from the map.
  44294. * Call this method when you no longer need the rectangle to be in the map.
  44295. */
  44296. PackedRect.prototype.freeContent = function () {
  44297. if (!this.contentSize) {
  44298. return;
  44299. }
  44300. this._contentSize = null;
  44301. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  44302. this.attemptDefrag();
  44303. };
  44304. Object.defineProperty(PackedRect.prototype, "isUsed", {
  44305. get: function () {
  44306. return this._contentSize != null || this._leftNode != null;
  44307. },
  44308. enumerable: true,
  44309. configurable: true
  44310. });
  44311. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  44312. var node = this.findNode(contentSize);
  44313. // Not enough space...
  44314. if (!node) {
  44315. return null;
  44316. }
  44317. node.splitNode(contentSize);
  44318. return node;
  44319. };
  44320. PackedRect.prototype.findNode = function (size) {
  44321. var resNode = null;
  44322. var margin = this._root._margin * 2;
  44323. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  44324. if (this.isUsed) {
  44325. if (this._leftNode) {
  44326. resNode = this._leftNode.findNode(size);
  44327. }
  44328. if (!resNode && this._rightNode) {
  44329. resNode = this._rightNode.findNode(size);
  44330. }
  44331. if (!resNode && this._bottomNode) {
  44332. resNode = this._bottomNode.findNode(size);
  44333. }
  44334. }
  44335. else if (this._initialSize) {
  44336. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  44337. resNode = this;
  44338. }
  44339. else {
  44340. return null;
  44341. }
  44342. }
  44343. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  44344. resNode = this;
  44345. }
  44346. return resNode;
  44347. };
  44348. PackedRect.prototype.splitNode = function (contentSize) {
  44349. var cs = PackedRect.TpsSize;
  44350. var margin = this._root._margin * 2;
  44351. cs.copyFrom(contentSize);
  44352. cs.width += margin;
  44353. cs.height += margin;
  44354. // 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)
  44355. if (!this._contentSize && this._initialSize) {
  44356. this._contentSize = cs.clone();
  44357. 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));
  44358. return this._leftNode.splitNode(contentSize);
  44359. }
  44360. else {
  44361. this._contentSize = cs.clone();
  44362. this._initialSize = cs.clone();
  44363. if (cs.width !== this._size.width) {
  44364. 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));
  44365. }
  44366. if (cs.height !== this._size.height) {
  44367. 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));
  44368. }
  44369. return this;
  44370. }
  44371. };
  44372. PackedRect.prototype.attemptDefrag = function () {
  44373. if (!this.isUsed && this.isRecursiveFree) {
  44374. this.clearNode();
  44375. if (this._parent) {
  44376. this._parent.attemptDefrag();
  44377. }
  44378. }
  44379. };
  44380. PackedRect.prototype.clearNode = function () {
  44381. this._initialSize = null;
  44382. this._rightNode = null;
  44383. this._bottomNode = null;
  44384. };
  44385. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  44386. get: function () {
  44387. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  44388. },
  44389. enumerable: true,
  44390. configurable: true
  44391. });
  44392. PackedRect.prototype.evalFreeSize = function (size) {
  44393. var levelSize = 0;
  44394. if (!this.isUsed) {
  44395. var margin = this._root._margin;
  44396. var is = this._initialSize;
  44397. if (is) {
  44398. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  44399. }
  44400. else {
  44401. var size_1 = this._size;
  44402. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  44403. }
  44404. }
  44405. if (this._rightNode) {
  44406. levelSize += this._rightNode.evalFreeSize(0);
  44407. }
  44408. if (this._bottomNode) {
  44409. levelSize += this._bottomNode.evalFreeSize(0);
  44410. }
  44411. return levelSize + size;
  44412. };
  44413. return PackedRect;
  44414. }());
  44415. PackedRect.TpsSize = BABYLON.Size.Zero();
  44416. BABYLON.PackedRect = PackedRect;
  44417. /**
  44418. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  44419. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  44420. * 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.
  44421. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  44422. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  44423. */
  44424. var RectPackingMap = (function (_super) {
  44425. __extends(RectPackingMap, _super);
  44426. /**
  44427. * Create an instance of the object with a dimension using the given size
  44428. * @param size The dimension of the rectangle that will contain all the sub ones.
  44429. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  44430. */
  44431. function RectPackingMap(size, margin) {
  44432. if (margin === void 0) { margin = 0; }
  44433. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  44434. _this._margin = margin;
  44435. _this._root = _this;
  44436. return _this;
  44437. }
  44438. /**
  44439. * Add a rectangle, finding the best location to store it into the map
  44440. * @param size the dimension of the rectangle to store
  44441. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  44442. */
  44443. RectPackingMap.prototype.addRect = function (size) {
  44444. var node = this.findAndSplitNode(size);
  44445. return node;
  44446. };
  44447. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  44448. /**
  44449. * Return the current space free normalized between [0;1]
  44450. * @returns {}
  44451. */
  44452. get: function () {
  44453. var freeSize = 0;
  44454. freeSize = this.evalFreeSize(freeSize);
  44455. return freeSize / (this._size.width * this._size.height);
  44456. },
  44457. enumerable: true,
  44458. configurable: true
  44459. });
  44460. return RectPackingMap;
  44461. }(PackedRect));
  44462. BABYLON.RectPackingMap = RectPackingMap;
  44463. })(BABYLON || (BABYLON = {}));
  44464. //# sourceMappingURL=babylon.rectPackingMap.js.map
  44465. var BABYLON;
  44466. (function (BABYLON) {
  44467. var DynamicFloatArrayElementInfo = (function () {
  44468. function DynamicFloatArrayElementInfo() {
  44469. }
  44470. return DynamicFloatArrayElementInfo;
  44471. }());
  44472. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  44473. /**
  44474. * 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.
  44475. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  44476. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  44477. * 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.
  44478. * 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.
  44479. * 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".
  44480. */
  44481. var DynamicFloatArray = (function () {
  44482. /**
  44483. * Construct an instance of the dynamic float array
  44484. * @param stride size of one element in float (i.e. not bytes!)
  44485. * @param initialElementCount the number of available entries at construction
  44486. */
  44487. function DynamicFloatArray(stride, initialElementCount) {
  44488. this.compareValueOffset = null;
  44489. this.sortingAscending = true;
  44490. this._stride = stride;
  44491. this.buffer = new Float32Array(stride * initialElementCount);
  44492. this._lastUsed = 0;
  44493. this._firstFree = 0;
  44494. this._allEntries = new Array(initialElementCount);
  44495. this._freeEntries = new Array(initialElementCount);
  44496. for (var i = 0; i < initialElementCount; i++) {
  44497. var element = new DynamicFloatArrayElementInfo();
  44498. element.offset = i * stride;
  44499. this._allEntries[i] = element;
  44500. this._freeEntries[initialElementCount - i - 1] = element;
  44501. }
  44502. }
  44503. /**
  44504. * Allocate an element in the array.
  44505. * @return the element info instance that contains the offset into the main buffer of the element's location.
  44506. * Beware, this offset may change when you call pack()
  44507. */
  44508. DynamicFloatArray.prototype.allocElement = function () {
  44509. if (this._freeEntries.length === 0) {
  44510. this._growBuffer();
  44511. }
  44512. var el = this._freeEntries.pop();
  44513. this._lastUsed = Math.max(el.offset, this._lastUsed);
  44514. if (el.offset === this._firstFree) {
  44515. if (this._freeEntries.length > 0) {
  44516. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  44517. }
  44518. else {
  44519. this._firstFree += this._stride;
  44520. }
  44521. }
  44522. return el;
  44523. };
  44524. /**
  44525. * Free the element corresponding to the given element info
  44526. * @param elInfo the element that describe the allocated element
  44527. */
  44528. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  44529. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  44530. this._freeEntries.push(elInfo);
  44531. };
  44532. /**
  44533. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  44534. * 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().
  44535. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  44536. */
  44537. DynamicFloatArray.prototype.pack = function () {
  44538. // no free slot? no need to pack
  44539. if (this._freeEntries.length === 0) {
  44540. return this.buffer;
  44541. }
  44542. // If the buffer is already packed the last used will always be lower than the first free
  44543. // 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.
  44544. if (this._lastUsed < this._firstFree) {
  44545. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  44546. return elementsBuffer_1;
  44547. }
  44548. var s = this._stride;
  44549. // 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
  44550. var lastFree = new DynamicFloatArrayElementInfo();
  44551. lastFree.offset = this.totalElementCount * s;
  44552. this._freeEntries.push(lastFree);
  44553. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  44554. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44555. var firstFreeSlotOffset = sortedFree[0].offset;
  44556. var freeZoneSize = 1;
  44557. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  44558. var prevOffset = sortedFree[0].offset;
  44559. for (var i = 1; i < sortedFree.length; i++) {
  44560. // 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
  44561. if (firstFreeSlotOffset >= occupiedZoneSize) {
  44562. break;
  44563. }
  44564. var curFree = sortedFree[i];
  44565. var curOffset = curFree.offset;
  44566. // Compute the distance between this offset and the previous
  44567. var distance = curOffset - prevOffset;
  44568. // If the distance is the stride size, they are adjacent, it good, move to the next
  44569. if (distance === s) {
  44570. // Free zone is one element bigger
  44571. ++freeZoneSize;
  44572. // as we're about to iterate to the next, the cur becomes the previous...
  44573. prevOffset = curOffset;
  44574. continue;
  44575. }
  44576. // Distance is bigger, which means there's x element between the previous free and this one
  44577. var usedRange = (distance / s) - 1;
  44578. // Two cases the free zone is smaller than the data to move or bigger
  44579. // Copy what can fit in the free zone
  44580. var curMoveOffset = curOffset - s;
  44581. var copyCount = Math.min(freeZoneSize, usedRange);
  44582. for (var j = 0; j < copyCount; j++) {
  44583. var freeI = firstFreeSlotOffset / s;
  44584. var curI = curMoveOffset / s;
  44585. var moveEl = sortedAll[curI];
  44586. this._moveElement(moveEl, firstFreeSlotOffset);
  44587. var replacedEl = sortedAll[freeI];
  44588. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  44589. replacedEl.offset = curMoveOffset;
  44590. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  44591. sortedAll[freeI] = moveEl;
  44592. sortedAll[curI] = replacedEl;
  44593. curMoveOffset -= s;
  44594. firstFreeSlotOffset += s;
  44595. }
  44596. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  44597. if (freeZoneSize <= usedRange) {
  44598. firstFreeSlotOffset = curMoveOffset + s;
  44599. freeZoneSize = 1 + copyCount;
  44600. }
  44601. else {
  44602. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  44603. }
  44604. // as we're about to iterate to the next, the cur becomes the previous...
  44605. prevOffset = curOffset;
  44606. }
  44607. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  44608. this._lastUsed = firstFreeSlotOffset - s;
  44609. this._firstFree = firstFreeSlotOffset;
  44610. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  44611. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  44612. this._allEntries = sortedAll;
  44613. return elementsBuffer;
  44614. };
  44615. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  44616. for (var i = 0; i < this._stride; i++) {
  44617. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  44618. }
  44619. element.offset = destOffset;
  44620. };
  44621. DynamicFloatArray.prototype._growBuffer = function () {
  44622. // Allocate the new buffer with 50% more entries, copy the content of the current one
  44623. var newElCount = Math.floor(this.totalElementCount * 1.5);
  44624. var newBuffer = new Float32Array(newElCount * this._stride);
  44625. newBuffer.set(this.buffer);
  44626. var curCount = this.totalElementCount;
  44627. var addedCount = newElCount - this.totalElementCount;
  44628. for (var i = 0; i < addedCount; i++) {
  44629. var element = new DynamicFloatArrayElementInfo();
  44630. element.offset = (curCount + i) * this.stride;
  44631. this._allEntries.push(element);
  44632. this._freeEntries[addedCount - i - 1] = element;
  44633. }
  44634. this._firstFree = curCount * this.stride;
  44635. this.buffer = newBuffer;
  44636. };
  44637. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  44638. /**
  44639. * Get the total count of entries that can fit in the current buffer
  44640. * @returns the elements count
  44641. */
  44642. get: function () {
  44643. return this._allEntries.length;
  44644. },
  44645. enumerable: true,
  44646. configurable: true
  44647. });
  44648. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  44649. /**
  44650. * Get the count of free entries that can still be allocated without resizing the buffer
  44651. * @returns the free elements count
  44652. */
  44653. get: function () {
  44654. return this._freeEntries.length;
  44655. },
  44656. enumerable: true,
  44657. configurable: true
  44658. });
  44659. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  44660. /**
  44661. * Get the count of allocated elements
  44662. * @returns the allocated elements count
  44663. */
  44664. get: function () {
  44665. return this._allEntries.length - this._freeEntries.length;
  44666. },
  44667. enumerable: true,
  44668. configurable: true
  44669. });
  44670. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  44671. /**
  44672. * Return the size of one element in float
  44673. * @returns the size in float
  44674. */
  44675. get: function () {
  44676. return this._stride;
  44677. },
  44678. enumerable: true,
  44679. configurable: true
  44680. });
  44681. DynamicFloatArray.prototype.sort = function () {
  44682. var _this = this;
  44683. if (!this.compareValueOffset) {
  44684. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  44685. }
  44686. var count = this.usedElementCount;
  44687. // Do we have to (re)create the sort table?
  44688. if (!this._sortTable || this._sortTable.length < count) {
  44689. // 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...
  44690. var newCount = Math.min(this.totalElementCount, count * 2);
  44691. this._sortTable = new Array(newCount);
  44692. }
  44693. if (!this._sortedTable || this._sortedTable.length !== count) {
  44694. this._sortedTable = new Array(count);
  44695. }
  44696. // Because, you know...
  44697. this.pack();
  44698. //let stride = this.stride;
  44699. //for (let i = 0; i < count; i++) {
  44700. // let si = this._sortTable[i];
  44701. // if (!si) {
  44702. // si = new SortInfo();
  44703. // this._sortTable[i] = si;
  44704. // }
  44705. // si.entry = this._allEntries[i];
  44706. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  44707. // si.swapedOffset = null;
  44708. // this._sortedTable[i] = si;
  44709. //}
  44710. var curOffset = 0;
  44711. var stride = this.stride;
  44712. for (var i = 0; i < count; i++, curOffset += stride) {
  44713. var si = this._sortTable[i];
  44714. if (!si) {
  44715. si = new SortInfo();
  44716. this._sortTable[i] = si;
  44717. }
  44718. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  44719. si.offset = curOffset;
  44720. si.swapedOffset = null;
  44721. this._sortedTable[i] = si;
  44722. }
  44723. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  44724. if (this.sortingAscending) {
  44725. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  44726. }
  44727. else {
  44728. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  44729. }
  44730. var swapElements = function (src, dst) {
  44731. for (var i = 0; i < stride; i++) {
  44732. var tps = _this.buffer[dst + i];
  44733. _this.buffer[dst + i] = _this.buffer[src + i];
  44734. _this.buffer[src + i] = tps;
  44735. }
  44736. };
  44737. // 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:
  44738. // 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),
  44739. // and I still want something with a good algorithm complexity.
  44740. // 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,
  44741. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  44742. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  44743. // 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
  44744. // until we find a SortInfo object without a swapedOffset which means we got the right location
  44745. // 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
  44746. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  44747. for (var i = 0; i < count; i++) {
  44748. // Get the element to move
  44749. var sourceSI = this._sortedTable[i];
  44750. var destSI = this._sortTable[i];
  44751. var sourceOff = sourceSI.offset;
  44752. // If the source changed location, find the new one
  44753. if (sourceSI.swapedOffset) {
  44754. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  44755. var curSI = sourceSI;
  44756. while (curSI.swapedOffset) {
  44757. curSI = this._sortTable[curSI.swapedOffset / stride];
  44758. }
  44759. // Finally get the right location
  44760. sourceOff = curSI.offset;
  44761. }
  44762. // Tag the element being replaced with its new location
  44763. destSI.swapedOffset = sourceOff;
  44764. // Swap elements (only if needed)
  44765. if (sourceOff !== destSI.offset) {
  44766. swapElements(sourceOff, destSI.offset);
  44767. }
  44768. // Update the offset in the corresponding DFAE
  44769. //sourceSI.entry.offset = destSI.entry.offset;
  44770. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  44771. }
  44772. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  44773. return true;
  44774. };
  44775. return DynamicFloatArray;
  44776. }());
  44777. BABYLON.DynamicFloatArray = DynamicFloatArray;
  44778. var SortInfo = (function () {
  44779. function SortInfo() {
  44780. this.compareData = this.offset = this.swapedOffset = null;
  44781. }
  44782. return SortInfo;
  44783. }());
  44784. })(BABYLON || (BABYLON = {}));
  44785. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  44786. var BABYLON;
  44787. (function (BABYLON) {
  44788. var MapTexture = (function (_super) {
  44789. __extends(MapTexture, _super);
  44790. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  44791. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44792. if (useMipMap === void 0) { useMipMap = false; }
  44793. if (margin === void 0) { margin = 0; }
  44794. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  44795. _this.name = name;
  44796. _this._size = size;
  44797. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44798. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44799. // Create the rectPackMap that will allocate portion of the texture
  44800. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  44801. // Create the texture that will store the content
  44802. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  44803. return _this;
  44804. }
  44805. /**
  44806. * Allocate a rectangle of a given size in the texture map
  44807. * @param size the size of the rectangle to allocation
  44808. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  44809. */
  44810. MapTexture.prototype.allocateRect = function (size) {
  44811. return this._rectPackingMap.addRect(size);
  44812. };
  44813. /**
  44814. * Free a given rectangle from the texture map
  44815. * @param rectInfo the instance corresponding to the rect to free.
  44816. */
  44817. MapTexture.prototype.freeRect = function (rectInfo) {
  44818. if (rectInfo) {
  44819. rectInfo.freeContent();
  44820. }
  44821. };
  44822. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  44823. /**
  44824. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  44825. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  44826. * @returns {}
  44827. */
  44828. get: function () {
  44829. return this._rectPackingMap.freeSpace;
  44830. },
  44831. enumerable: true,
  44832. configurable: true
  44833. });
  44834. /**
  44835. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  44836. * 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.
  44837. * Don't forget to call unbindTexture when you're done rendering
  44838. * @param rect the zone to render to
  44839. * @param clear true to clear the portion's color/depth data
  44840. */
  44841. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  44842. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  44843. };
  44844. /**
  44845. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  44846. * 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.
  44847. * Don't forget to call unbindTexture when you're done rendering
  44848. * @param pos the position into the texture
  44849. * @param size the portion to fit the clip space to
  44850. * @param clear true to clear the portion's color/depth data
  44851. */
  44852. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  44853. var engine = this.getScene().getEngine();
  44854. engine.bindFramebuffer(this._texture);
  44855. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  44856. if (clear) {
  44857. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  44858. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  44859. }
  44860. };
  44861. /**
  44862. * Unbind the texture map from the rendering engine.
  44863. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  44864. * @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.
  44865. */
  44866. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  44867. // Dump ?
  44868. if (dumpForDebug) {
  44869. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  44870. }
  44871. var engine = this.getScene().getEngine();
  44872. if (this._replacedViewport) {
  44873. engine.setViewport(this._replacedViewport);
  44874. this._replacedViewport = null;
  44875. }
  44876. engine.unBindFramebuffer(this._texture);
  44877. };
  44878. Object.defineProperty(MapTexture.prototype, "canRescale", {
  44879. get: function () {
  44880. return false;
  44881. },
  44882. enumerable: true,
  44883. configurable: true
  44884. });
  44885. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  44886. // Anyway, there's not much point to use this method for this kind of texture I guess
  44887. MapTexture.prototype.clone = function () {
  44888. return null;
  44889. };
  44890. return MapTexture;
  44891. }(BABYLON.Texture));
  44892. BABYLON.MapTexture = MapTexture;
  44893. })(BABYLON || (BABYLON = {}));
  44894. //# sourceMappingURL=babylon.mapTexture.js.map
  44895. var BABYLON;
  44896. (function (BABYLON) {
  44897. var ShaderMaterial = (function (_super) {
  44898. __extends(ShaderMaterial, _super);
  44899. function ShaderMaterial(name, scene, shaderPath, options) {
  44900. var _this = _super.call(this, name, scene) || this;
  44901. _this._textures = {};
  44902. _this._textureArrays = {};
  44903. _this._floats = {};
  44904. _this._floatsArrays = {};
  44905. _this._colors3 = {};
  44906. _this._colors4 = {};
  44907. _this._vectors2 = {};
  44908. _this._vectors3 = {};
  44909. _this._vectors4 = {};
  44910. _this._matrices = {};
  44911. _this._matrices3x3 = {};
  44912. _this._matrices2x2 = {};
  44913. _this._vectors3Arrays = {};
  44914. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  44915. _this._shaderPath = shaderPath;
  44916. options.needAlphaBlending = options.needAlphaBlending || false;
  44917. options.needAlphaTesting = options.needAlphaTesting || false;
  44918. options.attributes = options.attributes || ["position", "normal", "uv"];
  44919. options.uniforms = options.uniforms || ["worldViewProjection"];
  44920. options.samplers = options.samplers || [];
  44921. options.defines = options.defines || [];
  44922. _this._options = options;
  44923. return _this;
  44924. }
  44925. ShaderMaterial.prototype.getClassName = function () {
  44926. return "ShaderMaterial";
  44927. };
  44928. ShaderMaterial.prototype.needAlphaBlending = function () {
  44929. return this._options.needAlphaBlending;
  44930. };
  44931. ShaderMaterial.prototype.needAlphaTesting = function () {
  44932. return this._options.needAlphaTesting;
  44933. };
  44934. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  44935. if (this._options.uniforms.indexOf(uniformName) === -1) {
  44936. this._options.uniforms.push(uniformName);
  44937. }
  44938. };
  44939. ShaderMaterial.prototype.setTexture = function (name, texture) {
  44940. if (this._options.samplers.indexOf(name) === -1) {
  44941. this._options.samplers.push(name);
  44942. }
  44943. this._textures[name] = texture;
  44944. return this;
  44945. };
  44946. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  44947. if (this._options.samplers.indexOf(name) === -1) {
  44948. this._options.samplers.push(name);
  44949. }
  44950. this._checkUniform(name);
  44951. this._textureArrays[name] = textures;
  44952. return this;
  44953. };
  44954. ShaderMaterial.prototype.setFloat = function (name, value) {
  44955. this._checkUniform(name);
  44956. this._floats[name] = value;
  44957. return this;
  44958. };
  44959. ShaderMaterial.prototype.setFloats = function (name, value) {
  44960. this._checkUniform(name);
  44961. this._floatsArrays[name] = value;
  44962. return this;
  44963. };
  44964. ShaderMaterial.prototype.setColor3 = function (name, value) {
  44965. this._checkUniform(name);
  44966. this._colors3[name] = value;
  44967. return this;
  44968. };
  44969. ShaderMaterial.prototype.setColor4 = function (name, value) {
  44970. this._checkUniform(name);
  44971. this._colors4[name] = value;
  44972. return this;
  44973. };
  44974. ShaderMaterial.prototype.setVector2 = function (name, value) {
  44975. this._checkUniform(name);
  44976. this._vectors2[name] = value;
  44977. return this;
  44978. };
  44979. ShaderMaterial.prototype.setVector3 = function (name, value) {
  44980. this._checkUniform(name);
  44981. this._vectors3[name] = value;
  44982. return this;
  44983. };
  44984. ShaderMaterial.prototype.setVector4 = function (name, value) {
  44985. this._checkUniform(name);
  44986. this._vectors4[name] = value;
  44987. return this;
  44988. };
  44989. ShaderMaterial.prototype.setMatrix = function (name, value) {
  44990. this._checkUniform(name);
  44991. this._matrices[name] = value;
  44992. return this;
  44993. };
  44994. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  44995. this._checkUniform(name);
  44996. this._matrices3x3[name] = value;
  44997. return this;
  44998. };
  44999. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  45000. this._checkUniform(name);
  45001. this._matrices2x2[name] = value;
  45002. return this;
  45003. };
  45004. ShaderMaterial.prototype.setArray3 = function (name, value) {
  45005. this._checkUniform(name);
  45006. this._vectors3Arrays[name] = value;
  45007. return this;
  45008. };
  45009. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  45010. if (!mesh) {
  45011. return true;
  45012. }
  45013. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  45014. return false;
  45015. }
  45016. return false;
  45017. };
  45018. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  45019. var scene = this.getScene();
  45020. var engine = scene.getEngine();
  45021. if (!this.checkReadyOnEveryCall) {
  45022. if (this._renderId === scene.getRenderId()) {
  45023. if (this._checkCache(scene, mesh, useInstances)) {
  45024. return true;
  45025. }
  45026. }
  45027. }
  45028. // Instances
  45029. var defines = [];
  45030. var fallbacks = new BABYLON.EffectFallbacks();
  45031. if (useInstances) {
  45032. defines.push("#define INSTANCES");
  45033. }
  45034. for (var index = 0; index < this._options.defines.length; index++) {
  45035. defines.push(this._options.defines[index]);
  45036. }
  45037. // Bones
  45038. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  45039. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45040. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45041. fallbacks.addCPUSkinningFallback(0, mesh);
  45042. }
  45043. // Textures
  45044. for (var name in this._textures) {
  45045. if (!this._textures[name].isReady()) {
  45046. return false;
  45047. }
  45048. }
  45049. // Alpha test
  45050. if (engine.getAlphaTesting()) {
  45051. defines.push("#define ALPHATEST");
  45052. }
  45053. var previousEffect = this._effect;
  45054. var join = defines.join("\n");
  45055. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  45056. if (!this._effect.isReady()) {
  45057. return false;
  45058. }
  45059. if (previousEffect !== this._effect) {
  45060. scene.resetCachedMaterial();
  45061. }
  45062. this._renderId = scene.getRenderId();
  45063. return true;
  45064. };
  45065. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  45066. var scene = this.getScene();
  45067. if (this._options.uniforms.indexOf("world") !== -1) {
  45068. this._effect.setMatrix("world", world);
  45069. }
  45070. if (this._options.uniforms.indexOf("worldView") !== -1) {
  45071. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  45072. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  45073. }
  45074. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  45075. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  45076. }
  45077. };
  45078. ShaderMaterial.prototype.bind = function (world, mesh) {
  45079. // Std values
  45080. this.bindOnlyWorldMatrix(world);
  45081. if (this.getScene().getCachedMaterial() !== this) {
  45082. if (this._options.uniforms.indexOf("view") !== -1) {
  45083. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  45084. }
  45085. if (this._options.uniforms.indexOf("projection") !== -1) {
  45086. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  45087. }
  45088. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  45089. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  45090. }
  45091. // Bones
  45092. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  45093. var name;
  45094. // Texture
  45095. for (name in this._textures) {
  45096. this._effect.setTexture(name, this._textures[name]);
  45097. }
  45098. // Texture arrays
  45099. for (name in this._textureArrays) {
  45100. this._effect.setTextureArray(name, this._textureArrays[name]);
  45101. }
  45102. // Float
  45103. for (name in this._floats) {
  45104. this._effect.setFloat(name, this._floats[name]);
  45105. }
  45106. // Float s
  45107. for (name in this._floatsArrays) {
  45108. this._effect.setArray(name, this._floatsArrays[name]);
  45109. }
  45110. // Color3
  45111. for (name in this._colors3) {
  45112. this._effect.setColor3(name, this._colors3[name]);
  45113. }
  45114. // Color4
  45115. for (name in this._colors4) {
  45116. var color = this._colors4[name];
  45117. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  45118. }
  45119. // Vector2
  45120. for (name in this._vectors2) {
  45121. this._effect.setVector2(name, this._vectors2[name]);
  45122. }
  45123. // Vector3
  45124. for (name in this._vectors3) {
  45125. this._effect.setVector3(name, this._vectors3[name]);
  45126. }
  45127. // Vector4
  45128. for (name in this._vectors4) {
  45129. this._effect.setVector4(name, this._vectors4[name]);
  45130. }
  45131. // Matrix
  45132. for (name in this._matrices) {
  45133. this._effect.setMatrix(name, this._matrices[name]);
  45134. }
  45135. // Matrix 3x3
  45136. for (name in this._matrices3x3) {
  45137. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  45138. }
  45139. // Matrix 2x2
  45140. for (name in this._matrices2x2) {
  45141. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  45142. }
  45143. // Vector3Array
  45144. for (name in this._vectors3Arrays) {
  45145. this._effect.setArray3(name, this._vectors3Arrays[name]);
  45146. }
  45147. }
  45148. _super.prototype.bind.call(this, world, mesh);
  45149. };
  45150. ShaderMaterial.prototype.clone = function (name) {
  45151. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  45152. return newShaderMaterial;
  45153. };
  45154. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45155. if (forceDisposeTextures) {
  45156. var name;
  45157. for (name in this._textures) {
  45158. this._textures[name].dispose();
  45159. }
  45160. for (name in this._textureArrays) {
  45161. var array = this._textureArrays[name];
  45162. for (var index = 0; index < array.length; index++) {
  45163. array[index].dispose();
  45164. }
  45165. }
  45166. }
  45167. this._textures = {};
  45168. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45169. };
  45170. ShaderMaterial.prototype.serialize = function () {
  45171. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45172. serializationObject.customType = "BABYLON.ShaderMaterial";
  45173. serializationObject.options = this._options;
  45174. serializationObject.shaderPath = this._shaderPath;
  45175. var name;
  45176. // Texture
  45177. serializationObject.textures = {};
  45178. for (name in this._textures) {
  45179. serializationObject.textures[name] = this._textures[name].serialize();
  45180. }
  45181. // Texture arrays
  45182. serializationObject.textureArrays = {};
  45183. for (name in this._textureArrays) {
  45184. serializationObject.textureArrays[name] = [];
  45185. var array = this._textureArrays[name];
  45186. for (var index = 0; index < array.length; index++) {
  45187. serializationObject.textureArrays[name].push(array[index].serialize());
  45188. }
  45189. }
  45190. // Float
  45191. serializationObject.floats = {};
  45192. for (name in this._floats) {
  45193. serializationObject.floats[name] = this._floats[name];
  45194. }
  45195. // Float s
  45196. serializationObject.floatArrays = {};
  45197. for (name in this._floatsArrays) {
  45198. serializationObject.floatArrays[name] = this._floatsArrays[name];
  45199. }
  45200. // Color3
  45201. serializationObject.colors3 = {};
  45202. for (name in this._colors3) {
  45203. serializationObject.colors3[name] = this._colors3[name].asArray();
  45204. }
  45205. // Color4
  45206. serializationObject.colors4 = {};
  45207. for (name in this._colors4) {
  45208. serializationObject.colors4[name] = this._colors4[name].asArray();
  45209. }
  45210. // Vector2
  45211. serializationObject.vectors2 = {};
  45212. for (name in this._vectors2) {
  45213. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  45214. }
  45215. // Vector3
  45216. serializationObject.vectors3 = {};
  45217. for (name in this._vectors3) {
  45218. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  45219. }
  45220. // Vector4
  45221. serializationObject.vectors4 = {};
  45222. for (name in this._vectors4) {
  45223. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  45224. }
  45225. // Matrix
  45226. serializationObject.matrices = {};
  45227. for (name in this._matrices) {
  45228. serializationObject.matrices[name] = this._matrices[name].asArray();
  45229. }
  45230. // Matrix 3x3
  45231. serializationObject.matrices3x3 = {};
  45232. for (name in this._matrices3x3) {
  45233. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  45234. }
  45235. // Matrix 2x2
  45236. serializationObject.matrices2x2 = {};
  45237. for (name in this._matrices2x2) {
  45238. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  45239. }
  45240. // Vector3Array
  45241. serializationObject.vectors3Arrays = {};
  45242. for (name in this._vectors3Arrays) {
  45243. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  45244. }
  45245. return serializationObject;
  45246. };
  45247. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  45248. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  45249. var name;
  45250. // Texture
  45251. for (name in source.textures) {
  45252. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  45253. }
  45254. // Texture arrays
  45255. for (name in source.textureArrays) {
  45256. var array = source.textureArrays[name];
  45257. var textureArray = new Array();
  45258. for (var index = 0; index < array.length; index++) {
  45259. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  45260. }
  45261. material.setTextureArray(name, textureArray);
  45262. }
  45263. // Float
  45264. for (name in source.floats) {
  45265. material.setFloat(name, source.floats[name]);
  45266. }
  45267. // Float s
  45268. for (name in source.floatsArrays) {
  45269. material.setFloats(name, source.floatsArrays[name]);
  45270. }
  45271. // Color3
  45272. for (name in source.colors3) {
  45273. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  45274. }
  45275. // Color4
  45276. for (name in source.colors4) {
  45277. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  45278. }
  45279. // Vector2
  45280. for (name in source.vectors2) {
  45281. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  45282. }
  45283. // Vector3
  45284. for (name in source.vectors3) {
  45285. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  45286. }
  45287. // Vector4
  45288. for (name in source.vectors4) {
  45289. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  45290. }
  45291. // Matrix
  45292. for (name in source.matrices) {
  45293. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  45294. }
  45295. // Matrix 3x3
  45296. for (name in source.matrices3x3) {
  45297. material.setMatrix3x3(name, source.matrices3x3[name]);
  45298. }
  45299. // Matrix 2x2
  45300. for (name in source.matrices2x2) {
  45301. material.setMatrix2x2(name, source.matrices2x2[name]);
  45302. }
  45303. // Vector3Array
  45304. for (name in source.vectors3Arrays) {
  45305. material.setArray3(name, source.vectors3Arrays[name]);
  45306. }
  45307. return material;
  45308. };
  45309. return ShaderMaterial;
  45310. }(BABYLON.Material));
  45311. BABYLON.ShaderMaterial = ShaderMaterial;
  45312. })(BABYLON || (BABYLON = {}));
  45313. //# sourceMappingURL=babylon.shaderMaterial.js.map
  45314. var BABYLON;
  45315. (function (BABYLON) {
  45316. var Internals;
  45317. (function (Internals) {
  45318. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  45319. // All values and structures referenced from:
  45320. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  45321. var DDS_MAGIC = 0x20534444;
  45322. 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;
  45323. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  45324. 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;
  45325. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  45326. function FourCCToInt32(value) {
  45327. return value.charCodeAt(0) +
  45328. (value.charCodeAt(1) << 8) +
  45329. (value.charCodeAt(2) << 16) +
  45330. (value.charCodeAt(3) << 24);
  45331. }
  45332. function Int32ToFourCC(value) {
  45333. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  45334. }
  45335. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  45336. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  45337. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  45338. var headerLengthInt = 31; // The header length in 32 bit ints
  45339. // Offsets into the header array
  45340. var off_magic = 0;
  45341. var off_size = 1;
  45342. var off_flags = 2;
  45343. var off_height = 3;
  45344. var off_width = 4;
  45345. var off_mipmapCount = 7;
  45346. var off_pfFlags = 20;
  45347. var off_pfFourCC = 21;
  45348. var off_RGBbpp = 22;
  45349. var off_RMask = 23;
  45350. var off_GMask = 24;
  45351. var off_BMask = 25;
  45352. var off_AMask = 26;
  45353. var off_caps1 = 27;
  45354. var off_caps2 = 28;
  45355. ;
  45356. var DDSTools = (function () {
  45357. function DDSTools() {
  45358. }
  45359. DDSTools.GetDDSInfo = function (arrayBuffer) {
  45360. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  45361. var mipmapCount = 1;
  45362. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  45363. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45364. }
  45365. return {
  45366. width: header[off_width],
  45367. height: header[off_height],
  45368. mipmapCount: mipmapCount,
  45369. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  45370. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  45371. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  45372. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  45373. };
  45374. };
  45375. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45376. var byteArray = new Uint8Array(dataLength);
  45377. var srcData = new Uint8Array(arrayBuffer);
  45378. var index = 0;
  45379. for (var y = height - 1; y >= 0; y--) {
  45380. for (var x = 0; x < width; x++) {
  45381. var srcPos = dataOffset + (x + y * width) * 4;
  45382. byteArray[index + 2] = srcData[srcPos];
  45383. byteArray[index + 1] = srcData[srcPos + 1];
  45384. byteArray[index] = srcData[srcPos + 2];
  45385. byteArray[index + 3] = srcData[srcPos + 3];
  45386. index += 4;
  45387. }
  45388. }
  45389. return byteArray;
  45390. };
  45391. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45392. var byteArray = new Uint8Array(dataLength);
  45393. var srcData = new Uint8Array(arrayBuffer);
  45394. var index = 0;
  45395. for (var y = height - 1; y >= 0; y--) {
  45396. for (var x = 0; x < width; x++) {
  45397. var srcPos = dataOffset + (x + y * width) * 3;
  45398. byteArray[index + 2] = srcData[srcPos];
  45399. byteArray[index + 1] = srcData[srcPos + 1];
  45400. byteArray[index] = srcData[srcPos + 2];
  45401. index += 3;
  45402. }
  45403. }
  45404. return byteArray;
  45405. };
  45406. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  45407. var byteArray = new Uint8Array(dataLength);
  45408. var srcData = new Uint8Array(arrayBuffer);
  45409. var index = 0;
  45410. for (var y = height - 1; y >= 0; y--) {
  45411. for (var x = 0; x < width; x++) {
  45412. var srcPos = dataOffset + (x + y * width);
  45413. byteArray[index] = srcData[srcPos];
  45414. index++;
  45415. }
  45416. }
  45417. return byteArray;
  45418. };
  45419. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  45420. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  45421. if (header[off_magic] != DDS_MAGIC) {
  45422. BABYLON.Tools.Error("Invalid magic number in DDS header");
  45423. return;
  45424. }
  45425. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  45426. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  45427. return;
  45428. }
  45429. if (info.isFourCC) {
  45430. fourCC = header[off_pfFourCC];
  45431. switch (fourCC) {
  45432. case FOURCC_DXT1:
  45433. blockBytes = 8;
  45434. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45435. break;
  45436. case FOURCC_DXT3:
  45437. blockBytes = 16;
  45438. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45439. break;
  45440. case FOURCC_DXT5:
  45441. blockBytes = 16;
  45442. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45443. break;
  45444. default:
  45445. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  45446. return;
  45447. }
  45448. }
  45449. mipmapCount = 1;
  45450. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  45451. mipmapCount = Math.max(1, header[off_mipmapCount]);
  45452. }
  45453. var bpp = header[off_RGBbpp];
  45454. for (var face = 0; face < faces; face++) {
  45455. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45456. width = header[off_width];
  45457. height = header[off_height];
  45458. dataOffset = header[off_size] + 4;
  45459. for (i = 0; i < mipmapCount; ++i) {
  45460. if (info.isRGB) {
  45461. if (bpp === 24) {
  45462. dataLength = width * height * 3;
  45463. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45464. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  45465. }
  45466. else {
  45467. dataLength = width * height * 4;
  45468. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45469. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  45470. }
  45471. }
  45472. else if (info.isLuminance) {
  45473. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  45474. var unpaddedRowSize = width;
  45475. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  45476. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  45477. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  45478. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  45479. }
  45480. else {
  45481. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  45482. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  45483. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  45484. }
  45485. dataOffset += dataLength;
  45486. width *= 0.5;
  45487. height *= 0.5;
  45488. width = Math.max(1.0, width);
  45489. height = Math.max(1.0, height);
  45490. }
  45491. }
  45492. };
  45493. return DDSTools;
  45494. }());
  45495. Internals.DDSTools = DDSTools;
  45496. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45497. })(BABYLON || (BABYLON = {}));
  45498. //# sourceMappingURL=babylon.tools.dds.js.map
  45499. var BABYLON;
  45500. (function (BABYLON) {
  45501. var Internals;
  45502. (function (Internals) {
  45503. /**
  45504. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  45505. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  45506. */
  45507. var KhronosTextureContainer = (function () {
  45508. /**
  45509. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  45510. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  45511. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  45512. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  45513. */
  45514. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  45515. this.arrayBuffer = arrayBuffer;
  45516. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  45517. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  45518. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  45519. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  45520. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  45521. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  45522. BABYLON.Tools.Error("texture missing KTX identifier");
  45523. return;
  45524. }
  45525. // load the reset of the header in native 32 bit int
  45526. var header = new Int32Array(this.arrayBuffer, 12, 13);
  45527. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  45528. var oppositeEndianess = header[0] === 0x01020304;
  45529. // read all the header elements in order they exist in the file, without modification (sans endainness)
  45530. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  45531. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  45532. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  45533. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  45534. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  45535. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  45536. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  45537. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  45538. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  45539. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  45540. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  45541. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  45542. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  45543. if (this.glType !== 0) {
  45544. BABYLON.Tools.Error("only compressed formats currently supported");
  45545. return;
  45546. }
  45547. else {
  45548. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  45549. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  45550. }
  45551. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  45552. BABYLON.Tools.Error("only 2D textures currently supported");
  45553. return;
  45554. }
  45555. if (this.numberOfArrayElements !== 0) {
  45556. BABYLON.Tools.Error("texture arrays not currently supported");
  45557. return;
  45558. }
  45559. if (this.numberOfFaces !== facesExpected) {
  45560. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  45561. return;
  45562. }
  45563. // we now have a completely validated file, so could use existence of loadType as success
  45564. // would need to make this more elaborate & adjust checks above to support more than one load type
  45565. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  45566. }
  45567. // not as fast hardware based, but will probably never need to use
  45568. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  45569. return ((val & 0xFF) << 24)
  45570. | ((val & 0xFF00) << 8)
  45571. | ((val >> 8) & 0xFF00)
  45572. | ((val >> 24) & 0xFF);
  45573. };
  45574. /**
  45575. * It is assumed that the texture has already been created & is currently bound
  45576. */
  45577. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  45578. switch (this.loadType) {
  45579. case KhronosTextureContainer.COMPRESSED_2D:
  45580. this._upload2DCompressedLevels(gl, loadMipmaps);
  45581. break;
  45582. case KhronosTextureContainer.TEX_2D:
  45583. case KhronosTextureContainer.COMPRESSED_3D:
  45584. case KhronosTextureContainer.TEX_3D:
  45585. }
  45586. };
  45587. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  45588. // initialize width & height for level 1
  45589. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  45590. var width = this.pixelWidth;
  45591. var height = this.pixelHeight;
  45592. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  45593. for (var level = 0; level < mipmapCount; level++) {
  45594. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  45595. for (var face = 0; face < this.numberOfFaces; face++) {
  45596. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  45597. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  45598. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  45599. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  45600. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  45601. }
  45602. width = Math.max(1.0, width * 0.5);
  45603. height = Math.max(1.0, height * 0.5);
  45604. }
  45605. };
  45606. return KhronosTextureContainer;
  45607. }());
  45608. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  45609. // load types
  45610. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  45611. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  45612. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  45613. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  45614. Internals.KhronosTextureContainer = KhronosTextureContainer;
  45615. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45616. })(BABYLON || (BABYLON = {}));
  45617. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  45618. var BABYLON;
  45619. (function (BABYLON) {
  45620. var CannonJSPlugin = (function () {
  45621. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  45622. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  45623. if (iterations === void 0) { iterations = 10; }
  45624. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  45625. this.name = "CannonJSPlugin";
  45626. this._physicsMaterials = [];
  45627. this._fixedTimeStep = 1 / 60;
  45628. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45629. this._currentCollisionGroup = 2;
  45630. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  45631. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  45632. this._tmpPosition = BABYLON.Vector3.Zero();
  45633. this._tmpQuaternion = new BABYLON.Quaternion();
  45634. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  45635. this._tmpDeltaRotation = new BABYLON.Quaternion();
  45636. this._tmpUnityRotation = new BABYLON.Quaternion();
  45637. if (!this.isSupported()) {
  45638. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  45639. return;
  45640. }
  45641. this.world = new CANNON.World();
  45642. this.world.broadphase = new CANNON.NaiveBroadphase();
  45643. this.world.solver.iterations = iterations;
  45644. }
  45645. CannonJSPlugin.prototype.setGravity = function (gravity) {
  45646. this.world.gravity.copy(gravity);
  45647. };
  45648. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  45649. this._fixedTimeStep = timeStep;
  45650. };
  45651. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  45652. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  45653. };
  45654. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  45655. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45656. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45657. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  45658. };
  45659. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  45660. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  45661. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  45662. impostor.physicsBody.applyForce(impulse, worldPoint);
  45663. };
  45664. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  45665. //parent-child relationship. Does this impostor has a parent impostor?
  45666. if (impostor.parent) {
  45667. if (impostor.physicsBody) {
  45668. this.removePhysicsBody(impostor);
  45669. //TODO is that needed?
  45670. impostor.forceUpdate();
  45671. }
  45672. return;
  45673. }
  45674. //should a new body be created for this impostor?
  45675. if (impostor.isBodyInitRequired()) {
  45676. var shape = this._createShape(impostor);
  45677. //unregister events, if body is being changed
  45678. var oldBody = impostor.physicsBody;
  45679. if (oldBody) {
  45680. this.removePhysicsBody(impostor);
  45681. }
  45682. //create the body and material
  45683. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  45684. var bodyCreationObject = {
  45685. mass: impostor.getParam("mass"),
  45686. material: material
  45687. };
  45688. // A simple extend, in case native options were used.
  45689. var nativeOptions = impostor.getParam("nativeOptions");
  45690. for (var key in nativeOptions) {
  45691. if (nativeOptions.hasOwnProperty(key)) {
  45692. bodyCreationObject[key] = nativeOptions[key];
  45693. }
  45694. }
  45695. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  45696. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  45697. this.world.addEventListener("preStep", impostor.beforeStep);
  45698. this.world.addEventListener("postStep", impostor.afterStep);
  45699. impostor.physicsBody.addShape(shape);
  45700. this.world.add(impostor.physicsBody);
  45701. //try to keep the body moving in the right direction by taking old properties.
  45702. //Should be tested!
  45703. if (oldBody) {
  45704. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  45705. impostor.physicsBody[param].copy(oldBody[param]);
  45706. });
  45707. }
  45708. this._processChildMeshes(impostor);
  45709. }
  45710. //now update the body's transformation
  45711. this._updatePhysicsBodyTransformation(impostor);
  45712. };
  45713. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  45714. var _this = this;
  45715. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  45716. if (meshChildren.length) {
  45717. var processMesh = function (localPosition, mesh) {
  45718. var childImpostor = mesh.getPhysicsImpostor();
  45719. if (childImpostor) {
  45720. var parent = childImpostor.parent;
  45721. if (parent !== mainImpostor) {
  45722. var localPosition = mesh.position;
  45723. if (childImpostor.physicsBody) {
  45724. _this.removePhysicsBody(childImpostor);
  45725. childImpostor.physicsBody = null;
  45726. }
  45727. childImpostor.parent = mainImpostor;
  45728. childImpostor.resetUpdateFlags();
  45729. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  45730. //Add the mass of the children.
  45731. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  45732. }
  45733. }
  45734. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  45735. };
  45736. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  45737. }
  45738. };
  45739. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  45740. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  45741. this.world.removeEventListener("preStep", impostor.beforeStep);
  45742. this.world.removeEventListener("postStep", impostor.afterStep);
  45743. this.world.remove(impostor.physicsBody);
  45744. };
  45745. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  45746. var mainBody = impostorJoint.mainImpostor.physicsBody;
  45747. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  45748. if (!mainBody || !connectedBody) {
  45749. return;
  45750. }
  45751. var constraint;
  45752. var jointData = impostorJoint.joint.jointData;
  45753. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  45754. var constraintData = {
  45755. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  45756. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  45757. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  45758. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  45759. maxForce: jointData.nativeParams.maxForce,
  45760. collideConnected: !!jointData.collision
  45761. };
  45762. switch (impostorJoint.joint.type) {
  45763. case BABYLON.PhysicsJoint.HingeJoint:
  45764. case BABYLON.PhysicsJoint.Hinge2Joint:
  45765. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  45766. break;
  45767. case BABYLON.PhysicsJoint.DistanceJoint:
  45768. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  45769. break;
  45770. case BABYLON.PhysicsJoint.SpringJoint:
  45771. var springData = jointData;
  45772. constraint = new CANNON.Spring(mainBody, connectedBody, {
  45773. restLength: springData.length,
  45774. stiffness: springData.stiffness,
  45775. damping: springData.damping,
  45776. localAnchorA: constraintData.pivotA,
  45777. localAnchorB: constraintData.pivotB
  45778. });
  45779. break;
  45780. case BABYLON.PhysicsJoint.LockJoint:
  45781. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  45782. break;
  45783. case BABYLON.PhysicsJoint.PointToPointJoint:
  45784. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  45785. default:
  45786. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  45787. break;
  45788. }
  45789. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  45790. constraint.collideConnected = !!jointData.collision;
  45791. impostorJoint.joint.physicsJoint = constraint;
  45792. //don't add spring as constraint, as it is not one.
  45793. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  45794. this.world.addConstraint(constraint);
  45795. }
  45796. else {
  45797. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  45798. constraint.applyForce();
  45799. });
  45800. }
  45801. };
  45802. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  45803. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  45804. };
  45805. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  45806. var index;
  45807. var mat;
  45808. for (index = 0; index < this._physicsMaterials.length; index++) {
  45809. mat = this._physicsMaterials[index];
  45810. if (mat.friction === friction && mat.restitution === restitution) {
  45811. return mat;
  45812. }
  45813. }
  45814. var currentMat = new CANNON.Material(name);
  45815. currentMat.friction = friction;
  45816. currentMat.restitution = restitution;
  45817. this._physicsMaterials.push(currentMat);
  45818. return currentMat;
  45819. };
  45820. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  45821. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  45822. };
  45823. CannonJSPlugin.prototype._createShape = function (impostor) {
  45824. var object = impostor.object;
  45825. var returnValue;
  45826. var extendSize = impostor.getObjectExtendSize();
  45827. switch (impostor.type) {
  45828. case BABYLON.PhysicsImpostor.SphereImpostor:
  45829. var radiusX = extendSize.x;
  45830. var radiusY = extendSize.y;
  45831. var radiusZ = extendSize.z;
  45832. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  45833. break;
  45834. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  45835. case BABYLON.PhysicsImpostor.CylinderImpostor:
  45836. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  45837. break;
  45838. case BABYLON.PhysicsImpostor.BoxImpostor:
  45839. var box = extendSize.scale(0.5);
  45840. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  45841. break;
  45842. case BABYLON.PhysicsImpostor.PlaneImpostor:
  45843. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  45844. returnValue = new CANNON.Plane();
  45845. break;
  45846. case BABYLON.PhysicsImpostor.MeshImpostor:
  45847. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  45848. var rawFaces = object.getIndices ? object.getIndices() : [];
  45849. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  45850. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  45851. break;
  45852. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  45853. returnValue = this._createHeightmap(object);
  45854. break;
  45855. case BABYLON.PhysicsImpostor.ParticleImpostor:
  45856. returnValue = new CANNON.Particle();
  45857. break;
  45858. }
  45859. return returnValue;
  45860. };
  45861. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  45862. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45863. var matrix = [];
  45864. //For now pointDepth will not be used and will be automatically calculated.
  45865. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  45866. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  45867. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  45868. var elementSize = dim * 2 / arraySize;
  45869. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  45870. for (var i = 0; i < pos.length; i = i + 3) {
  45871. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  45872. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  45873. var y = pos[i + 1] + minY;
  45874. if (!matrix[x]) {
  45875. matrix[x] = [];
  45876. }
  45877. if (!matrix[x][z]) {
  45878. matrix[x][z] = y;
  45879. }
  45880. matrix[x][z] = Math.max(y, matrix[x][z]);
  45881. }
  45882. for (var x = 0; x <= arraySize; ++x) {
  45883. if (!matrix[x]) {
  45884. var loc = 1;
  45885. while (!matrix[(x + loc) % arraySize]) {
  45886. loc++;
  45887. }
  45888. matrix[x] = matrix[(x + loc) % arraySize].slice();
  45889. //console.log("missing x", x);
  45890. }
  45891. for (var z = 0; z <= arraySize; ++z) {
  45892. if (!matrix[x][z]) {
  45893. var loc = 1;
  45894. var newValue;
  45895. while (newValue === undefined) {
  45896. newValue = matrix[x][(z + loc++) % arraySize];
  45897. }
  45898. matrix[x][z] = newValue;
  45899. }
  45900. }
  45901. }
  45902. var shape = new CANNON.Heightfield(matrix, {
  45903. elementSize: elementSize
  45904. });
  45905. //For future reference, needed for body transformation
  45906. shape.minY = minY;
  45907. return shape;
  45908. };
  45909. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  45910. var object = impostor.object;
  45911. //make sure it is updated...
  45912. object.computeWorldMatrix && object.computeWorldMatrix(true);
  45913. // The delta between the mesh position and the mesh bounding box center
  45914. var center = impostor.getObjectCenter();
  45915. var extendSize = impostor.getObjectExtendSize();
  45916. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  45917. this._tmpPosition.copyFrom(center);
  45918. var quaternion = object.rotationQuaternion;
  45919. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  45920. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  45921. //-90 DEG in X, precalculated
  45922. quaternion = quaternion.multiply(this._minus90X);
  45923. //Invert! (Precalculated, 90 deg in X)
  45924. //No need to clone. this will never change.
  45925. impostor.setDeltaRotation(this._plus90X);
  45926. }
  45927. //If it is a heightfield, if should be centered.
  45928. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  45929. var mesh = object;
  45930. //calculate the correct body position:
  45931. var rotationQuaternion = mesh.rotationQuaternion;
  45932. mesh.rotationQuaternion = this._tmpUnityRotation;
  45933. mesh.computeWorldMatrix(true);
  45934. //get original center with no rotation
  45935. var c = center.clone();
  45936. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  45937. //rotation is back
  45938. mesh.rotationQuaternion = rotationQuaternion;
  45939. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  45940. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  45941. mesh.setPivotMatrix(p);
  45942. mesh.computeWorldMatrix(true);
  45943. //calculate the translation
  45944. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  45945. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  45946. //add it inverted to the delta
  45947. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  45948. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  45949. mesh.setPivotMatrix(oldPivot);
  45950. mesh.computeWorldMatrix(true);
  45951. }
  45952. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  45953. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  45954. this._tmpPosition.copyFrom(object.position);
  45955. }
  45956. impostor.setDeltaPosition(this._tmpDeltaPosition);
  45957. //Now update the impostor object
  45958. impostor.physicsBody.position.copy(this._tmpPosition);
  45959. impostor.physicsBody.quaternion.copy(quaternion);
  45960. };
  45961. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  45962. impostor.object.position.copyFrom(impostor.physicsBody.position);
  45963. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  45964. };
  45965. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  45966. impostor.physicsBody.position.copy(newPosition);
  45967. impostor.physicsBody.quaternion.copy(newRotation);
  45968. };
  45969. CannonJSPlugin.prototype.isSupported = function () {
  45970. return window.CANNON !== undefined;
  45971. };
  45972. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  45973. impostor.physicsBody.velocity.copy(velocity);
  45974. };
  45975. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  45976. impostor.physicsBody.angularVelocity.copy(velocity);
  45977. };
  45978. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  45979. var v = impostor.physicsBody.velocity;
  45980. if (!v)
  45981. return null;
  45982. return new BABYLON.Vector3(v.x, v.y, v.z);
  45983. };
  45984. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  45985. var v = impostor.physicsBody.angularVelocity;
  45986. if (!v)
  45987. return null;
  45988. return new BABYLON.Vector3(v.x, v.y, v.z);
  45989. };
  45990. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  45991. impostor.physicsBody.mass = mass;
  45992. impostor.physicsBody.updateMassProperties();
  45993. };
  45994. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  45995. impostor.physicsBody.sleep();
  45996. };
  45997. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  45998. impostor.physicsBody.wakeUp();
  45999. };
  46000. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46001. joint.physicsJoint.distance = maxDistance;
  46002. };
  46003. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  46004. if (!motorIndex) {
  46005. joint.physicsJoint.enableMotor();
  46006. }
  46007. };
  46008. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  46009. if (!motorIndex) {
  46010. joint.physicsJoint.disableMotor();
  46011. }
  46012. };
  46013. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46014. if (!motorIndex) {
  46015. joint.physicsJoint.enableMotor();
  46016. joint.physicsJoint.setMotorSpeed(speed);
  46017. if (maxForce) {
  46018. this.setLimit(joint, maxForce);
  46019. }
  46020. }
  46021. };
  46022. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  46023. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  46024. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  46025. };
  46026. CannonJSPlugin.prototype.dispose = function () {
  46027. //nothing to do, actually.
  46028. };
  46029. return CannonJSPlugin;
  46030. }());
  46031. BABYLON.CannonJSPlugin = CannonJSPlugin;
  46032. })(BABYLON || (BABYLON = {}));
  46033. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  46034. var BABYLON;
  46035. (function (BABYLON) {
  46036. var OimoJSPlugin = (function () {
  46037. function OimoJSPlugin(iterations) {
  46038. this.name = "OimoJSPlugin";
  46039. this._tmpImpostorsArray = [];
  46040. this._tmpPositionVector = BABYLON.Vector3.Zero();
  46041. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  46042. this.world.worldscale(1);
  46043. this.world.clear();
  46044. //making sure no stats are calculated
  46045. this.world.isNoStat = true;
  46046. }
  46047. OimoJSPlugin.prototype.setGravity = function (gravity) {
  46048. this.world.gravity.copy(gravity);
  46049. };
  46050. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  46051. this.world.timeStep = timeStep;
  46052. };
  46053. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  46054. var _this = this;
  46055. impostors.forEach(function (impostor) {
  46056. impostor.beforeStep();
  46057. });
  46058. this.world.step();
  46059. impostors.forEach(function (impostor) {
  46060. impostor.afterStep();
  46061. //update the ordered impostors array
  46062. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  46063. });
  46064. //check for collisions
  46065. var contact = this.world.contacts;
  46066. while (contact !== null) {
  46067. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  46068. contact = contact.next;
  46069. continue;
  46070. }
  46071. //is this body colliding with any other? get the impostor
  46072. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  46073. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  46074. if (!mainImpostor || !collidingImpostor) {
  46075. contact = contact.next;
  46076. continue;
  46077. }
  46078. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  46079. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  46080. contact = contact.next;
  46081. }
  46082. };
  46083. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  46084. var mass = impostor.physicsBody.massInfo.mass;
  46085. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  46086. };
  46087. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  46088. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  46089. this.applyImpulse(impostor, force, contactPoint);
  46090. };
  46091. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  46092. var _this = this;
  46093. //parent-child relationship. Does this impostor has a parent impostor?
  46094. if (impostor.parent) {
  46095. if (impostor.physicsBody) {
  46096. this.removePhysicsBody(impostor);
  46097. //TODO is that needed?
  46098. impostor.forceUpdate();
  46099. }
  46100. return;
  46101. }
  46102. if (impostor.isBodyInitRequired()) {
  46103. var bodyConfig = {
  46104. name: impostor.uniqueId,
  46105. //Oimo must have mass, also for static objects.
  46106. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  46107. size: [],
  46108. type: [],
  46109. pos: [],
  46110. rot: [],
  46111. move: impostor.getParam("mass") !== 0,
  46112. //Supporting older versions of Oimo
  46113. world: this.world
  46114. };
  46115. var impostors = [impostor];
  46116. var addToArray = function (parent) {
  46117. if (!parent.getChildMeshes)
  46118. return;
  46119. parent.getChildMeshes().forEach(function (m) {
  46120. if (m.physicsImpostor) {
  46121. impostors.push(m.physicsImpostor);
  46122. m.physicsImpostor._init();
  46123. }
  46124. });
  46125. };
  46126. addToArray(impostor.object);
  46127. var checkWithEpsilon_1 = function (value) {
  46128. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  46129. };
  46130. impostors.forEach(function (i) {
  46131. //get the correct bounding box
  46132. var oldQuaternion = i.object.rotationQuaternion;
  46133. var rot = new OIMO.Euler().setFromQuaternion({
  46134. x: impostor.object.rotationQuaternion.x,
  46135. y: impostor.object.rotationQuaternion.y,
  46136. z: impostor.object.rotationQuaternion.z,
  46137. s: impostor.object.rotationQuaternion.w
  46138. });
  46139. var extendSize = i.getObjectExtendSize();
  46140. if (i === impostor) {
  46141. var center = impostor.getObjectCenter();
  46142. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  46143. //Can also use Array.prototype.push.apply
  46144. bodyConfig.pos.push(center.x);
  46145. bodyConfig.pos.push(center.y);
  46146. bodyConfig.pos.push(center.z);
  46147. //tmp solution
  46148. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  46149. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  46150. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  46151. }
  46152. else {
  46153. bodyConfig.pos.push(i.object.position.x);
  46154. bodyConfig.pos.push(i.object.position.y);
  46155. bodyConfig.pos.push(i.object.position.z);
  46156. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  46157. bodyConfig.rot.push(0);
  46158. bodyConfig.rot.push(0);
  46159. bodyConfig.rot.push(0);
  46160. }
  46161. // register mesh
  46162. switch (i.type) {
  46163. case BABYLON.PhysicsImpostor.ParticleImpostor:
  46164. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  46165. case BABYLON.PhysicsImpostor.SphereImpostor:
  46166. var radiusX = extendSize.x;
  46167. var radiusY = extendSize.y;
  46168. var radiusZ = extendSize.z;
  46169. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  46170. bodyConfig.type.push('sphere');
  46171. //due to the way oimo works with compounds, add 3 times
  46172. bodyConfig.size.push(size);
  46173. bodyConfig.size.push(size);
  46174. bodyConfig.size.push(size);
  46175. break;
  46176. case BABYLON.PhysicsImpostor.CylinderImpostor:
  46177. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  46178. var sizeY = checkWithEpsilon_1(extendSize.y);
  46179. bodyConfig.type.push('cylinder');
  46180. bodyConfig.size.push(sizeX);
  46181. bodyConfig.size.push(sizeY);
  46182. //due to the way oimo works with compounds, add one more value.
  46183. bodyConfig.size.push(sizeY);
  46184. break;
  46185. case BABYLON.PhysicsImpostor.PlaneImpostor:
  46186. case BABYLON.PhysicsImpostor.BoxImpostor:
  46187. default:
  46188. var sizeX = checkWithEpsilon_1(extendSize.x);
  46189. var sizeY = checkWithEpsilon_1(extendSize.y);
  46190. var sizeZ = checkWithEpsilon_1(extendSize.z);
  46191. bodyConfig.type.push('box');
  46192. bodyConfig.size.push(sizeX);
  46193. bodyConfig.size.push(sizeY);
  46194. bodyConfig.size.push(sizeZ);
  46195. break;
  46196. }
  46197. //actually not needed, but hey...
  46198. i.object.rotationQuaternion = oldQuaternion;
  46199. });
  46200. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  46201. }
  46202. else {
  46203. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  46204. }
  46205. impostor.setDeltaPosition(this._tmpPositionVector);
  46206. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  46207. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  46208. };
  46209. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  46210. //impostor.physicsBody.dispose();
  46211. //Same as : (older oimo versions)
  46212. this.world.removeRigidBody(impostor.physicsBody);
  46213. };
  46214. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  46215. var mainBody = impostorJoint.mainImpostor.physicsBody;
  46216. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  46217. if (!mainBody || !connectedBody) {
  46218. return;
  46219. }
  46220. var jointData = impostorJoint.joint.jointData;
  46221. var options = jointData.nativeParams || {};
  46222. var type;
  46223. var nativeJointData = {
  46224. body1: mainBody,
  46225. body2: connectedBody,
  46226. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  46227. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  46228. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  46229. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  46230. min: options.min,
  46231. max: options.max,
  46232. collision: options.collision || jointData.collision,
  46233. spring: options.spring,
  46234. //supporting older version of Oimo
  46235. world: this.world
  46236. };
  46237. switch (impostorJoint.joint.type) {
  46238. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  46239. type = "jointBall";
  46240. break;
  46241. case BABYLON.PhysicsJoint.SpringJoint:
  46242. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  46243. var springData = jointData;
  46244. nativeJointData.min = springData.length || nativeJointData.min;
  46245. //Max should also be set, just make sure it is at least min
  46246. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  46247. case BABYLON.PhysicsJoint.DistanceJoint:
  46248. type = "jointDistance";
  46249. nativeJointData.max = jointData.maxDistance;
  46250. break;
  46251. case BABYLON.PhysicsJoint.PrismaticJoint:
  46252. type = "jointPrisme";
  46253. break;
  46254. case BABYLON.PhysicsJoint.SliderJoint:
  46255. type = "jointSlide";
  46256. break;
  46257. case BABYLON.PhysicsJoint.WheelJoint:
  46258. type = "jointWheel";
  46259. break;
  46260. case BABYLON.PhysicsJoint.HingeJoint:
  46261. default:
  46262. type = "jointHinge";
  46263. break;
  46264. }
  46265. nativeJointData.type = type;
  46266. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  46267. };
  46268. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  46269. //Bug in Oimo prevents us from disposing a joint in the playground
  46270. //joint.joint.physicsJoint.dispose();
  46271. //So we will bruteforce it!
  46272. try {
  46273. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  46274. }
  46275. catch (e) {
  46276. BABYLON.Tools.Warn(e);
  46277. }
  46278. };
  46279. OimoJSPlugin.prototype.isSupported = function () {
  46280. return OIMO !== undefined;
  46281. };
  46282. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  46283. if (!impostor.physicsBody.sleeping) {
  46284. //TODO check that
  46285. if (impostor.physicsBody.shapes.next) {
  46286. var parentShape = this._getLastShape(impostor.physicsBody);
  46287. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  46288. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  46289. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  46290. }
  46291. else {
  46292. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  46293. }
  46294. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  46295. impostor.object.rotationQuaternion.normalize();
  46296. }
  46297. };
  46298. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  46299. var body = impostor.physicsBody;
  46300. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  46301. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  46302. body.syncShapes();
  46303. body.awake();
  46304. };
  46305. OimoJSPlugin.prototype._getLastShape = function (body) {
  46306. var lastShape = body.shapes;
  46307. while (lastShape.next) {
  46308. lastShape = lastShape.next;
  46309. }
  46310. return lastShape;
  46311. };
  46312. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  46313. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  46314. };
  46315. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  46316. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  46317. };
  46318. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  46319. var v = impostor.physicsBody.linearVelocity;
  46320. if (!v)
  46321. return null;
  46322. return new BABYLON.Vector3(v.x, v.y, v.z);
  46323. };
  46324. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  46325. var v = impostor.physicsBody.angularVelocity;
  46326. if (!v)
  46327. return null;
  46328. return new BABYLON.Vector3(v.x, v.y, v.z);
  46329. };
  46330. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  46331. var staticBody = mass === 0;
  46332. //this will actually set the body's density and not its mass.
  46333. //But this is how oimo treats the mass variable.
  46334. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  46335. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  46336. };
  46337. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  46338. impostor.physicsBody.sleep();
  46339. };
  46340. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  46341. impostor.physicsBody.awake();
  46342. };
  46343. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  46344. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  46345. if (minDistance !== void 0) {
  46346. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  46347. }
  46348. };
  46349. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  46350. //TODO separate rotational and transational motors.
  46351. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46352. if (motor) {
  46353. motor.setMotor(speed, maxForce);
  46354. }
  46355. };
  46356. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  46357. //TODO separate rotational and transational motors.
  46358. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  46359. if (motor) {
  46360. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  46361. }
  46362. };
  46363. OimoJSPlugin.prototype.dispose = function () {
  46364. this.world.clear();
  46365. };
  46366. return OimoJSPlugin;
  46367. }());
  46368. BABYLON.OimoJSPlugin = OimoJSPlugin;
  46369. })(BABYLON || (BABYLON = {}));
  46370. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  46371. var BABYLON;
  46372. (function (BABYLON) {
  46373. var DisplayPassPostProcess = (function (_super) {
  46374. __extends(DisplayPassPostProcess, _super);
  46375. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46376. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  46377. }
  46378. return DisplayPassPostProcess;
  46379. }(BABYLON.PostProcess));
  46380. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  46381. })(BABYLON || (BABYLON = {}));
  46382. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  46383. var BABYLON;
  46384. (function (BABYLON) {
  46385. var SimplificationSettings = (function () {
  46386. function SimplificationSettings(quality, distance, optimizeMesh) {
  46387. this.quality = quality;
  46388. this.distance = distance;
  46389. this.optimizeMesh = optimizeMesh;
  46390. }
  46391. return SimplificationSettings;
  46392. }());
  46393. BABYLON.SimplificationSettings = SimplificationSettings;
  46394. var SimplificationQueue = (function () {
  46395. function SimplificationQueue() {
  46396. this.running = false;
  46397. this._simplificationArray = [];
  46398. }
  46399. SimplificationQueue.prototype.addTask = function (task) {
  46400. this._simplificationArray.push(task);
  46401. };
  46402. SimplificationQueue.prototype.executeNext = function () {
  46403. var task = this._simplificationArray.pop();
  46404. if (task) {
  46405. this.running = true;
  46406. this.runSimplification(task);
  46407. }
  46408. else {
  46409. this.running = false;
  46410. }
  46411. };
  46412. SimplificationQueue.prototype.runSimplification = function (task) {
  46413. var _this = this;
  46414. if (task.parallelProcessing) {
  46415. //parallel simplifier
  46416. task.settings.forEach(function (setting) {
  46417. var simplifier = _this.getSimplifier(task);
  46418. simplifier.simplify(setting, function (newMesh) {
  46419. task.mesh.addLODLevel(setting.distance, newMesh);
  46420. newMesh.isVisible = true;
  46421. //check if it is the last
  46422. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  46423. //all done, run the success callback.
  46424. task.successCallback();
  46425. }
  46426. _this.executeNext();
  46427. });
  46428. });
  46429. }
  46430. else {
  46431. //single simplifier.
  46432. var simplifier = this.getSimplifier(task);
  46433. var runDecimation = function (setting, callback) {
  46434. simplifier.simplify(setting, function (newMesh) {
  46435. task.mesh.addLODLevel(setting.distance, newMesh);
  46436. newMesh.isVisible = true;
  46437. //run the next quality level
  46438. callback();
  46439. });
  46440. };
  46441. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  46442. runDecimation(task.settings[loop.index], function () {
  46443. loop.executeNext();
  46444. });
  46445. }, function () {
  46446. //execution ended, run the success callback.
  46447. if (task.successCallback) {
  46448. task.successCallback();
  46449. }
  46450. _this.executeNext();
  46451. });
  46452. }
  46453. };
  46454. SimplificationQueue.prototype.getSimplifier = function (task) {
  46455. switch (task.simplificationType) {
  46456. case SimplificationType.QUADRATIC:
  46457. default:
  46458. return new QuadraticErrorSimplification(task.mesh);
  46459. }
  46460. };
  46461. return SimplificationQueue;
  46462. }());
  46463. BABYLON.SimplificationQueue = SimplificationQueue;
  46464. /**
  46465. * The implemented types of simplification.
  46466. * At the moment only Quadratic Error Decimation is implemented.
  46467. */
  46468. var SimplificationType;
  46469. (function (SimplificationType) {
  46470. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  46471. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  46472. var DecimationTriangle = (function () {
  46473. function DecimationTriangle(vertices) {
  46474. this.vertices = vertices;
  46475. this.error = new Array(4);
  46476. this.deleted = false;
  46477. this.isDirty = false;
  46478. this.deletePending = false;
  46479. this.borderFactor = 0;
  46480. }
  46481. return DecimationTriangle;
  46482. }());
  46483. BABYLON.DecimationTriangle = DecimationTriangle;
  46484. var DecimationVertex = (function () {
  46485. function DecimationVertex(position, id) {
  46486. this.position = position;
  46487. this.id = id;
  46488. this.isBorder = true;
  46489. this.q = new QuadraticMatrix();
  46490. this.triangleCount = 0;
  46491. this.triangleStart = 0;
  46492. this.originalOffsets = [];
  46493. }
  46494. DecimationVertex.prototype.updatePosition = function (newPosition) {
  46495. this.position.copyFrom(newPosition);
  46496. };
  46497. return DecimationVertex;
  46498. }());
  46499. BABYLON.DecimationVertex = DecimationVertex;
  46500. var QuadraticMatrix = (function () {
  46501. function QuadraticMatrix(data) {
  46502. this.data = new Array(10);
  46503. for (var i = 0; i < 10; ++i) {
  46504. if (data && data[i]) {
  46505. this.data[i] = data[i];
  46506. }
  46507. else {
  46508. this.data[i] = 0;
  46509. }
  46510. }
  46511. }
  46512. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  46513. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  46514. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  46515. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  46516. return det;
  46517. };
  46518. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  46519. for (var i = 0; i < 10; ++i) {
  46520. this.data[i] += matrix.data[i];
  46521. }
  46522. };
  46523. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  46524. for (var i = 0; i < 10; ++i) {
  46525. this.data[i] += data[i];
  46526. }
  46527. };
  46528. QuadraticMatrix.prototype.add = function (matrix) {
  46529. var m = new QuadraticMatrix();
  46530. for (var i = 0; i < 10; ++i) {
  46531. m.data[i] = this.data[i] + matrix.data[i];
  46532. }
  46533. return m;
  46534. };
  46535. QuadraticMatrix.FromData = function (a, b, c, d) {
  46536. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  46537. };
  46538. //returning an array to avoid garbage collection
  46539. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  46540. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  46541. };
  46542. return QuadraticMatrix;
  46543. }());
  46544. BABYLON.QuadraticMatrix = QuadraticMatrix;
  46545. var Reference = (function () {
  46546. function Reference(vertexId, triangleId) {
  46547. this.vertexId = vertexId;
  46548. this.triangleId = triangleId;
  46549. }
  46550. return Reference;
  46551. }());
  46552. BABYLON.Reference = Reference;
  46553. /**
  46554. * An implementation of the Quadratic Error simplification algorithm.
  46555. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  46556. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  46557. * @author RaananW
  46558. */
  46559. var QuadraticErrorSimplification = (function () {
  46560. function QuadraticErrorSimplification(_mesh) {
  46561. this._mesh = _mesh;
  46562. this.initialized = false;
  46563. this.syncIterations = 5000;
  46564. this.aggressiveness = 7;
  46565. this.decimationIterations = 100;
  46566. this.boundingBoxEpsilon = BABYLON.Epsilon;
  46567. }
  46568. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  46569. var _this = this;
  46570. this.initDecimatedMesh();
  46571. //iterating through the submeshes array, one after the other.
  46572. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  46573. _this.initWithMesh(loop.index, function () {
  46574. _this.runDecimation(settings, loop.index, function () {
  46575. loop.executeNext();
  46576. });
  46577. }, settings.optimizeMesh);
  46578. }, function () {
  46579. setTimeout(function () {
  46580. successCallback(_this._reconstructedMesh);
  46581. }, 0);
  46582. });
  46583. };
  46584. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  46585. var _this = this;
  46586. var gCount = 0;
  46587. triangle.vertices.forEach(function (vertex) {
  46588. var count = 0;
  46589. var vPos = vertex.position;
  46590. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  46591. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  46592. ++count;
  46593. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  46594. ++count;
  46595. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  46596. ++count;
  46597. if (count > 1) {
  46598. ++gCount;
  46599. }
  46600. ;
  46601. });
  46602. if (gCount > 1) {
  46603. console.log(triangle, gCount);
  46604. }
  46605. return gCount > 1;
  46606. };
  46607. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  46608. var _this = this;
  46609. var targetCount = ~~(this.triangles.length * settings.quality);
  46610. var deletedTriangles = 0;
  46611. var triangleCount = this.triangles.length;
  46612. var iterationFunction = function (iteration, callback) {
  46613. setTimeout(function () {
  46614. if (iteration % 5 === 0) {
  46615. _this.updateMesh(iteration === 0);
  46616. }
  46617. for (var i = 0; i < _this.triangles.length; ++i) {
  46618. _this.triangles[i].isDirty = false;
  46619. }
  46620. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  46621. var trianglesIterator = function (i) {
  46622. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  46623. var t = _this.triangles[tIdx];
  46624. if (!t)
  46625. return;
  46626. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  46627. return;
  46628. }
  46629. for (var j = 0; j < 3; ++j) {
  46630. if (t.error[j] < threshold) {
  46631. var deleted0 = [];
  46632. var deleted1 = [];
  46633. var v0 = t.vertices[j];
  46634. var v1 = t.vertices[(j + 1) % 3];
  46635. if (v0.isBorder || v1.isBorder)
  46636. continue;
  46637. var p = BABYLON.Vector3.Zero();
  46638. var n = BABYLON.Vector3.Zero();
  46639. var uv = BABYLON.Vector2.Zero();
  46640. var color = new BABYLON.Color4(0, 0, 0, 1);
  46641. _this.calculateError(v0, v1, p, n, uv, color);
  46642. var delTr = [];
  46643. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  46644. continue;
  46645. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  46646. continue;
  46647. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  46648. continue;
  46649. var uniqueArray = [];
  46650. delTr.forEach(function (deletedT) {
  46651. if (uniqueArray.indexOf(deletedT) === -1) {
  46652. deletedT.deletePending = true;
  46653. uniqueArray.push(deletedT);
  46654. }
  46655. });
  46656. if (uniqueArray.length % 2 !== 0) {
  46657. continue;
  46658. }
  46659. v0.q = v1.q.add(v0.q);
  46660. v0.updatePosition(p);
  46661. var tStart = _this.references.length;
  46662. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  46663. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  46664. var tCount = _this.references.length - tStart;
  46665. if (tCount <= v0.triangleCount) {
  46666. if (tCount) {
  46667. for (var c = 0; c < tCount; c++) {
  46668. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  46669. }
  46670. }
  46671. }
  46672. else {
  46673. v0.triangleStart = tStart;
  46674. }
  46675. v0.triangleCount = tCount;
  46676. break;
  46677. }
  46678. }
  46679. };
  46680. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  46681. }, 0);
  46682. };
  46683. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  46684. if (triangleCount - deletedTriangles <= targetCount)
  46685. loop.breakLoop();
  46686. else {
  46687. iterationFunction(loop.index, function () {
  46688. loop.executeNext();
  46689. });
  46690. }
  46691. }, function () {
  46692. setTimeout(function () {
  46693. //reconstruct this part of the mesh
  46694. _this.reconstructMesh(submeshIndex);
  46695. successCallback();
  46696. }, 0);
  46697. });
  46698. };
  46699. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  46700. var _this = this;
  46701. this.vertices = [];
  46702. this.triangles = [];
  46703. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46704. var indices = this._mesh.getIndices();
  46705. var submesh = this._mesh.subMeshes[submeshIndex];
  46706. var findInVertices = function (positionToSearch) {
  46707. if (optimizeMesh) {
  46708. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  46709. if (_this.vertices[ii].position.equals(positionToSearch)) {
  46710. return _this.vertices[ii];
  46711. }
  46712. }
  46713. }
  46714. return null;
  46715. };
  46716. var vertexReferences = [];
  46717. var vertexInit = function (i) {
  46718. var offset = i + submesh.verticesStart;
  46719. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  46720. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  46721. vertex.originalOffsets.push(offset);
  46722. if (vertex.id === _this.vertices.length) {
  46723. _this.vertices.push(vertex);
  46724. }
  46725. vertexReferences.push(vertex.id);
  46726. };
  46727. //var totalVertices = mesh.getTotalVertices();
  46728. var totalVertices = submesh.verticesCount;
  46729. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  46730. var indicesInit = function (i) {
  46731. var offset = (submesh.indexStart / 3) + i;
  46732. var pos = (offset * 3);
  46733. var i0 = indices[pos + 0];
  46734. var i1 = indices[pos + 1];
  46735. var i2 = indices[pos + 2];
  46736. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  46737. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  46738. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  46739. var triangle = new DecimationTriangle([v0, v1, v2]);
  46740. triangle.originalOffset = pos;
  46741. _this.triangles.push(triangle);
  46742. };
  46743. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  46744. _this.init(callback);
  46745. });
  46746. });
  46747. };
  46748. QuadraticErrorSimplification.prototype.init = function (callback) {
  46749. var _this = this;
  46750. var triangleInit1 = function (i) {
  46751. var t = _this.triangles[i];
  46752. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  46753. for (var j = 0; j < 3; j++) {
  46754. 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))));
  46755. }
  46756. };
  46757. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  46758. var triangleInit2 = function (i) {
  46759. var t = _this.triangles[i];
  46760. for (var j = 0; j < 3; ++j) {
  46761. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  46762. }
  46763. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46764. };
  46765. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  46766. _this.initialized = true;
  46767. callback();
  46768. });
  46769. });
  46770. };
  46771. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  46772. var newTriangles = [];
  46773. var i;
  46774. for (i = 0; i < this.vertices.length; ++i) {
  46775. this.vertices[i].triangleCount = 0;
  46776. }
  46777. var t;
  46778. var j;
  46779. for (i = 0; i < this.triangles.length; ++i) {
  46780. if (!this.triangles[i].deleted) {
  46781. t = this.triangles[i];
  46782. for (j = 0; j < 3; ++j) {
  46783. t.vertices[j].triangleCount = 1;
  46784. }
  46785. newTriangles.push(t);
  46786. }
  46787. }
  46788. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  46789. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  46790. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  46791. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  46792. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46793. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46794. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46795. var vertexCount = 0;
  46796. for (i = 0; i < this.vertices.length; ++i) {
  46797. var vertex = this.vertices[i];
  46798. vertex.id = vertexCount;
  46799. if (vertex.triangleCount) {
  46800. vertex.originalOffsets.forEach(function (originalOffset) {
  46801. newPositionData.push(vertex.position.x);
  46802. newPositionData.push(vertex.position.y);
  46803. newPositionData.push(vertex.position.z);
  46804. newNormalData.push(normalData[originalOffset * 3]);
  46805. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  46806. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  46807. if (uvs && uvs.length) {
  46808. newUVsData.push(uvs[(originalOffset * 2)]);
  46809. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  46810. }
  46811. else if (colorsData && colorsData.length) {
  46812. newColorsData.push(colorsData[(originalOffset * 4)]);
  46813. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  46814. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  46815. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  46816. }
  46817. ++vertexCount;
  46818. });
  46819. }
  46820. }
  46821. var startingIndex = this._reconstructedMesh.getTotalIndices();
  46822. var startingVertex = this._reconstructedMesh.getTotalVertices();
  46823. var submeshesArray = this._reconstructedMesh.subMeshes;
  46824. this._reconstructedMesh.subMeshes = [];
  46825. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  46826. var originalIndices = this._mesh.getIndices();
  46827. for (i = 0; i < newTriangles.length; ++i) {
  46828. t = newTriangles[i]; //now get the new referencing point for each vertex
  46829. [0, 1, 2].forEach(function (idx) {
  46830. var id = originalIndices[t.originalOffset + idx];
  46831. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  46832. if (offset < 0)
  46833. offset = 0;
  46834. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  46835. });
  46836. }
  46837. //overwriting the old vertex buffers and indices.
  46838. this._reconstructedMesh.setIndices(newIndicesArray);
  46839. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  46840. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  46841. if (newUVsData.length > 0)
  46842. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  46843. if (newColorsData.length > 0)
  46844. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  46845. //create submesh
  46846. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  46847. if (submeshIndex > 0) {
  46848. this._reconstructedMesh.subMeshes = [];
  46849. submeshesArray.forEach(function (submesh) {
  46850. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  46851. });
  46852. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  46853. }
  46854. };
  46855. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  46856. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  46857. this._reconstructedMesh.material = this._mesh.material;
  46858. this._reconstructedMesh.parent = this._mesh.parent;
  46859. this._reconstructedMesh.isVisible = false;
  46860. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  46861. };
  46862. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  46863. for (var i = 0; i < vertex1.triangleCount; ++i) {
  46864. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  46865. if (t.deleted)
  46866. continue;
  46867. var s = this.references[vertex1.triangleStart + i].vertexId;
  46868. var v1 = t.vertices[(s + 1) % 3];
  46869. var v2 = t.vertices[(s + 2) % 3];
  46870. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  46871. deletedArray[i] = true;
  46872. delTr.push(t);
  46873. continue;
  46874. }
  46875. var d1 = v1.position.subtract(point);
  46876. d1 = d1.normalize();
  46877. var d2 = v2.position.subtract(point);
  46878. d2 = d2.normalize();
  46879. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  46880. return true;
  46881. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  46882. deletedArray[i] = false;
  46883. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  46884. return true;
  46885. }
  46886. return false;
  46887. };
  46888. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  46889. var newDeleted = deletedTriangles;
  46890. for (var i = 0; i < vertex.triangleCount; ++i) {
  46891. var ref = this.references[vertex.triangleStart + i];
  46892. var t = this.triangles[ref.triangleId];
  46893. if (t.deleted)
  46894. continue;
  46895. if (deletedArray[i] && t.deletePending) {
  46896. t.deleted = true;
  46897. newDeleted++;
  46898. continue;
  46899. }
  46900. t.vertices[ref.vertexId] = origVertex;
  46901. t.isDirty = true;
  46902. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  46903. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  46904. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  46905. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  46906. this.references.push(ref);
  46907. }
  46908. return newDeleted;
  46909. };
  46910. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  46911. for (var i = 0; i < this.vertices.length; ++i) {
  46912. var vCount = [];
  46913. var vId = [];
  46914. var v = this.vertices[i];
  46915. var j;
  46916. for (j = 0; j < v.triangleCount; ++j) {
  46917. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  46918. for (var ii = 0; ii < 3; ii++) {
  46919. var ofs = 0;
  46920. var vv = triangle.vertices[ii];
  46921. while (ofs < vCount.length) {
  46922. if (vId[ofs] === vv.id)
  46923. break;
  46924. ++ofs;
  46925. }
  46926. if (ofs === vCount.length) {
  46927. vCount.push(1);
  46928. vId.push(vv.id);
  46929. }
  46930. else {
  46931. vCount[ofs]++;
  46932. }
  46933. }
  46934. }
  46935. for (j = 0; j < vCount.length; ++j) {
  46936. if (vCount[j] === 1) {
  46937. this.vertices[vId[j]].isBorder = true;
  46938. }
  46939. else {
  46940. this.vertices[vId[j]].isBorder = false;
  46941. }
  46942. }
  46943. }
  46944. };
  46945. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  46946. if (identifyBorders === void 0) { identifyBorders = false; }
  46947. var i;
  46948. if (!identifyBorders) {
  46949. var newTrianglesVector = [];
  46950. for (i = 0; i < this.triangles.length; ++i) {
  46951. if (!this.triangles[i].deleted) {
  46952. newTrianglesVector.push(this.triangles[i]);
  46953. }
  46954. }
  46955. this.triangles = newTrianglesVector;
  46956. }
  46957. for (i = 0; i < this.vertices.length; ++i) {
  46958. this.vertices[i].triangleCount = 0;
  46959. this.vertices[i].triangleStart = 0;
  46960. }
  46961. var t;
  46962. var j;
  46963. var v;
  46964. for (i = 0; i < this.triangles.length; ++i) {
  46965. t = this.triangles[i];
  46966. for (j = 0; j < 3; ++j) {
  46967. v = t.vertices[j];
  46968. v.triangleCount++;
  46969. }
  46970. }
  46971. var tStart = 0;
  46972. for (i = 0; i < this.vertices.length; ++i) {
  46973. this.vertices[i].triangleStart = tStart;
  46974. tStart += this.vertices[i].triangleCount;
  46975. this.vertices[i].triangleCount = 0;
  46976. }
  46977. var newReferences = new Array(this.triangles.length * 3);
  46978. for (i = 0; i < this.triangles.length; ++i) {
  46979. t = this.triangles[i];
  46980. for (j = 0; j < 3; ++j) {
  46981. v = t.vertices[j];
  46982. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  46983. v.triangleCount++;
  46984. }
  46985. }
  46986. this.references = newReferences;
  46987. if (identifyBorders) {
  46988. this.identifyBorder();
  46989. }
  46990. };
  46991. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  46992. var x = point.x;
  46993. var y = point.y;
  46994. var z = point.z;
  46995. 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
  46996. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  46997. };
  46998. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  46999. var q = vertex1.q.add(vertex2.q);
  47000. var border = vertex1.isBorder && vertex2.isBorder;
  47001. var error = 0;
  47002. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  47003. if (qDet !== 0 && !border) {
  47004. if (!pointResult) {
  47005. pointResult = BABYLON.Vector3.Zero();
  47006. }
  47007. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  47008. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  47009. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  47010. error = this.vertexError(q, pointResult);
  47011. }
  47012. else {
  47013. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  47014. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  47015. var error1 = this.vertexError(q, vertex1.position);
  47016. var error2 = this.vertexError(q, vertex2.position);
  47017. var error3 = this.vertexError(q, p3);
  47018. error = Math.min(error1, error2, error3);
  47019. if (error === error1) {
  47020. if (pointResult) {
  47021. pointResult.copyFrom(vertex1.position);
  47022. }
  47023. }
  47024. else if (error === error2) {
  47025. if (pointResult) {
  47026. pointResult.copyFrom(vertex2.position);
  47027. }
  47028. }
  47029. else {
  47030. if (pointResult) {
  47031. pointResult.copyFrom(p3);
  47032. }
  47033. }
  47034. }
  47035. return error;
  47036. };
  47037. return QuadraticErrorSimplification;
  47038. }());
  47039. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  47040. })(BABYLON || (BABYLON = {}));
  47041. //# sourceMappingURL=babylon.meshSimplification.js.map
  47042. var BABYLON;
  47043. (function (BABYLON) {
  47044. var serializedGeometries = [];
  47045. var serializeGeometry = function (geometry, serializationGeometries) {
  47046. if (serializedGeometries[geometry.id]) {
  47047. return;
  47048. }
  47049. if (geometry.doNotSerialize) {
  47050. return;
  47051. }
  47052. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  47053. serializationGeometries.boxes.push(geometry.serialize());
  47054. }
  47055. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  47056. serializationGeometries.spheres.push(geometry.serialize());
  47057. }
  47058. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  47059. serializationGeometries.cylinders.push(geometry.serialize());
  47060. }
  47061. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  47062. serializationGeometries.toruses.push(geometry.serialize());
  47063. }
  47064. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  47065. serializationGeometries.grounds.push(geometry.serialize());
  47066. }
  47067. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  47068. serializationGeometries.planes.push(geometry.serialize());
  47069. }
  47070. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  47071. serializationGeometries.torusKnots.push(geometry.serialize());
  47072. }
  47073. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  47074. throw new Error("Unknown primitive type");
  47075. }
  47076. else {
  47077. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  47078. }
  47079. serializedGeometries[geometry.id] = true;
  47080. };
  47081. var serializeMesh = function (mesh, serializationScene) {
  47082. var serializationObject = {};
  47083. // Geometry
  47084. var geometry = mesh._geometry;
  47085. if (geometry) {
  47086. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  47087. // 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
  47088. serializeGeometry(geometry, serializationScene.geometries);
  47089. }
  47090. }
  47091. // Custom
  47092. if (mesh.serialize) {
  47093. mesh.serialize(serializationObject);
  47094. }
  47095. return serializationObject;
  47096. };
  47097. var finalizeSingleMesh = function (mesh, serializationObject) {
  47098. //only works if the mesh is already loaded
  47099. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47100. //serialize material
  47101. if (mesh.material) {
  47102. if (mesh.material instanceof BABYLON.StandardMaterial) {
  47103. serializationObject.materials = serializationObject.materials || [];
  47104. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  47105. serializationObject.materials.push(mesh.material.serialize());
  47106. }
  47107. }
  47108. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  47109. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  47110. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  47111. serializationObject.multiMaterials.push(mesh.material.serialize());
  47112. }
  47113. }
  47114. }
  47115. //serialize geometry
  47116. var geometry = mesh._geometry;
  47117. if (geometry) {
  47118. if (!serializationObject.geometries) {
  47119. serializationObject.geometries = {};
  47120. serializationObject.geometries.boxes = [];
  47121. serializationObject.geometries.spheres = [];
  47122. serializationObject.geometries.cylinders = [];
  47123. serializationObject.geometries.toruses = [];
  47124. serializationObject.geometries.grounds = [];
  47125. serializationObject.geometries.planes = [];
  47126. serializationObject.geometries.torusKnots = [];
  47127. serializationObject.geometries.vertexData = [];
  47128. }
  47129. serializeGeometry(geometry, serializationObject.geometries);
  47130. }
  47131. // Skeletons
  47132. if (mesh.skeleton) {
  47133. serializationObject.skeletons = serializationObject.skeletons || [];
  47134. serializationObject.skeletons.push(mesh.skeleton.serialize());
  47135. }
  47136. //serialize the actual mesh
  47137. serializationObject.meshes = serializationObject.meshes || [];
  47138. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47139. }
  47140. };
  47141. var SceneSerializer = (function () {
  47142. function SceneSerializer() {
  47143. }
  47144. SceneSerializer.ClearCache = function () {
  47145. serializedGeometries = [];
  47146. };
  47147. SceneSerializer.Serialize = function (scene) {
  47148. var serializationObject = {};
  47149. SceneSerializer.ClearCache();
  47150. // Scene
  47151. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  47152. serializationObject.autoClear = scene.autoClear;
  47153. serializationObject.clearColor = scene.clearColor.asArray();
  47154. serializationObject.ambientColor = scene.ambientColor.asArray();
  47155. serializationObject.gravity = scene.gravity.asArray();
  47156. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  47157. serializationObject.workerCollisions = scene.workerCollisions;
  47158. // Fog
  47159. if (scene.fogMode && scene.fogMode !== 0) {
  47160. serializationObject.fogMode = scene.fogMode;
  47161. serializationObject.fogColor = scene.fogColor.asArray();
  47162. serializationObject.fogStart = scene.fogStart;
  47163. serializationObject.fogEnd = scene.fogEnd;
  47164. serializationObject.fogDensity = scene.fogDensity;
  47165. }
  47166. //Physics
  47167. if (scene.isPhysicsEnabled()) {
  47168. serializationObject.physicsEnabled = true;
  47169. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  47170. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  47171. }
  47172. // Metadata
  47173. if (scene.metadata) {
  47174. serializationObject.metadata = scene.metadata;
  47175. }
  47176. // Lights
  47177. serializationObject.lights = [];
  47178. var index;
  47179. var light;
  47180. for (index = 0; index < scene.lights.length; index++) {
  47181. light = scene.lights[index];
  47182. if (!light.doNotSerialize) {
  47183. serializationObject.lights.push(light.serialize());
  47184. }
  47185. }
  47186. // Cameras
  47187. serializationObject.cameras = [];
  47188. for (index = 0; index < scene.cameras.length; index++) {
  47189. var camera = scene.cameras[index];
  47190. if (!camera.doNotSerialize) {
  47191. serializationObject.cameras.push(camera.serialize());
  47192. }
  47193. }
  47194. if (scene.activeCamera) {
  47195. serializationObject.activeCameraID = scene.activeCamera.id;
  47196. }
  47197. // Animations
  47198. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  47199. // Materials
  47200. serializationObject.materials = [];
  47201. serializationObject.multiMaterials = [];
  47202. var material;
  47203. for (index = 0; index < scene.materials.length; index++) {
  47204. material = scene.materials[index];
  47205. if (!material.doNotSerialize) {
  47206. serializationObject.materials.push(material.serialize());
  47207. }
  47208. }
  47209. // MultiMaterials
  47210. serializationObject.multiMaterials = [];
  47211. for (index = 0; index < scene.multiMaterials.length; index++) {
  47212. var multiMaterial = scene.multiMaterials[index];
  47213. serializationObject.multiMaterials.push(multiMaterial.serialize());
  47214. }
  47215. // Skeletons
  47216. serializationObject.skeletons = [];
  47217. for (index = 0; index < scene.skeletons.length; index++) {
  47218. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  47219. }
  47220. // Geometries
  47221. serializationObject.geometries = {};
  47222. serializationObject.geometries.boxes = [];
  47223. serializationObject.geometries.spheres = [];
  47224. serializationObject.geometries.cylinders = [];
  47225. serializationObject.geometries.toruses = [];
  47226. serializationObject.geometries.grounds = [];
  47227. serializationObject.geometries.planes = [];
  47228. serializationObject.geometries.torusKnots = [];
  47229. serializationObject.geometries.vertexData = [];
  47230. serializedGeometries = [];
  47231. var geometries = scene.getGeometries();
  47232. for (index = 0; index < geometries.length; index++) {
  47233. var geometry = geometries[index];
  47234. if (geometry.isReady()) {
  47235. serializeGeometry(geometry, serializationObject.geometries);
  47236. }
  47237. }
  47238. // Meshes
  47239. serializationObject.meshes = [];
  47240. for (index = 0; index < scene.meshes.length; index++) {
  47241. var abstractMesh = scene.meshes[index];
  47242. if (abstractMesh instanceof BABYLON.Mesh) {
  47243. var mesh = abstractMesh;
  47244. if (!mesh.doNotSerialize) {
  47245. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  47246. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  47247. }
  47248. }
  47249. }
  47250. }
  47251. // Particles Systems
  47252. serializationObject.particleSystems = [];
  47253. for (index = 0; index < scene.particleSystems.length; index++) {
  47254. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  47255. }
  47256. // Lens flares
  47257. serializationObject.lensFlareSystems = [];
  47258. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  47259. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  47260. }
  47261. // Shadows
  47262. serializationObject.shadowGenerators = [];
  47263. for (index = 0; index < scene.lights.length; index++) {
  47264. light = scene.lights[index];
  47265. var shadowGenerator = light.getShadowGenerator();
  47266. // Only support serialization for official generator so far.
  47267. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  47268. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  47269. }
  47270. }
  47271. // Action Manager
  47272. if (scene.actionManager) {
  47273. serializationObject.actions = scene.actionManager.serialize("scene");
  47274. }
  47275. // Audio
  47276. serializationObject.sounds = [];
  47277. for (index = 0; index < scene.soundTracks.length; index++) {
  47278. var soundtrack = scene.soundTracks[index];
  47279. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  47280. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  47281. }
  47282. }
  47283. return serializationObject;
  47284. };
  47285. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  47286. if (withParents === void 0) { withParents = false; }
  47287. if (withChildren === void 0) { withChildren = false; }
  47288. var serializationObject = {};
  47289. SceneSerializer.ClearCache();
  47290. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  47291. if (withParents || withChildren) {
  47292. //deliberate for loop! not for each, appended should be processed as well.
  47293. for (var i = 0; i < toSerialize.length; ++i) {
  47294. if (withChildren) {
  47295. toSerialize[i].getDescendants().forEach(function (node) {
  47296. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  47297. toSerialize.push(node);
  47298. }
  47299. });
  47300. }
  47301. //make sure the array doesn't contain the object already
  47302. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  47303. toSerialize.push(toSerialize[i].parent);
  47304. }
  47305. }
  47306. }
  47307. toSerialize.forEach(function (mesh) {
  47308. finalizeSingleMesh(mesh, serializationObject);
  47309. });
  47310. return serializationObject;
  47311. };
  47312. return SceneSerializer;
  47313. }());
  47314. BABYLON.SceneSerializer = SceneSerializer;
  47315. })(BABYLON || (BABYLON = {}));
  47316. //# sourceMappingURL=babylon.sceneSerializer.js.map
  47317. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  47318. // Huge respect for a such great lib.
  47319. // Earcut license:
  47320. // Copyright (c) 2016, Mapbox
  47321. //
  47322. // Permission to use, copy, modify, and/or distribute this software for any purpose
  47323. // with or without fee is hereby granted, provided that the above copyright notice
  47324. // and this permission notice appear in all copies.
  47325. //
  47326. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  47327. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  47328. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  47329. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  47330. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  47331. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  47332. // THIS SOFTWARE.
  47333. var Earcut;
  47334. (function (Earcut) {
  47335. /**
  47336. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  47337. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  47338. * @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).
  47339. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  47340. */
  47341. function earcut(data, holeIndices, dim) {
  47342. dim = dim || 2;
  47343. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  47344. if (!outerNode)
  47345. return triangles;
  47346. var minX, minY, maxX, maxY, x, y, size;
  47347. if (hasHoles)
  47348. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  47349. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  47350. if (data.length > 80 * dim) {
  47351. minX = maxX = data[0];
  47352. minY = maxY = data[1];
  47353. for (var i = dim; i < outerLen; i += dim) {
  47354. x = data[i];
  47355. y = data[i + 1];
  47356. if (x < minX)
  47357. minX = x;
  47358. if (y < minY)
  47359. minY = y;
  47360. if (x > maxX)
  47361. maxX = x;
  47362. if (y > maxY)
  47363. maxY = y;
  47364. }
  47365. // minX, minY and size are later used to transform coords into integers for z-order calculation
  47366. size = Math.max(maxX - minX, maxY - minY);
  47367. }
  47368. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  47369. return triangles;
  47370. }
  47371. Earcut.earcut = earcut;
  47372. // create a circular doubly linked list from polygon points in the specified winding order
  47373. function linkedList(data, start, end, dim, clockwise) {
  47374. var i, last;
  47375. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  47376. for (i = start; i < end; i += dim)
  47377. last = insertNode(i, data[i], data[i + 1], last);
  47378. }
  47379. else {
  47380. for (i = end - dim; i >= start; i -= dim)
  47381. last = insertNode(i, data[i], data[i + 1], last);
  47382. }
  47383. if (last && equals(last, last.next)) {
  47384. removeNode(last);
  47385. last = last.next;
  47386. }
  47387. return last;
  47388. }
  47389. // eliminate colinear or duplicate points
  47390. function filterPoints(start, end) {
  47391. if (!start)
  47392. return start;
  47393. if (!end)
  47394. end = start;
  47395. var p = start, again;
  47396. do {
  47397. again = false;
  47398. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  47399. removeNode(p);
  47400. p = end = p.prev;
  47401. if (p === p.next)
  47402. return null;
  47403. again = true;
  47404. }
  47405. else {
  47406. p = p.next;
  47407. }
  47408. } while (again || p !== end);
  47409. return end;
  47410. }
  47411. // main ear slicing loop which triangulates a polygon (given as a linked list)
  47412. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  47413. if (!ear)
  47414. return;
  47415. // interlink polygon nodes in z-order
  47416. if (!pass && size)
  47417. indexCurve(ear, minX, minY, size);
  47418. var stop = ear, prev, next;
  47419. // iterate through ears, slicing them one by one
  47420. while (ear.prev !== ear.next) {
  47421. prev = ear.prev;
  47422. next = ear.next;
  47423. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  47424. // cut off the triangle
  47425. triangles.push(prev.i / dim);
  47426. triangles.push(ear.i / dim);
  47427. triangles.push(next.i / dim);
  47428. removeNode(ear);
  47429. // skipping the next vertice leads to less sliver triangles
  47430. ear = next.next;
  47431. stop = next.next;
  47432. continue;
  47433. }
  47434. ear = next;
  47435. // if we looped through the whole remaining polygon and can't find any more ears
  47436. if (ear === stop) {
  47437. // try filtering points and slicing again
  47438. if (!pass) {
  47439. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  47440. // if this didn't work, try curing all small self-intersections locally
  47441. }
  47442. else if (pass === 1) {
  47443. ear = cureLocalIntersections(ear, triangles, dim);
  47444. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  47445. // as a last resort, try splitting the remaining polygon into two
  47446. }
  47447. else if (pass === 2) {
  47448. splitEarcut(ear, triangles, dim, minX, minY, size);
  47449. }
  47450. break;
  47451. }
  47452. }
  47453. }
  47454. // check whether a polygon node forms a valid ear with adjacent nodes
  47455. function isEar(ear) {
  47456. var a = ear.prev, b = ear, c = ear.next;
  47457. if (area(a, b, c) >= 0)
  47458. return false; // reflex, can't be an ear
  47459. // now make sure we don't have other points inside the potential ear
  47460. var p = ear.next.next;
  47461. while (p !== ear.prev) {
  47462. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47463. area(p.prev, p, p.next) >= 0)
  47464. return false;
  47465. p = p.next;
  47466. }
  47467. return true;
  47468. }
  47469. function isEarHashed(ear, minX, minY, size) {
  47470. var a = ear.prev, b = ear, c = ear.next;
  47471. if (area(a, b, c) >= 0)
  47472. return false; // reflex, can't be an ear
  47473. // triangle bbox; min & max are calculated like this for speed
  47474. 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);
  47475. // z-order range for the current triangle bbox;
  47476. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  47477. // first look for points inside the triangle in increasing z-order
  47478. var p = ear.nextZ;
  47479. while (p && p.z <= maxZ) {
  47480. if (p !== ear.prev &&
  47481. p !== ear.next &&
  47482. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47483. area(p.prev, p, p.next) >= 0)
  47484. return false;
  47485. p = p.nextZ;
  47486. }
  47487. // then look for points in decreasing z-order
  47488. p = ear.prevZ;
  47489. while (p && p.z >= minZ) {
  47490. if (p !== ear.prev &&
  47491. p !== ear.next &&
  47492. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  47493. area(p.prev, p, p.next) >= 0)
  47494. return false;
  47495. p = p.prevZ;
  47496. }
  47497. return true;
  47498. }
  47499. // go through all polygon nodes and cure small local self-intersections
  47500. function cureLocalIntersections(start, triangles, dim) {
  47501. var p = start;
  47502. do {
  47503. var a = p.prev, b = p.next.next;
  47504. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  47505. triangles.push(a.i / dim);
  47506. triangles.push(p.i / dim);
  47507. triangles.push(b.i / dim);
  47508. // remove two nodes involved
  47509. removeNode(p);
  47510. removeNode(p.next);
  47511. p = start = b;
  47512. }
  47513. p = p.next;
  47514. } while (p !== start);
  47515. return p;
  47516. }
  47517. // try splitting polygon into two and triangulate them independently
  47518. function splitEarcut(start, triangles, dim, minX, minY, size) {
  47519. // look for a valid diagonal that divides the polygon into two
  47520. var a = start;
  47521. do {
  47522. var b = a.next.next;
  47523. while (b !== a.prev) {
  47524. if (a.i !== b.i && isValidDiagonal(a, b)) {
  47525. // split the polygon in two by the diagonal
  47526. var c = splitPolygon(a, b);
  47527. // filter colinear points around the cuts
  47528. a = filterPoints(a, a.next);
  47529. c = filterPoints(c, c.next);
  47530. // run earcut on each half
  47531. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  47532. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  47533. return;
  47534. }
  47535. b = b.next;
  47536. }
  47537. a = a.next;
  47538. } while (a !== start);
  47539. }
  47540. // link every hole into the outer loop, producing a single-ring polygon without holes
  47541. function eliminateHoles(data, holeIndices, outerNode, dim) {
  47542. var queue = [], i, len, start, end, list;
  47543. for (i = 0, len = holeIndices.length; i < len; i++) {
  47544. start = holeIndices[i] * dim;
  47545. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47546. list = linkedList(data, start, end, dim, false);
  47547. if (list === list.next)
  47548. list.steiner = true;
  47549. queue.push(getLeftmost(list));
  47550. }
  47551. queue.sort(compareX);
  47552. // process holes from left to right
  47553. for (i = 0; i < queue.length; i++) {
  47554. eliminateHole(queue[i], outerNode);
  47555. outerNode = filterPoints(outerNode, outerNode.next);
  47556. }
  47557. return outerNode;
  47558. }
  47559. function compareX(a, b) {
  47560. return a.x - b.x;
  47561. }
  47562. // find a bridge between vertices that connects hole with an outer ring and and link it
  47563. function eliminateHole(hole, outerNode) {
  47564. outerNode = findHoleBridge(hole, outerNode);
  47565. if (outerNode) {
  47566. var b = splitPolygon(outerNode, hole);
  47567. filterPoints(b, b.next);
  47568. }
  47569. }
  47570. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  47571. function findHoleBridge(hole, outerNode) {
  47572. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  47573. // find a segment intersected by a ray from the hole's leftmost point to the left;
  47574. // segment's endpoint with lesser x will be potential connection point
  47575. do {
  47576. if (hy <= p.y && hy >= p.next.y) {
  47577. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  47578. if (x <= hx && x > qx) {
  47579. qx = x;
  47580. if (x === hx) {
  47581. if (hy === p.y)
  47582. return p;
  47583. if (hy === p.next.y)
  47584. return p.next;
  47585. }
  47586. m = p.x < p.next.x ? p : p.next;
  47587. }
  47588. }
  47589. p = p.next;
  47590. } while (p !== outerNode);
  47591. if (!m)
  47592. return null;
  47593. if (hx === qx)
  47594. return m.prev; // hole touches outer segment; pick lower endpoint
  47595. // look for points inside the triangle of hole point, segment intersection and endpoint;
  47596. // if there are no points found, we have a valid connection;
  47597. // otherwise choose the point of the minimum angle with the ray as connection point
  47598. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  47599. p = m.next;
  47600. while (p !== stop) {
  47601. if (hx >= p.x &&
  47602. p.x >= mx &&
  47603. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  47604. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  47605. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  47606. m = p;
  47607. tanMin = tan;
  47608. }
  47609. }
  47610. p = p.next;
  47611. }
  47612. return m;
  47613. }
  47614. // interlink polygon nodes in z-order
  47615. function indexCurve(start, minX, minY, size) {
  47616. var p = start;
  47617. do {
  47618. if (p.z === null)
  47619. p.z = zOrder(p.x, p.y, minX, minY, size);
  47620. p.prevZ = p.prev;
  47621. p.nextZ = p.next;
  47622. p = p.next;
  47623. } while (p !== start);
  47624. p.prevZ.nextZ = null;
  47625. p.prevZ = null;
  47626. sortLinked(p);
  47627. }
  47628. // Simon Tatham's linked list merge sort algorithm
  47629. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  47630. function sortLinked(list) {
  47631. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  47632. do {
  47633. p = list;
  47634. list = null;
  47635. tail = null;
  47636. numMerges = 0;
  47637. while (p) {
  47638. numMerges++;
  47639. q = p;
  47640. pSize = 0;
  47641. for (i = 0; i < inSize; i++) {
  47642. pSize++;
  47643. q = q.nextZ;
  47644. if (!q)
  47645. break;
  47646. }
  47647. qSize = inSize;
  47648. while (pSize > 0 || (qSize > 0 && q)) {
  47649. if (pSize === 0) {
  47650. e = q;
  47651. q = q.nextZ;
  47652. qSize--;
  47653. }
  47654. else if (qSize === 0 || !q) {
  47655. e = p;
  47656. p = p.nextZ;
  47657. pSize--;
  47658. }
  47659. else if (p.z <= q.z) {
  47660. e = p;
  47661. p = p.nextZ;
  47662. pSize--;
  47663. }
  47664. else {
  47665. e = q;
  47666. q = q.nextZ;
  47667. qSize--;
  47668. }
  47669. if (tail)
  47670. tail.nextZ = e;
  47671. else
  47672. list = e;
  47673. e.prevZ = tail;
  47674. tail = e;
  47675. }
  47676. p = q;
  47677. }
  47678. tail.nextZ = null;
  47679. inSize *= 2;
  47680. } while (numMerges > 1);
  47681. return list;
  47682. }
  47683. // z-order of a point given coords and size of the data bounding box
  47684. function zOrder(x, y, minX, minY, size) {
  47685. // coords are transformed into non-negative 15-bit integer range
  47686. x = 32767 * (x - minX) / size;
  47687. y = 32767 * (y - minY) / size;
  47688. x = (x | (x << 8)) & 0x00FF00FF;
  47689. x = (x | (x << 4)) & 0x0F0F0F0F;
  47690. x = (x | (x << 2)) & 0x33333333;
  47691. x = (x | (x << 1)) & 0x55555555;
  47692. y = (y | (y << 8)) & 0x00FF00FF;
  47693. y = (y | (y << 4)) & 0x0F0F0F0F;
  47694. y = (y | (y << 2)) & 0x33333333;
  47695. y = (y | (y << 1)) & 0x55555555;
  47696. return x | (y << 1);
  47697. }
  47698. // find the leftmost node of a polygon ring
  47699. function getLeftmost(start) {
  47700. var p = start, leftmost = start;
  47701. do {
  47702. if (p.x < leftmost.x)
  47703. leftmost = p;
  47704. p = p.next;
  47705. } while (p !== start);
  47706. return leftmost;
  47707. }
  47708. // check if a point lies within a convex triangle
  47709. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  47710. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  47711. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  47712. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  47713. }
  47714. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  47715. function isValidDiagonal(a, b) {
  47716. return a.next.i !== b.i &&
  47717. a.prev.i !== b.i &&
  47718. !intersectsPolygon(a, b) &&
  47719. locallyInside(a, b) &&
  47720. locallyInside(b, a) &&
  47721. middleInside(a, b);
  47722. }
  47723. // signed area of a triangle
  47724. function area(p, q, r) {
  47725. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  47726. }
  47727. // check if two points are equal
  47728. function equals(p1, p2) {
  47729. return p1.x === p2.x && p1.y === p2.y;
  47730. }
  47731. // check if two segments intersect
  47732. function intersects(p1, q1, p2, q2) {
  47733. if ((equals(p1, q1) && equals(p2, q2)) ||
  47734. (equals(p1, q2) && equals(p2, q1)))
  47735. return true;
  47736. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  47737. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  47738. }
  47739. // check if a polygon diagonal intersects any polygon segments
  47740. function intersectsPolygon(a, b) {
  47741. var p = a;
  47742. do {
  47743. if (p.i !== a.i &&
  47744. p.next.i !== a.i &&
  47745. p.i !== b.i &&
  47746. p.next.i !== b.i &&
  47747. intersects(p, p.next, a, b))
  47748. return true;
  47749. p = p.next;
  47750. } while (p !== a);
  47751. return false;
  47752. }
  47753. // check if a polygon diagonal is locally inside the polygon
  47754. function locallyInside(a, b) {
  47755. return area(a.prev, a, a.next) < 0
  47756. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  47757. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  47758. }
  47759. // check if the middle point of a polygon diagonal is inside the polygon
  47760. function middleInside(a, b) {
  47761. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  47762. do {
  47763. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  47764. inside = !inside;
  47765. p = p.next;
  47766. } while (p !== a);
  47767. return inside;
  47768. }
  47769. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  47770. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  47771. function splitPolygon(a, b) {
  47772. 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;
  47773. a.next = b;
  47774. b.prev = a;
  47775. a2.next = an;
  47776. an.prev = a2;
  47777. b2.next = a2;
  47778. a2.prev = b2;
  47779. bp.next = b2;
  47780. b2.prev = bp;
  47781. return b2;
  47782. }
  47783. // create a node and optionally link it with previous one (in a circular doubly linked list)
  47784. function insertNode(i, x, y, last) {
  47785. var p = new Node(i, x, y);
  47786. if (!last) {
  47787. p.prev = p;
  47788. p.next = p;
  47789. }
  47790. else {
  47791. p.next = last.next;
  47792. p.prev = last;
  47793. last.next.prev = p;
  47794. last.next = p;
  47795. }
  47796. return p;
  47797. }
  47798. function removeNode(p) {
  47799. p.next.prev = p.prev;
  47800. p.prev.next = p.next;
  47801. if (p.prevZ)
  47802. p.prevZ.nextZ = p.nextZ;
  47803. if (p.nextZ)
  47804. p.nextZ.prevZ = p.prevZ;
  47805. }
  47806. function Node(i, x, y) {
  47807. // vertice index in coordinates array
  47808. this.i = i;
  47809. // vertex coordinates
  47810. this.x = x;
  47811. this.y = y;
  47812. // previous and next vertice nodes in a polygon ring
  47813. this.prev = null;
  47814. this.next = null;
  47815. // z-order curve value
  47816. this.z = null;
  47817. // previous and next nodes in z-order
  47818. this.prevZ = null;
  47819. this.nextZ = null;
  47820. // indicates whether this is a steiner point
  47821. this.steiner = false;
  47822. }
  47823. /**
  47824. * return a percentage difference between the polygon area and its triangulation area;
  47825. * used to verify correctness of triangulation
  47826. */
  47827. function deviation(data, holeIndices, dim, triangles) {
  47828. var hasHoles = holeIndices && holeIndices.length;
  47829. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  47830. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  47831. if (hasHoles) {
  47832. for (var i = 0, len = holeIndices.length; i < len; i++) {
  47833. var start = holeIndices[i] * dim;
  47834. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  47835. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  47836. }
  47837. }
  47838. var trianglesArea = 0;
  47839. for (i = 0; i < triangles.length; i += 3) {
  47840. var a = triangles[i] * dim;
  47841. var b = triangles[i + 1] * dim;
  47842. var c = triangles[i + 2] * dim;
  47843. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  47844. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  47845. }
  47846. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  47847. }
  47848. Earcut.deviation = deviation;
  47849. ;
  47850. function signedArea(data, start, end, dim) {
  47851. var sum = 0;
  47852. for (var i = start, j = end - dim; i < end; i += dim) {
  47853. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  47854. j = i;
  47855. }
  47856. return sum;
  47857. }
  47858. /**
  47859. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  47860. */
  47861. function flatten(data) {
  47862. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  47863. for (var i = 0; i < data.length; i++) {
  47864. for (var j = 0; j < data[i].length; j++) {
  47865. for (var d = 0; d < dim; d++)
  47866. result.vertices.push(data[i][j][d]);
  47867. }
  47868. if (i > 0) {
  47869. holeIndex += data[i - 1].length;
  47870. result.holes.push(holeIndex);
  47871. }
  47872. }
  47873. return result;
  47874. }
  47875. Earcut.flatten = flatten;
  47876. ;
  47877. })(Earcut || (Earcut = {}));
  47878. //# sourceMappingURL=babylon.earcut.js.map
  47879. var BABYLON;
  47880. (function (BABYLON) {
  47881. // Unique ID when we import meshes from Babylon to CSG
  47882. var currentCSGMeshId = 0;
  47883. // # class Vertex
  47884. // Represents a vertex of a polygon. Use your own vertex class instead of this
  47885. // one to provide additional features like texture coordinates and vertex
  47886. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  47887. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  47888. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  47889. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  47890. // is not used anywhere else.
  47891. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  47892. var Vertex = (function () {
  47893. function Vertex(pos, normal, uv) {
  47894. this.pos = pos;
  47895. this.normal = normal;
  47896. this.uv = uv;
  47897. }
  47898. Vertex.prototype.clone = function () {
  47899. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  47900. };
  47901. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  47902. // orientation of a polygon is flipped.
  47903. Vertex.prototype.flip = function () {
  47904. this.normal = this.normal.scale(-1);
  47905. };
  47906. // Create a new vertex between this vertex and `other` by linearly
  47907. // interpolating all properties using a parameter of `t`. Subclasses should
  47908. // override this to interpolate additional properties.
  47909. Vertex.prototype.interpolate = function (other, t) {
  47910. 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));
  47911. };
  47912. return Vertex;
  47913. }());
  47914. // # class Plane
  47915. // Represents a plane in 3D space.
  47916. var Plane = (function () {
  47917. function Plane(normal, w) {
  47918. this.normal = normal;
  47919. this.w = w;
  47920. }
  47921. Plane.FromPoints = function (a, b, c) {
  47922. var v0 = c.subtract(a);
  47923. var v1 = b.subtract(a);
  47924. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  47925. return null;
  47926. }
  47927. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  47928. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  47929. };
  47930. Plane.prototype.clone = function () {
  47931. return new Plane(this.normal.clone(), this.w);
  47932. };
  47933. Plane.prototype.flip = function () {
  47934. this.normal.scaleInPlace(-1);
  47935. this.w = -this.w;
  47936. };
  47937. // Split `polygon` by this plane if needed, then put the polygon or polygon
  47938. // fragments in the appropriate lists. Coplanar polygons go into either
  47939. // `coplanarFront` or `coplanarBack` depending on their orientation with
  47940. // respect to this plane. Polygons in front or in back of this plane go into
  47941. // either `front` or `back`.
  47942. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  47943. var COPLANAR = 0;
  47944. var FRONT = 1;
  47945. var BACK = 2;
  47946. var SPANNING = 3;
  47947. // Classify each point as well as the entire polygon into one of the above
  47948. // four classes.
  47949. var polygonType = 0;
  47950. var types = [];
  47951. var i;
  47952. var t;
  47953. for (i = 0; i < polygon.vertices.length; i++) {
  47954. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  47955. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  47956. polygonType |= type;
  47957. types.push(type);
  47958. }
  47959. // Put the polygon in the correct list, splitting it when necessary.
  47960. switch (polygonType) {
  47961. case COPLANAR:
  47962. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  47963. break;
  47964. case FRONT:
  47965. front.push(polygon);
  47966. break;
  47967. case BACK:
  47968. back.push(polygon);
  47969. break;
  47970. case SPANNING:
  47971. var f = [], b = [];
  47972. for (i = 0; i < polygon.vertices.length; i++) {
  47973. var j = (i + 1) % polygon.vertices.length;
  47974. var ti = types[i], tj = types[j];
  47975. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  47976. if (ti !== BACK)
  47977. f.push(vi);
  47978. if (ti !== FRONT)
  47979. b.push(ti !== BACK ? vi.clone() : vi);
  47980. if ((ti | tj) === SPANNING) {
  47981. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  47982. var v = vi.interpolate(vj, t);
  47983. f.push(v);
  47984. b.push(v.clone());
  47985. }
  47986. }
  47987. var poly;
  47988. if (f.length >= 3) {
  47989. poly = new Polygon(f, polygon.shared);
  47990. if (poly.plane)
  47991. front.push(poly);
  47992. }
  47993. if (b.length >= 3) {
  47994. poly = new Polygon(b, polygon.shared);
  47995. if (poly.plane)
  47996. back.push(poly);
  47997. }
  47998. break;
  47999. }
  48000. };
  48001. return Plane;
  48002. }());
  48003. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  48004. // point is on the plane.
  48005. Plane.EPSILON = 1e-5;
  48006. // # class Polygon
  48007. // Represents a convex polygon. The vertices used to initialize a polygon must
  48008. // be coplanar and form a convex loop.
  48009. //
  48010. // Each convex polygon has a `shared` property, which is shared between all
  48011. // polygons that are clones of each other or were split from the same polygon.
  48012. // This can be used to define per-polygon properties (such as surface color).
  48013. var Polygon = (function () {
  48014. function Polygon(vertices, shared) {
  48015. this.vertices = vertices;
  48016. this.shared = shared;
  48017. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  48018. }
  48019. Polygon.prototype.clone = function () {
  48020. var vertices = this.vertices.map(function (v) { return v.clone(); });
  48021. return new Polygon(vertices, this.shared);
  48022. };
  48023. Polygon.prototype.flip = function () {
  48024. this.vertices.reverse().map(function (v) { v.flip(); });
  48025. this.plane.flip();
  48026. };
  48027. return Polygon;
  48028. }());
  48029. // # class Node
  48030. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  48031. // by picking a polygon to split along. That polygon (and all other coplanar
  48032. // polygons) are added directly to that node and the other polygons are added to
  48033. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  48034. // no distinction between internal and leaf nodes.
  48035. var Node = (function () {
  48036. function Node(polygons) {
  48037. this.plane = null;
  48038. this.front = null;
  48039. this.back = null;
  48040. this.polygons = [];
  48041. if (polygons) {
  48042. this.build(polygons);
  48043. }
  48044. }
  48045. Node.prototype.clone = function () {
  48046. var node = new Node();
  48047. node.plane = this.plane && this.plane.clone();
  48048. node.front = this.front && this.front.clone();
  48049. node.back = this.back && this.back.clone();
  48050. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  48051. return node;
  48052. };
  48053. // Convert solid space to empty space and empty space to solid space.
  48054. Node.prototype.invert = function () {
  48055. for (var i = 0; i < this.polygons.length; i++) {
  48056. this.polygons[i].flip();
  48057. }
  48058. if (this.plane) {
  48059. this.plane.flip();
  48060. }
  48061. if (this.front) {
  48062. this.front.invert();
  48063. }
  48064. if (this.back) {
  48065. this.back.invert();
  48066. }
  48067. var temp = this.front;
  48068. this.front = this.back;
  48069. this.back = temp;
  48070. };
  48071. // Recursively remove all polygons in `polygons` that are inside this BSP
  48072. // tree.
  48073. Node.prototype.clipPolygons = function (polygons) {
  48074. if (!this.plane)
  48075. return polygons.slice();
  48076. var front = [], back = [];
  48077. for (var i = 0; i < polygons.length; i++) {
  48078. this.plane.splitPolygon(polygons[i], front, back, front, back);
  48079. }
  48080. if (this.front) {
  48081. front = this.front.clipPolygons(front);
  48082. }
  48083. if (this.back) {
  48084. back = this.back.clipPolygons(back);
  48085. }
  48086. else {
  48087. back = [];
  48088. }
  48089. return front.concat(back);
  48090. };
  48091. // Remove all polygons in this BSP tree that are inside the other BSP tree
  48092. // `bsp`.
  48093. Node.prototype.clipTo = function (bsp) {
  48094. this.polygons = bsp.clipPolygons(this.polygons);
  48095. if (this.front)
  48096. this.front.clipTo(bsp);
  48097. if (this.back)
  48098. this.back.clipTo(bsp);
  48099. };
  48100. // Return a list of all polygons in this BSP tree.
  48101. Node.prototype.allPolygons = function () {
  48102. var polygons = this.polygons.slice();
  48103. if (this.front)
  48104. polygons = polygons.concat(this.front.allPolygons());
  48105. if (this.back)
  48106. polygons = polygons.concat(this.back.allPolygons());
  48107. return polygons;
  48108. };
  48109. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  48110. // new polygons are filtered down to the bottom of the tree and become new
  48111. // nodes there. Each set of polygons is partitioned using the first polygon
  48112. // (no heuristic is used to pick a good split).
  48113. Node.prototype.build = function (polygons) {
  48114. if (!polygons.length)
  48115. return;
  48116. if (!this.plane)
  48117. this.plane = polygons[0].plane.clone();
  48118. var front = [], back = [];
  48119. for (var i = 0; i < polygons.length; i++) {
  48120. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  48121. }
  48122. if (front.length) {
  48123. if (!this.front)
  48124. this.front = new Node();
  48125. this.front.build(front);
  48126. }
  48127. if (back.length) {
  48128. if (!this.back)
  48129. this.back = new Node();
  48130. this.back.build(back);
  48131. }
  48132. };
  48133. return Node;
  48134. }());
  48135. var CSG = (function () {
  48136. function CSG() {
  48137. this.polygons = new Array();
  48138. }
  48139. // Convert BABYLON.Mesh to BABYLON.CSG
  48140. CSG.FromMesh = function (mesh) {
  48141. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  48142. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  48143. if (mesh instanceof BABYLON.Mesh) {
  48144. mesh.computeWorldMatrix(true);
  48145. matrix = mesh.getWorldMatrix();
  48146. meshPosition = mesh.position.clone();
  48147. meshRotation = mesh.rotation.clone();
  48148. if (mesh.rotationQuaternion) {
  48149. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  48150. }
  48151. meshScaling = mesh.scaling.clone();
  48152. }
  48153. else {
  48154. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  48155. }
  48156. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48157. var subMeshes = mesh.subMeshes;
  48158. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  48159. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  48160. vertices = [];
  48161. for (var j = 0; j < 3; j++) {
  48162. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  48163. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  48164. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  48165. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  48166. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  48167. vertex = new Vertex(position, normal, uv);
  48168. vertices.push(vertex);
  48169. }
  48170. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  48171. // To handle the case of degenerated triangle
  48172. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  48173. if (polygon.plane)
  48174. polygons.push(polygon);
  48175. }
  48176. }
  48177. var csg = CSG.FromPolygons(polygons);
  48178. csg.matrix = matrix;
  48179. csg.position = meshPosition;
  48180. csg.rotation = meshRotation;
  48181. csg.scaling = meshScaling;
  48182. csg.rotationQuaternion = meshRotationQuaternion;
  48183. currentCSGMeshId++;
  48184. return csg;
  48185. };
  48186. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  48187. CSG.FromPolygons = function (polygons) {
  48188. var csg = new CSG();
  48189. csg.polygons = polygons;
  48190. return csg;
  48191. };
  48192. CSG.prototype.clone = function () {
  48193. var csg = new CSG();
  48194. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  48195. csg.copyTransformAttributes(this);
  48196. return csg;
  48197. };
  48198. CSG.prototype.toPolygons = function () {
  48199. return this.polygons;
  48200. };
  48201. CSG.prototype.union = function (csg) {
  48202. var a = new Node(this.clone().polygons);
  48203. var b = new Node(csg.clone().polygons);
  48204. a.clipTo(b);
  48205. b.clipTo(a);
  48206. b.invert();
  48207. b.clipTo(a);
  48208. b.invert();
  48209. a.build(b.allPolygons());
  48210. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48211. };
  48212. CSG.prototype.unionInPlace = function (csg) {
  48213. var a = new Node(this.polygons);
  48214. var b = new Node(csg.polygons);
  48215. a.clipTo(b);
  48216. b.clipTo(a);
  48217. b.invert();
  48218. b.clipTo(a);
  48219. b.invert();
  48220. a.build(b.allPolygons());
  48221. this.polygons = a.allPolygons();
  48222. };
  48223. CSG.prototype.subtract = function (csg) {
  48224. var a = new Node(this.clone().polygons);
  48225. var b = new Node(csg.clone().polygons);
  48226. a.invert();
  48227. a.clipTo(b);
  48228. b.clipTo(a);
  48229. b.invert();
  48230. b.clipTo(a);
  48231. b.invert();
  48232. a.build(b.allPolygons());
  48233. a.invert();
  48234. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48235. };
  48236. CSG.prototype.subtractInPlace = function (csg) {
  48237. var a = new Node(this.polygons);
  48238. var b = new Node(csg.polygons);
  48239. a.invert();
  48240. a.clipTo(b);
  48241. b.clipTo(a);
  48242. b.invert();
  48243. b.clipTo(a);
  48244. b.invert();
  48245. a.build(b.allPolygons());
  48246. a.invert();
  48247. this.polygons = a.allPolygons();
  48248. };
  48249. CSG.prototype.intersect = function (csg) {
  48250. var a = new Node(this.clone().polygons);
  48251. var b = new Node(csg.clone().polygons);
  48252. a.invert();
  48253. b.clipTo(a);
  48254. b.invert();
  48255. a.clipTo(b);
  48256. b.clipTo(a);
  48257. a.build(b.allPolygons());
  48258. a.invert();
  48259. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  48260. };
  48261. CSG.prototype.intersectInPlace = function (csg) {
  48262. var a = new Node(this.polygons);
  48263. var b = new Node(csg.polygons);
  48264. a.invert();
  48265. b.clipTo(a);
  48266. b.invert();
  48267. a.clipTo(b);
  48268. b.clipTo(a);
  48269. a.build(b.allPolygons());
  48270. a.invert();
  48271. this.polygons = a.allPolygons();
  48272. };
  48273. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  48274. // not modified.
  48275. CSG.prototype.inverse = function () {
  48276. var csg = this.clone();
  48277. csg.inverseInPlace();
  48278. return csg;
  48279. };
  48280. CSG.prototype.inverseInPlace = function () {
  48281. this.polygons.map(function (p) { p.flip(); });
  48282. };
  48283. // This is used to keep meshes transformations so they can be restored
  48284. // when we build back a Babylon Mesh
  48285. // NB : All CSG operations are performed in world coordinates
  48286. CSG.prototype.copyTransformAttributes = function (csg) {
  48287. this.matrix = csg.matrix;
  48288. this.position = csg.position;
  48289. this.rotation = csg.rotation;
  48290. this.scaling = csg.scaling;
  48291. this.rotationQuaternion = csg.rotationQuaternion;
  48292. return this;
  48293. };
  48294. // Build Raw mesh from CSG
  48295. // Coordinates here are in world space
  48296. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  48297. var matrix = this.matrix.clone();
  48298. matrix.invert();
  48299. 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;
  48300. if (keepSubMeshes) {
  48301. // Sort Polygons, since subMeshes are indices range
  48302. polygons.sort(function (a, b) {
  48303. if (a.shared.meshId === b.shared.meshId) {
  48304. return a.shared.subMeshId - b.shared.subMeshId;
  48305. }
  48306. else {
  48307. return a.shared.meshId - b.shared.meshId;
  48308. }
  48309. });
  48310. }
  48311. for (var i = 0, il = polygons.length; i < il; i++) {
  48312. polygon = polygons[i];
  48313. // Building SubMeshes
  48314. if (!subMesh_dict[polygon.shared.meshId]) {
  48315. subMesh_dict[polygon.shared.meshId] = {};
  48316. }
  48317. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  48318. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  48319. indexStart: +Infinity,
  48320. indexEnd: -Infinity,
  48321. materialIndex: polygon.shared.materialIndex
  48322. };
  48323. }
  48324. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  48325. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  48326. polygonIndices[0] = 0;
  48327. polygonIndices[1] = j - 1;
  48328. polygonIndices[2] = j;
  48329. for (var k = 0; k < 3; k++) {
  48330. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  48331. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  48332. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  48333. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  48334. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  48335. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  48336. // Check if 2 points can be merged
  48337. if (!(typeof vertex_idx !== 'undefined' &&
  48338. normals[vertex_idx * 3] === localNormal.x &&
  48339. normals[vertex_idx * 3 + 1] === localNormal.y &&
  48340. normals[vertex_idx * 3 + 2] === localNormal.z &&
  48341. uvs[vertex_idx * 2] === uv.x &&
  48342. uvs[vertex_idx * 2 + 1] === uv.y)) {
  48343. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  48344. uvs.push(uv.x, uv.y);
  48345. normals.push(normal.x, normal.y, normal.z);
  48346. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  48347. }
  48348. indices.push(vertex_idx);
  48349. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  48350. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  48351. currentIndex++;
  48352. }
  48353. }
  48354. }
  48355. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  48356. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  48357. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  48358. mesh.setIndices(indices);
  48359. if (keepSubMeshes) {
  48360. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  48361. var materialIndexOffset = 0, materialMaxIndex;
  48362. mesh.subMeshes = new Array();
  48363. for (var m in subMesh_dict) {
  48364. materialMaxIndex = -1;
  48365. for (var sm in subMesh_dict[m]) {
  48366. subMesh_obj = subMesh_dict[m][sm];
  48367. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  48368. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  48369. }
  48370. materialIndexOffset += ++materialMaxIndex;
  48371. }
  48372. }
  48373. return mesh;
  48374. };
  48375. // Build Mesh from CSG taking material and transforms into account
  48376. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  48377. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  48378. mesh.material = material;
  48379. mesh.position.copyFrom(this.position);
  48380. mesh.rotation.copyFrom(this.rotation);
  48381. if (this.rotationQuaternion) {
  48382. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  48383. }
  48384. mesh.scaling.copyFrom(this.scaling);
  48385. mesh.computeWorldMatrix(true);
  48386. return mesh;
  48387. };
  48388. return CSG;
  48389. }());
  48390. BABYLON.CSG = CSG;
  48391. })(BABYLON || (BABYLON = {}));
  48392. //# sourceMappingURL=babylon.csg.js.map
  48393. var BABYLON;
  48394. (function (BABYLON) {
  48395. var VRDistortionCorrectionPostProcess = (function (_super) {
  48396. __extends(VRDistortionCorrectionPostProcess, _super);
  48397. //ANY
  48398. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  48399. var _this = _super.call(this, name, "vrDistortionCorrection", [
  48400. 'LensCenter',
  48401. 'Scale',
  48402. 'ScaleIn',
  48403. 'HmdWarpParam'
  48404. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  48405. _this._isRightEye = isRightEye;
  48406. _this._distortionFactors = vrMetrics.distortionK;
  48407. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  48408. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  48409. _this.onSizeChangedObservable.add(function () {
  48410. _this.aspectRatio = _this.width * .5 / _this.height;
  48411. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  48412. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  48413. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  48414. });
  48415. _this.onApplyObservable.add(function (effect) {
  48416. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  48417. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  48418. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  48419. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  48420. });
  48421. return _this;
  48422. }
  48423. return VRDistortionCorrectionPostProcess;
  48424. }(BABYLON.PostProcess));
  48425. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  48426. })(BABYLON || (BABYLON = {}));
  48427. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  48428. // Mainly based on these 2 articles :
  48429. // 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
  48430. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  48431. var BABYLON;
  48432. (function (BABYLON) {
  48433. var JoystickAxis;
  48434. (function (JoystickAxis) {
  48435. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  48436. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  48437. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  48438. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  48439. var VirtualJoystick = (function () {
  48440. function VirtualJoystick(leftJoystick) {
  48441. var _this = this;
  48442. if (leftJoystick) {
  48443. this._leftJoystick = true;
  48444. }
  48445. else {
  48446. this._leftJoystick = false;
  48447. }
  48448. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  48449. VirtualJoystick._globalJoystickIndex++;
  48450. // By default left & right arrow keys are moving the X
  48451. // and up & down keys are moving the Y
  48452. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48453. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48454. this.reverseLeftRight = false;
  48455. this.reverseUpDown = false;
  48456. // collections of pointers
  48457. this._touches = new BABYLON.StringDictionary();
  48458. this.deltaPosition = BABYLON.Vector3.Zero();
  48459. this._joystickSensibility = 25;
  48460. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48461. this._rotationSpeed = 25;
  48462. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  48463. this._rotateOnAxisRelativeToMesh = false;
  48464. this._onResize = function (evt) {
  48465. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48466. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48467. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  48468. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  48469. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  48470. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  48471. };
  48472. // injecting a canvas element on top of the canvas 3D game
  48473. if (!VirtualJoystick.vjCanvas) {
  48474. window.addEventListener("resize", this._onResize, false);
  48475. VirtualJoystick.vjCanvas = document.createElement("canvas");
  48476. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  48477. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  48478. VirtualJoystick.vjCanvas.width = window.innerWidth;
  48479. VirtualJoystick.vjCanvas.height = window.innerHeight;
  48480. VirtualJoystick.vjCanvas.style.width = "100%";
  48481. VirtualJoystick.vjCanvas.style.height = "100%";
  48482. VirtualJoystick.vjCanvas.style.position = "absolute";
  48483. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  48484. VirtualJoystick.vjCanvas.style.top = "0px";
  48485. VirtualJoystick.vjCanvas.style.left = "0px";
  48486. VirtualJoystick.vjCanvas.style.zIndex = "5";
  48487. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  48488. // Support for jQuery PEP polyfill
  48489. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  48490. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  48491. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  48492. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48493. document.body.appendChild(VirtualJoystick.vjCanvas);
  48494. }
  48495. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  48496. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  48497. this.pressed = false;
  48498. // default joystick color
  48499. this._joystickColor = "cyan";
  48500. this._joystickPointerID = -1;
  48501. // current joystick position
  48502. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  48503. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  48504. // origin joystick position
  48505. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  48506. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  48507. this._onPointerDownHandlerRef = function (evt) {
  48508. _this._onPointerDown(evt);
  48509. };
  48510. this._onPointerMoveHandlerRef = function (evt) {
  48511. _this._onPointerMove(evt);
  48512. };
  48513. this._onPointerOutHandlerRef = function (evt) {
  48514. _this._onPointerUp(evt);
  48515. };
  48516. this._onPointerUpHandlerRef = function (evt) {
  48517. _this._onPointerUp(evt);
  48518. };
  48519. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  48520. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  48521. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  48522. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  48523. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  48524. evt.preventDefault(); // Disables system menu
  48525. }, false);
  48526. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48527. }
  48528. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  48529. this._joystickSensibility = newJoystickSensibility;
  48530. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  48531. };
  48532. VirtualJoystick.prototype._onPointerDown = function (e) {
  48533. var positionOnScreenCondition;
  48534. e.preventDefault();
  48535. if (this._leftJoystick === true) {
  48536. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  48537. }
  48538. else {
  48539. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  48540. }
  48541. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  48542. // First contact will be dedicated to the virtual joystick
  48543. this._joystickPointerID = e.pointerId;
  48544. this._joystickPointerStartPos.x = e.clientX;
  48545. this._joystickPointerStartPos.y = e.clientY;
  48546. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  48547. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  48548. this._deltaJoystickVector.x = 0;
  48549. this._deltaJoystickVector.y = 0;
  48550. this.pressed = true;
  48551. this._touches.add(e.pointerId.toString(), e);
  48552. }
  48553. else {
  48554. // You can only trigger the action buttons with a joystick declared
  48555. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  48556. this._action();
  48557. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  48558. }
  48559. }
  48560. };
  48561. VirtualJoystick.prototype._onPointerMove = function (e) {
  48562. // If the current pointer is the one associated to the joystick (first touch contact)
  48563. if (this._joystickPointerID == e.pointerId) {
  48564. this._joystickPointerPos.x = e.clientX;
  48565. this._joystickPointerPos.y = e.clientY;
  48566. this._deltaJoystickVector = this._joystickPointerPos.clone();
  48567. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  48568. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  48569. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  48570. switch (this._axisTargetedByLeftAndRight) {
  48571. case JoystickAxis.X:
  48572. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  48573. break;
  48574. case JoystickAxis.Y:
  48575. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  48576. break;
  48577. case JoystickAxis.Z:
  48578. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  48579. break;
  48580. }
  48581. var directionUpDown = this.reverseUpDown ? 1 : -1;
  48582. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  48583. switch (this._axisTargetedByUpAndDown) {
  48584. case JoystickAxis.X:
  48585. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  48586. break;
  48587. case JoystickAxis.Y:
  48588. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  48589. break;
  48590. case JoystickAxis.Z:
  48591. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  48592. break;
  48593. }
  48594. }
  48595. else {
  48596. var data = this._touches.get(e.pointerId.toString());
  48597. if (data) {
  48598. data.x = e.clientX;
  48599. data.y = e.clientY;
  48600. }
  48601. }
  48602. };
  48603. VirtualJoystick.prototype._onPointerUp = function (e) {
  48604. if (this._joystickPointerID == e.pointerId) {
  48605. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  48606. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  48607. this._joystickPointerID = -1;
  48608. this.pressed = false;
  48609. }
  48610. else {
  48611. var touch = this._touches.get(e.pointerId.toString());
  48612. if (touch) {
  48613. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48614. }
  48615. }
  48616. this._deltaJoystickVector.x = 0;
  48617. this._deltaJoystickVector.y = 0;
  48618. this._touches.remove(e.pointerId.toString());
  48619. };
  48620. /**
  48621. * Change the color of the virtual joystick
  48622. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  48623. */
  48624. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  48625. this._joystickColor = newColor;
  48626. };
  48627. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  48628. this._action = action;
  48629. };
  48630. // Define which axis you'd like to control for left & right
  48631. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  48632. switch (axis) {
  48633. case JoystickAxis.X:
  48634. case JoystickAxis.Y:
  48635. case JoystickAxis.Z:
  48636. this._axisTargetedByLeftAndRight = axis;
  48637. break;
  48638. default:
  48639. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  48640. break;
  48641. }
  48642. };
  48643. // Define which axis you'd like to control for up & down
  48644. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  48645. switch (axis) {
  48646. case JoystickAxis.X:
  48647. case JoystickAxis.Y:
  48648. case JoystickAxis.Z:
  48649. this._axisTargetedByUpAndDown = axis;
  48650. break;
  48651. default:
  48652. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  48653. break;
  48654. }
  48655. };
  48656. VirtualJoystick.prototype._clearCanvas = function () {
  48657. if (this._leftJoystick) {
  48658. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  48659. }
  48660. else {
  48661. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  48662. }
  48663. };
  48664. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  48665. var _this = this;
  48666. if (this.pressed) {
  48667. this._touches.forEach(function (key, touch) {
  48668. if (touch.pointerId === _this._joystickPointerID) {
  48669. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  48670. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  48671. VirtualJoystick.vjCanvasContext.beginPath();
  48672. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48673. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48674. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  48675. VirtualJoystick.vjCanvasContext.stroke();
  48676. VirtualJoystick.vjCanvasContext.closePath();
  48677. VirtualJoystick.vjCanvasContext.beginPath();
  48678. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48679. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  48680. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  48681. VirtualJoystick.vjCanvasContext.stroke();
  48682. VirtualJoystick.vjCanvasContext.closePath();
  48683. VirtualJoystick.vjCanvasContext.beginPath();
  48684. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  48685. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  48686. VirtualJoystick.vjCanvasContext.stroke();
  48687. VirtualJoystick.vjCanvasContext.closePath();
  48688. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  48689. }
  48690. else {
  48691. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  48692. VirtualJoystick.vjCanvasContext.beginPath();
  48693. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  48694. VirtualJoystick.vjCanvasContext.beginPath();
  48695. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  48696. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  48697. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  48698. VirtualJoystick.vjCanvasContext.stroke();
  48699. VirtualJoystick.vjCanvasContext.closePath();
  48700. touch.prevX = touch.x;
  48701. touch.prevY = touch.y;
  48702. }
  48703. ;
  48704. });
  48705. }
  48706. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  48707. };
  48708. VirtualJoystick.prototype.releaseCanvas = function () {
  48709. if (VirtualJoystick.vjCanvas) {
  48710. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  48711. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  48712. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  48713. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  48714. window.removeEventListener("resize", this._onResize);
  48715. document.body.removeChild(VirtualJoystick.vjCanvas);
  48716. VirtualJoystick.vjCanvas = null;
  48717. }
  48718. };
  48719. return VirtualJoystick;
  48720. }());
  48721. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  48722. VirtualJoystick._globalJoystickIndex = 0;
  48723. BABYLON.VirtualJoystick = VirtualJoystick;
  48724. })(BABYLON || (BABYLON = {}));
  48725. //# sourceMappingURL=babylon.virtualJoystick.js.map
  48726. var BABYLON;
  48727. (function (BABYLON) {
  48728. // We're mainly based on the logic defined into the FreeCamera code
  48729. var VirtualJoysticksCamera = (function (_super) {
  48730. __extends(VirtualJoysticksCamera, _super);
  48731. function VirtualJoysticksCamera(name, position, scene) {
  48732. var _this = _super.call(this, name, position, scene) || this;
  48733. _this.inputs.addVirtualJoystick();
  48734. return _this;
  48735. }
  48736. VirtualJoysticksCamera.prototype.getClassName = function () {
  48737. return "VirtualJoysticksCamera";
  48738. };
  48739. return VirtualJoysticksCamera;
  48740. }(BABYLON.FreeCamera));
  48741. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  48742. })(BABYLON || (BABYLON = {}));
  48743. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  48744. var BABYLON;
  48745. (function (BABYLON) {
  48746. var FreeCameraVirtualJoystickInput = (function () {
  48747. function FreeCameraVirtualJoystickInput() {
  48748. }
  48749. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  48750. return this._leftjoystick;
  48751. };
  48752. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  48753. return this._rightjoystick;
  48754. };
  48755. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  48756. if (this._leftjoystick) {
  48757. var camera = this.camera;
  48758. var speed = camera._computeLocalCameraSpeed() * 50;
  48759. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  48760. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  48761. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  48762. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  48763. if (!this._leftjoystick.pressed) {
  48764. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  48765. }
  48766. if (!this._rightjoystick.pressed) {
  48767. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  48768. }
  48769. }
  48770. };
  48771. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  48772. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  48773. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  48774. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  48775. this._leftjoystick.setJoystickSensibility(0.15);
  48776. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  48777. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  48778. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  48779. this._rightjoystick.reverseUpDown = true;
  48780. this._rightjoystick.setJoystickSensibility(0.05);
  48781. this._rightjoystick.setJoystickColor("yellow");
  48782. };
  48783. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  48784. this._leftjoystick.releaseCanvas();
  48785. this._rightjoystick.releaseCanvas();
  48786. };
  48787. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  48788. return "FreeCameraVirtualJoystickInput";
  48789. };
  48790. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  48791. return "virtualJoystick";
  48792. };
  48793. return FreeCameraVirtualJoystickInput;
  48794. }());
  48795. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  48796. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  48797. })(BABYLON || (BABYLON = {}));
  48798. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  48799. var BABYLON;
  48800. (function (BABYLON) {
  48801. var AnaglyphPostProcess = (function (_super) {
  48802. __extends(AnaglyphPostProcess, _super);
  48803. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  48804. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  48805. _this._passedProcess = rigCameras[0]._rigPostProcess;
  48806. _this.onApplyObservable.add(function (effect) {
  48807. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  48808. });
  48809. return _this;
  48810. }
  48811. return AnaglyphPostProcess;
  48812. }(BABYLON.PostProcess));
  48813. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  48814. })(BABYLON || (BABYLON = {}));
  48815. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  48816. var BABYLON;
  48817. (function (BABYLON) {
  48818. var OutlineRenderer = (function () {
  48819. function OutlineRenderer(scene) {
  48820. this._scene = scene;
  48821. }
  48822. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  48823. var _this = this;
  48824. if (useOverlay === void 0) { useOverlay = false; }
  48825. var scene = this._scene;
  48826. var engine = this._scene.getEngine();
  48827. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  48828. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  48829. return;
  48830. }
  48831. var mesh = subMesh.getRenderingMesh();
  48832. var material = subMesh.getMaterial();
  48833. engine.enableEffect(this._effect);
  48834. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  48835. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  48836. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  48837. // Bones
  48838. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48839. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48840. }
  48841. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  48842. // Alpha test
  48843. if (material && material.needAlphaTesting()) {
  48844. var alphaTexture = material.getAlphaTestTexture();
  48845. this._effect.setTexture("diffuseSampler", alphaTexture);
  48846. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48847. }
  48848. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  48849. };
  48850. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  48851. var defines = [];
  48852. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  48853. var mesh = subMesh.getMesh();
  48854. var material = subMesh.getMaterial();
  48855. // Alpha test
  48856. if (material && material.needAlphaTesting()) {
  48857. defines.push("#define ALPHATEST");
  48858. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48859. attribs.push(BABYLON.VertexBuffer.UVKind);
  48860. defines.push("#define UV1");
  48861. }
  48862. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48863. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48864. defines.push("#define UV2");
  48865. }
  48866. }
  48867. // Bones
  48868. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48869. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48870. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48871. if (mesh.numBoneInfluencers > 4) {
  48872. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48873. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48874. }
  48875. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48876. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48877. }
  48878. else {
  48879. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48880. }
  48881. // Instances
  48882. if (useInstances) {
  48883. defines.push("#define INSTANCES");
  48884. attribs.push("world0");
  48885. attribs.push("world1");
  48886. attribs.push("world2");
  48887. attribs.push("world3");
  48888. }
  48889. // Get correct effect
  48890. var join = defines.join("\n");
  48891. if (this._cachedDefines !== join) {
  48892. this._cachedDefines = join;
  48893. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  48894. }
  48895. return this._effect.isReady();
  48896. };
  48897. return OutlineRenderer;
  48898. }());
  48899. BABYLON.OutlineRenderer = OutlineRenderer;
  48900. })(BABYLON || (BABYLON = {}));
  48901. //# sourceMappingURL=babylon.outlineRenderer.js.map
  48902. var BABYLON;
  48903. (function (BABYLON) {
  48904. var MeshAssetTask = (function () {
  48905. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  48906. this.name = name;
  48907. this.meshesNames = meshesNames;
  48908. this.rootUrl = rootUrl;
  48909. this.sceneFilename = sceneFilename;
  48910. this.isCompleted = false;
  48911. }
  48912. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48913. var _this = this;
  48914. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  48915. _this.loadedMeshes = meshes;
  48916. _this.loadedParticleSystems = particleSystems;
  48917. _this.loadedSkeletons = skeletons;
  48918. _this.isCompleted = true;
  48919. if (_this.onSuccess) {
  48920. _this.onSuccess(_this);
  48921. }
  48922. onSuccess();
  48923. }, null, function () {
  48924. if (_this.onError) {
  48925. _this.onError(_this);
  48926. }
  48927. onError();
  48928. });
  48929. };
  48930. return MeshAssetTask;
  48931. }());
  48932. BABYLON.MeshAssetTask = MeshAssetTask;
  48933. var TextFileAssetTask = (function () {
  48934. function TextFileAssetTask(name, url) {
  48935. this.name = name;
  48936. this.url = url;
  48937. this.isCompleted = false;
  48938. }
  48939. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48940. var _this = this;
  48941. BABYLON.Tools.LoadFile(this.url, function (data) {
  48942. _this.text = data;
  48943. _this.isCompleted = true;
  48944. if (_this.onSuccess) {
  48945. _this.onSuccess(_this);
  48946. }
  48947. onSuccess();
  48948. }, null, scene.database, false, function () {
  48949. if (_this.onError) {
  48950. _this.onError(_this);
  48951. }
  48952. onError();
  48953. });
  48954. };
  48955. return TextFileAssetTask;
  48956. }());
  48957. BABYLON.TextFileAssetTask = TextFileAssetTask;
  48958. var BinaryFileAssetTask = (function () {
  48959. function BinaryFileAssetTask(name, url) {
  48960. this.name = name;
  48961. this.url = url;
  48962. this.isCompleted = false;
  48963. }
  48964. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48965. var _this = this;
  48966. BABYLON.Tools.LoadFile(this.url, function (data) {
  48967. _this.data = data;
  48968. _this.isCompleted = true;
  48969. if (_this.onSuccess) {
  48970. _this.onSuccess(_this);
  48971. }
  48972. onSuccess();
  48973. }, null, scene.database, true, function () {
  48974. if (_this.onError) {
  48975. _this.onError(_this);
  48976. }
  48977. onError();
  48978. });
  48979. };
  48980. return BinaryFileAssetTask;
  48981. }());
  48982. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  48983. var ImageAssetTask = (function () {
  48984. function ImageAssetTask(name, url) {
  48985. this.name = name;
  48986. this.url = url;
  48987. this.isCompleted = false;
  48988. }
  48989. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  48990. var _this = this;
  48991. var img = new Image();
  48992. BABYLON.Tools.SetCorsBehavior(this.url, img);
  48993. img.onload = function () {
  48994. _this.image = img;
  48995. _this.isCompleted = true;
  48996. if (_this.onSuccess) {
  48997. _this.onSuccess(_this);
  48998. }
  48999. onSuccess();
  49000. };
  49001. img.onerror = function () {
  49002. if (_this.onError) {
  49003. _this.onError(_this);
  49004. }
  49005. onError();
  49006. };
  49007. img.src = this.url;
  49008. };
  49009. return ImageAssetTask;
  49010. }());
  49011. BABYLON.ImageAssetTask = ImageAssetTask;
  49012. var TextureAssetTask = (function () {
  49013. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  49014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49015. this.name = name;
  49016. this.url = url;
  49017. this.noMipmap = noMipmap;
  49018. this.invertY = invertY;
  49019. this.samplingMode = samplingMode;
  49020. this.isCompleted = false;
  49021. }
  49022. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49023. var _this = this;
  49024. var onload = function () {
  49025. _this.isCompleted = true;
  49026. if (_this.onSuccess) {
  49027. _this.onSuccess(_this);
  49028. }
  49029. onSuccess();
  49030. };
  49031. var onerror = function () {
  49032. if (_this.onError) {
  49033. _this.onError(_this);
  49034. }
  49035. onError();
  49036. };
  49037. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  49038. };
  49039. return TextureAssetTask;
  49040. }());
  49041. BABYLON.TextureAssetTask = TextureAssetTask;
  49042. var CubeTextureAssetTask = (function () {
  49043. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  49044. this.name = name;
  49045. this.url = url;
  49046. this.extensions = extensions;
  49047. this.noMipmap = noMipmap;
  49048. this.files = files;
  49049. this.isCompleted = false;
  49050. }
  49051. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49052. var _this = this;
  49053. var onload = function () {
  49054. _this.isCompleted = true;
  49055. if (_this.onSuccess) {
  49056. _this.onSuccess(_this);
  49057. }
  49058. onSuccess();
  49059. };
  49060. var onerror = function () {
  49061. if (_this.onError) {
  49062. _this.onError(_this);
  49063. }
  49064. onError();
  49065. };
  49066. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  49067. };
  49068. return CubeTextureAssetTask;
  49069. }());
  49070. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  49071. var HDRCubeTextureAssetTask = (function () {
  49072. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  49073. if (noMipmap === void 0) { noMipmap = false; }
  49074. if (generateHarmonics === void 0) { generateHarmonics = true; }
  49075. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  49076. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  49077. this.name = name;
  49078. this.url = url;
  49079. this.size = size;
  49080. this.noMipmap = noMipmap;
  49081. this.generateHarmonics = generateHarmonics;
  49082. this.useInGammaSpace = useInGammaSpace;
  49083. this.usePMREMGenerator = usePMREMGenerator;
  49084. this.isCompleted = false;
  49085. }
  49086. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  49087. var _this = this;
  49088. var onload = function () {
  49089. _this.isCompleted = true;
  49090. if (_this.onSuccess) {
  49091. _this.onSuccess(_this);
  49092. }
  49093. onSuccess();
  49094. };
  49095. var onerror = function () {
  49096. if (_this.onError) {
  49097. _this.onError(_this);
  49098. }
  49099. onError();
  49100. };
  49101. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  49102. };
  49103. return HDRCubeTextureAssetTask;
  49104. }());
  49105. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  49106. var AssetsManager = (function () {
  49107. function AssetsManager(scene) {
  49108. this.tasks = new Array();
  49109. this.waitingTasksCount = 0;
  49110. this.useDefaultLoadingScreen = true;
  49111. this._scene = scene;
  49112. }
  49113. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  49114. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  49115. this.tasks.push(task);
  49116. return task;
  49117. };
  49118. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  49119. var task = new TextFileAssetTask(taskName, url);
  49120. this.tasks.push(task);
  49121. return task;
  49122. };
  49123. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  49124. var task = new BinaryFileAssetTask(taskName, url);
  49125. this.tasks.push(task);
  49126. return task;
  49127. };
  49128. AssetsManager.prototype.addImageTask = function (taskName, url) {
  49129. var task = new ImageAssetTask(taskName, url);
  49130. this.tasks.push(task);
  49131. return task;
  49132. };
  49133. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  49134. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49135. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  49136. this.tasks.push(task);
  49137. return task;
  49138. };
  49139. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  49140. this.waitingTasksCount--;
  49141. if (this.waitingTasksCount === 0) {
  49142. if (this.onFinish) {
  49143. this.onFinish(this.tasks);
  49144. }
  49145. this._scene.getEngine().hideLoadingUI();
  49146. }
  49147. };
  49148. AssetsManager.prototype._runTask = function (task) {
  49149. var _this = this;
  49150. task.run(this._scene, function () {
  49151. if (_this.onTaskSuccess) {
  49152. _this.onTaskSuccess(task);
  49153. }
  49154. _this._decreaseWaitingTasksCount();
  49155. }, function () {
  49156. if (_this.onTaskError) {
  49157. _this.onTaskError(task);
  49158. }
  49159. _this._decreaseWaitingTasksCount();
  49160. });
  49161. };
  49162. AssetsManager.prototype.reset = function () {
  49163. this.tasks = new Array();
  49164. return this;
  49165. };
  49166. AssetsManager.prototype.load = function () {
  49167. this.waitingTasksCount = this.tasks.length;
  49168. if (this.waitingTasksCount === 0) {
  49169. if (this.onFinish) {
  49170. this.onFinish(this.tasks);
  49171. }
  49172. return this;
  49173. }
  49174. if (this.useDefaultLoadingScreen) {
  49175. this._scene.getEngine().displayLoadingUI();
  49176. }
  49177. for (var index = 0; index < this.tasks.length; index++) {
  49178. var task = this.tasks[index];
  49179. this._runTask(task);
  49180. }
  49181. return this;
  49182. };
  49183. return AssetsManager;
  49184. }());
  49185. BABYLON.AssetsManager = AssetsManager;
  49186. })(BABYLON || (BABYLON = {}));
  49187. //# sourceMappingURL=babylon.assetsManager.js.map
  49188. var BABYLON;
  49189. (function (BABYLON) {
  49190. var VRCameraMetrics = (function () {
  49191. function VRCameraMetrics() {
  49192. this.compensateDistortion = true;
  49193. }
  49194. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  49195. get: function () {
  49196. return this.hResolution / (2 * this.vResolution);
  49197. },
  49198. enumerable: true,
  49199. configurable: true
  49200. });
  49201. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  49202. get: function () {
  49203. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  49204. },
  49205. enumerable: true,
  49206. configurable: true
  49207. });
  49208. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  49209. get: function () {
  49210. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49211. var h = (4 * meters) / this.hScreenSize;
  49212. return BABYLON.Matrix.Translation(h, 0, 0);
  49213. },
  49214. enumerable: true,
  49215. configurable: true
  49216. });
  49217. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  49218. get: function () {
  49219. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  49220. var h = (4 * meters) / this.hScreenSize;
  49221. return BABYLON.Matrix.Translation(-h, 0, 0);
  49222. },
  49223. enumerable: true,
  49224. configurable: true
  49225. });
  49226. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  49227. get: function () {
  49228. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  49234. get: function () {
  49235. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  49236. },
  49237. enumerable: true,
  49238. configurable: true
  49239. });
  49240. VRCameraMetrics.GetDefault = function () {
  49241. var result = new VRCameraMetrics();
  49242. result.hResolution = 1280;
  49243. result.vResolution = 800;
  49244. result.hScreenSize = 0.149759993;
  49245. result.vScreenSize = 0.0935999975;
  49246. result.vScreenCenter = 0.0467999987;
  49247. result.eyeToScreenDistance = 0.0410000011;
  49248. result.lensSeparationDistance = 0.0635000020;
  49249. result.interpupillaryDistance = 0.0640000030;
  49250. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  49251. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  49252. result.postProcessScaleFactor = 1.714605507808412;
  49253. result.lensCenterOffset = 0.151976421;
  49254. return result;
  49255. };
  49256. return VRCameraMetrics;
  49257. }());
  49258. BABYLON.VRCameraMetrics = VRCameraMetrics;
  49259. })(BABYLON || (BABYLON = {}));
  49260. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  49261. var BABYLON;
  49262. (function (BABYLON) {
  49263. var WebVRFreeCamera = (function (_super) {
  49264. __extends(WebVRFreeCamera, _super);
  49265. function WebVRFreeCamera(name, position, scene, webVROptions) {
  49266. if (webVROptions === void 0) { webVROptions = {}; }
  49267. var _this = _super.call(this, name, position, scene) || this;
  49268. _this.webVROptions = webVROptions;
  49269. _this._vrDevice = null;
  49270. _this.rawPose = null;
  49271. _this._vrEnabled = false;
  49272. _this._attached = false;
  49273. _this._positionOffset = BABYLON.Vector3.Zero();
  49274. _this._descendants = [];
  49275. _this.devicePosition = BABYLON.Vector3.Zero();
  49276. _this.deviceScaleFactor = 1;
  49277. _this.controllers = [];
  49278. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  49279. //legacy support - the compensation boolean was removed.
  49280. if (arguments.length === 5) {
  49281. _this.webVROptions = arguments[4];
  49282. }
  49283. // default webVR options
  49284. if (_this.webVROptions.trackPosition == undefined) {
  49285. _this.webVROptions.trackPosition = true;
  49286. }
  49287. if (_this.webVROptions.controllerMeshes == undefined) {
  49288. _this.webVROptions.controllerMeshes = true;
  49289. }
  49290. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  49291. _this.webVROptions.defaultLightningOnControllers = true;
  49292. }
  49293. _this.rotationQuaternion = new BABYLON.Quaternion();
  49294. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  49295. if (_this.webVROptions && _this.webVROptions.positionScale) {
  49296. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  49297. }
  49298. //enable VR
  49299. _this.getEngine().initWebVR();
  49300. if (!_this.getEngine().vrDisplaysPromise) {
  49301. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  49302. }
  49303. else {
  49304. _this._frameData = new VRFrameData();
  49305. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  49306. if (devices.length > 0) {
  49307. _this._vrEnabled = true;
  49308. if (_this.webVROptions.displayName) {
  49309. var found = devices.some(function (device) {
  49310. if (device.displayName === _this.webVROptions.displayName) {
  49311. _this._vrDevice = device;
  49312. return true;
  49313. }
  49314. else {
  49315. return false;
  49316. }
  49317. });
  49318. if (!found) {
  49319. _this._vrDevice = devices[0];
  49320. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  49321. }
  49322. }
  49323. else {
  49324. //choose the first one
  49325. _this._vrDevice = devices[0];
  49326. }
  49327. //reset the rig parameters.
  49328. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData });
  49329. if (_this._attached) {
  49330. _this.getEngine().enableVR(_this._vrDevice);
  49331. }
  49332. }
  49333. else {
  49334. BABYLON.Tools.Error("No WebVR devices found!");
  49335. }
  49336. });
  49337. }
  49338. // try to attach the controllers, if found.
  49339. _this.initControllers();
  49340. /**
  49341. * The idea behind the following lines:
  49342. * objects that have the camera as parent should actually have the rig cameras as a parent.
  49343. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  49344. * the second will not show it correctly.
  49345. *
  49346. * To solve this - each object that has the camera as parent will be added to a protected array.
  49347. * When the rig camera renders, it will take this array and set all of those to be its children.
  49348. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  49349. * Amazing!
  49350. */
  49351. scene.onBeforeCameraRenderObservable.add(function (camera) {
  49352. if (camera.parent === _this && _this.rigParenting) {
  49353. _this._descendants = _this.getDescendants(true, function (n) {
  49354. // don't take the cameras or the controllers!
  49355. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  49356. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  49357. return !isController && !isRigCamera;
  49358. });
  49359. _this._descendants.forEach(function (node) {
  49360. node.parent = camera;
  49361. });
  49362. }
  49363. });
  49364. scene.onAfterCameraRenderObservable.add(function (camera) {
  49365. if (camera.parent === _this && _this.rigParenting) {
  49366. _this._descendants.forEach(function (node) {
  49367. node.parent = _this;
  49368. });
  49369. }
  49370. });
  49371. return _this;
  49372. }
  49373. WebVRFreeCamera.prototype._checkInputs = function () {
  49374. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  49375. var currentPose = this._frameData.pose;
  49376. this.updateFromDevice(currentPose);
  49377. }
  49378. _super.prototype._checkInputs.call(this);
  49379. };
  49380. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  49381. if (poseData && poseData.orientation) {
  49382. this.rawPose = poseData;
  49383. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  49384. if (this.getScene().useRightHandedSystem) {
  49385. this.deviceRotationQuaternion.z *= -1;
  49386. this.deviceRotationQuaternion.w *= -1;
  49387. }
  49388. if (this.webVROptions.trackPosition && this.rawPose.position) {
  49389. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  49390. if (this.getScene().useRightHandedSystem) {
  49391. this.devicePosition.z *= -1;
  49392. }
  49393. }
  49394. }
  49395. };
  49396. /**
  49397. * WebVR's attach control will start broadcasting frames to the device.
  49398. * Note that in certain browsers (chrome for example) this function must be called
  49399. * within a user-interaction callback. Example:
  49400. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  49401. *
  49402. * @param {HTMLElement} element
  49403. * @param {boolean} [noPreventDefault]
  49404. *
  49405. * @memberOf WebVRFreeCamera
  49406. */
  49407. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  49408. _super.prototype.attachControl.call(this, element, noPreventDefault);
  49409. this._attached = true;
  49410. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  49411. if (this._vrEnabled) {
  49412. this.getEngine().enableVR(this._vrDevice);
  49413. }
  49414. };
  49415. WebVRFreeCamera.prototype.detachControl = function (element) {
  49416. _super.prototype.detachControl.call(this, element);
  49417. this._vrEnabled = false;
  49418. this._attached = false;
  49419. this.getEngine().disableVR();
  49420. };
  49421. WebVRFreeCamera.prototype.getClassName = function () {
  49422. return "WebVRFreeCamera";
  49423. };
  49424. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  49425. //uses the vrDisplay's "resetPose()".
  49426. //pitch and roll won't be affected.
  49427. this._vrDevice.resetPose();
  49428. };
  49429. WebVRFreeCamera.prototype._updateRigCameras = function () {
  49430. var camLeft = this._rigCameras[0];
  49431. var camRight = this._rigCameras[1];
  49432. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49433. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  49434. camLeft.position.copyFrom(this.devicePosition);
  49435. camRight.position.copyFrom(this.devicePosition);
  49436. };
  49437. /**
  49438. * This function is called by the two RIG cameras.
  49439. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  49440. */
  49441. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  49442. var _this = this;
  49443. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  49444. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  49445. if (!this.getScene().useRightHandedSystem) {
  49446. [2, 6, 8, 9, 14].forEach(function (num) {
  49447. _this._webvrViewMatrix.m[num] *= -1;
  49448. });
  49449. }
  49450. var parentCamera = this._cameraRigParams["parentCamera"];
  49451. // should the view matrix be updated with scale and position offset?
  49452. if (parentCamera.deviceScaleFactor !== 1) {
  49453. this._webvrViewMatrix.invert();
  49454. // scale the position, if set
  49455. if (parentCamera.deviceScaleFactor) {
  49456. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  49457. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  49458. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  49459. }
  49460. this._webvrViewMatrix.invert();
  49461. }
  49462. // update the camera rotation matrix
  49463. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  49464. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  49465. // Computing target and final matrix
  49466. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  49467. return this._webvrViewMatrix;
  49468. };
  49469. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  49470. var _this = this;
  49471. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  49472. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  49473. //babylon compatible matrix
  49474. if (!this.getScene().useRightHandedSystem) {
  49475. [8, 9, 10, 11].forEach(function (num) {
  49476. _this._projectionMatrix.m[num] *= -1;
  49477. });
  49478. }
  49479. return this._projectionMatrix;
  49480. };
  49481. WebVRFreeCamera.prototype.initControllers = function () {
  49482. var _this = this;
  49483. this.controllers = [];
  49484. new BABYLON.Gamepads(function (gp) {
  49485. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  49486. var webVrController = gp;
  49487. if (_this.webVROptions.controllerMeshes) {
  49488. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  49489. if (_this.webVROptions.defaultLightningOnControllers) {
  49490. if (!_this._lightOnControllers) {
  49491. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  49492. }
  49493. loadedMesh.getChildren().forEach(function (mesh) {
  49494. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  49495. });
  49496. }
  49497. });
  49498. }
  49499. webVrController.attachToPoseControlledCamera(_this);
  49500. // since this is async - sanity check. Is the controller already stored?
  49501. if (_this.controllers.indexOf(webVrController) === -1) {
  49502. //add to the controllers array
  49503. _this.controllers.push(webVrController);
  49504. //did we find enough controllers? Great! let the developer know.
  49505. if (_this.onControllersAttached && _this.controllers.length === 2) {
  49506. _this.onControllersAttached(_this.controllers);
  49507. }
  49508. }
  49509. }
  49510. });
  49511. };
  49512. return WebVRFreeCamera;
  49513. }(BABYLON.FreeCamera));
  49514. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  49515. })(BABYLON || (BABYLON = {}));
  49516. //# sourceMappingURL=babylon.webVRCamera.js.map
  49517. var BABYLON;
  49518. (function (BABYLON) {
  49519. // Standard optimizations
  49520. var SceneOptimization = (function () {
  49521. function SceneOptimization(priority) {
  49522. if (priority === void 0) { priority = 0; }
  49523. this.priority = priority;
  49524. this.apply = function (scene) {
  49525. return true; // Return true if everything that can be done was applied
  49526. };
  49527. }
  49528. return SceneOptimization;
  49529. }());
  49530. BABYLON.SceneOptimization = SceneOptimization;
  49531. var TextureOptimization = (function (_super) {
  49532. __extends(TextureOptimization, _super);
  49533. function TextureOptimization(priority, maximumSize) {
  49534. if (priority === void 0) { priority = 0; }
  49535. if (maximumSize === void 0) { maximumSize = 1024; }
  49536. var _this = _super.call(this, priority) || this;
  49537. _this.priority = priority;
  49538. _this.maximumSize = maximumSize;
  49539. _this.apply = function (scene) {
  49540. var allDone = true;
  49541. for (var index = 0; index < scene.textures.length; index++) {
  49542. var texture = scene.textures[index];
  49543. if (!texture.canRescale) {
  49544. continue;
  49545. }
  49546. var currentSize = texture.getSize();
  49547. var maxDimension = Math.max(currentSize.width, currentSize.height);
  49548. if (maxDimension > _this.maximumSize) {
  49549. texture.scale(0.5);
  49550. allDone = false;
  49551. }
  49552. }
  49553. return allDone;
  49554. };
  49555. return _this;
  49556. }
  49557. return TextureOptimization;
  49558. }(SceneOptimization));
  49559. BABYLON.TextureOptimization = TextureOptimization;
  49560. var HardwareScalingOptimization = (function (_super) {
  49561. __extends(HardwareScalingOptimization, _super);
  49562. function HardwareScalingOptimization(priority, maximumScale) {
  49563. if (priority === void 0) { priority = 0; }
  49564. if (maximumScale === void 0) { maximumScale = 2; }
  49565. var _this = _super.call(this, priority) || this;
  49566. _this.priority = priority;
  49567. _this.maximumScale = maximumScale;
  49568. _this._currentScale = 1;
  49569. _this.apply = function (scene) {
  49570. _this._currentScale++;
  49571. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  49572. return _this._currentScale >= _this.maximumScale;
  49573. };
  49574. return _this;
  49575. }
  49576. return HardwareScalingOptimization;
  49577. }(SceneOptimization));
  49578. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  49579. var ShadowsOptimization = (function (_super) {
  49580. __extends(ShadowsOptimization, _super);
  49581. function ShadowsOptimization() {
  49582. var _this = _super !== null && _super.apply(this, arguments) || this;
  49583. _this.apply = function (scene) {
  49584. scene.shadowsEnabled = false;
  49585. return true;
  49586. };
  49587. return _this;
  49588. }
  49589. return ShadowsOptimization;
  49590. }(SceneOptimization));
  49591. BABYLON.ShadowsOptimization = ShadowsOptimization;
  49592. var PostProcessesOptimization = (function (_super) {
  49593. __extends(PostProcessesOptimization, _super);
  49594. function PostProcessesOptimization() {
  49595. var _this = _super !== null && _super.apply(this, arguments) || this;
  49596. _this.apply = function (scene) {
  49597. scene.postProcessesEnabled = false;
  49598. return true;
  49599. };
  49600. return _this;
  49601. }
  49602. return PostProcessesOptimization;
  49603. }(SceneOptimization));
  49604. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  49605. var LensFlaresOptimization = (function (_super) {
  49606. __extends(LensFlaresOptimization, _super);
  49607. function LensFlaresOptimization() {
  49608. var _this = _super !== null && _super.apply(this, arguments) || this;
  49609. _this.apply = function (scene) {
  49610. scene.lensFlaresEnabled = false;
  49611. return true;
  49612. };
  49613. return _this;
  49614. }
  49615. return LensFlaresOptimization;
  49616. }(SceneOptimization));
  49617. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  49618. var ParticlesOptimization = (function (_super) {
  49619. __extends(ParticlesOptimization, _super);
  49620. function ParticlesOptimization() {
  49621. var _this = _super !== null && _super.apply(this, arguments) || this;
  49622. _this.apply = function (scene) {
  49623. scene.particlesEnabled = false;
  49624. return true;
  49625. };
  49626. return _this;
  49627. }
  49628. return ParticlesOptimization;
  49629. }(SceneOptimization));
  49630. BABYLON.ParticlesOptimization = ParticlesOptimization;
  49631. var RenderTargetsOptimization = (function (_super) {
  49632. __extends(RenderTargetsOptimization, _super);
  49633. function RenderTargetsOptimization() {
  49634. var _this = _super !== null && _super.apply(this, arguments) || this;
  49635. _this.apply = function (scene) {
  49636. scene.renderTargetsEnabled = false;
  49637. return true;
  49638. };
  49639. return _this;
  49640. }
  49641. return RenderTargetsOptimization;
  49642. }(SceneOptimization));
  49643. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  49644. var MergeMeshesOptimization = (function (_super) {
  49645. __extends(MergeMeshesOptimization, _super);
  49646. function MergeMeshesOptimization() {
  49647. var _this = _super !== null && _super.apply(this, arguments) || this;
  49648. _this._canBeMerged = function (abstractMesh) {
  49649. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  49650. return false;
  49651. }
  49652. var mesh = abstractMesh;
  49653. if (!mesh.isVisible || !mesh.isEnabled()) {
  49654. return false;
  49655. }
  49656. if (mesh.instances.length > 0) {
  49657. return false;
  49658. }
  49659. if (mesh.skeleton || mesh.hasLODLevels) {
  49660. return false;
  49661. }
  49662. if (mesh.parent) {
  49663. return false;
  49664. }
  49665. return true;
  49666. };
  49667. _this.apply = function (scene, updateSelectionTree) {
  49668. var globalPool = scene.meshes.slice(0);
  49669. var globalLength = globalPool.length;
  49670. for (var index = 0; index < globalLength; index++) {
  49671. var currentPool = new Array();
  49672. var current = globalPool[index];
  49673. // Checks
  49674. if (!_this._canBeMerged(current)) {
  49675. continue;
  49676. }
  49677. currentPool.push(current);
  49678. // Find compatible meshes
  49679. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  49680. var otherMesh = globalPool[subIndex];
  49681. if (!_this._canBeMerged(otherMesh)) {
  49682. continue;
  49683. }
  49684. if (otherMesh.material !== current.material) {
  49685. continue;
  49686. }
  49687. if (otherMesh.checkCollisions !== current.checkCollisions) {
  49688. continue;
  49689. }
  49690. currentPool.push(otherMesh);
  49691. globalLength--;
  49692. globalPool.splice(subIndex, 1);
  49693. subIndex--;
  49694. }
  49695. if (currentPool.length < 2) {
  49696. continue;
  49697. }
  49698. // Merge meshes
  49699. BABYLON.Mesh.MergeMeshes(currentPool);
  49700. }
  49701. if (updateSelectionTree != undefined) {
  49702. if (updateSelectionTree) {
  49703. scene.createOrUpdateSelectionOctree();
  49704. }
  49705. }
  49706. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  49707. scene.createOrUpdateSelectionOctree();
  49708. }
  49709. return true;
  49710. };
  49711. return _this;
  49712. }
  49713. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  49714. get: function () {
  49715. return MergeMeshesOptimization._UpdateSelectionTree;
  49716. },
  49717. set: function (value) {
  49718. MergeMeshesOptimization._UpdateSelectionTree = value;
  49719. },
  49720. enumerable: true,
  49721. configurable: true
  49722. });
  49723. return MergeMeshesOptimization;
  49724. }(SceneOptimization));
  49725. MergeMeshesOptimization._UpdateSelectionTree = false;
  49726. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  49727. // Options
  49728. var SceneOptimizerOptions = (function () {
  49729. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  49730. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  49731. if (trackerDuration === void 0) { trackerDuration = 2000; }
  49732. this.targetFrameRate = targetFrameRate;
  49733. this.trackerDuration = trackerDuration;
  49734. this.optimizations = new Array();
  49735. }
  49736. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  49737. var result = new SceneOptimizerOptions(targetFrameRate);
  49738. var priority = 0;
  49739. result.optimizations.push(new MergeMeshesOptimization(priority));
  49740. result.optimizations.push(new ShadowsOptimization(priority));
  49741. result.optimizations.push(new LensFlaresOptimization(priority));
  49742. // Next priority
  49743. priority++;
  49744. result.optimizations.push(new PostProcessesOptimization(priority));
  49745. result.optimizations.push(new ParticlesOptimization(priority));
  49746. // Next priority
  49747. priority++;
  49748. result.optimizations.push(new TextureOptimization(priority, 1024));
  49749. return result;
  49750. };
  49751. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  49752. var result = new SceneOptimizerOptions(targetFrameRate);
  49753. var priority = 0;
  49754. result.optimizations.push(new MergeMeshesOptimization(priority));
  49755. result.optimizations.push(new ShadowsOptimization(priority));
  49756. result.optimizations.push(new LensFlaresOptimization(priority));
  49757. // Next priority
  49758. priority++;
  49759. result.optimizations.push(new PostProcessesOptimization(priority));
  49760. result.optimizations.push(new ParticlesOptimization(priority));
  49761. // Next priority
  49762. priority++;
  49763. result.optimizations.push(new TextureOptimization(priority, 512));
  49764. // Next priority
  49765. priority++;
  49766. result.optimizations.push(new RenderTargetsOptimization(priority));
  49767. // Next priority
  49768. priority++;
  49769. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  49770. return result;
  49771. };
  49772. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  49773. var result = new SceneOptimizerOptions(targetFrameRate);
  49774. var priority = 0;
  49775. result.optimizations.push(new MergeMeshesOptimization(priority));
  49776. result.optimizations.push(new ShadowsOptimization(priority));
  49777. result.optimizations.push(new LensFlaresOptimization(priority));
  49778. // Next priority
  49779. priority++;
  49780. result.optimizations.push(new PostProcessesOptimization(priority));
  49781. result.optimizations.push(new ParticlesOptimization(priority));
  49782. // Next priority
  49783. priority++;
  49784. result.optimizations.push(new TextureOptimization(priority, 256));
  49785. // Next priority
  49786. priority++;
  49787. result.optimizations.push(new RenderTargetsOptimization(priority));
  49788. // Next priority
  49789. priority++;
  49790. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  49791. return result;
  49792. };
  49793. return SceneOptimizerOptions;
  49794. }());
  49795. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  49796. // Scene optimizer tool
  49797. var SceneOptimizer = (function () {
  49798. function SceneOptimizer() {
  49799. }
  49800. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  49801. // TODO: add an epsilon
  49802. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  49803. if (onSuccess) {
  49804. onSuccess();
  49805. }
  49806. return;
  49807. }
  49808. // Apply current level of optimizations
  49809. var allDone = true;
  49810. var noOptimizationApplied = true;
  49811. for (var index = 0; index < options.optimizations.length; index++) {
  49812. var optimization = options.optimizations[index];
  49813. if (optimization.priority === currentPriorityLevel) {
  49814. noOptimizationApplied = false;
  49815. allDone = allDone && optimization.apply(scene);
  49816. }
  49817. }
  49818. // If no optimization was applied, this is a failure :(
  49819. if (noOptimizationApplied) {
  49820. if (onFailure) {
  49821. onFailure();
  49822. }
  49823. return;
  49824. }
  49825. // If all optimizations were done, move to next level
  49826. if (allDone) {
  49827. currentPriorityLevel++;
  49828. }
  49829. // Let's the system running for a specific amount of time before checking FPS
  49830. scene.executeWhenReady(function () {
  49831. setTimeout(function () {
  49832. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  49833. }, options.trackerDuration);
  49834. });
  49835. };
  49836. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  49837. if (!options) {
  49838. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  49839. }
  49840. // Let's the system running for a specific amount of time before checking FPS
  49841. scene.executeWhenReady(function () {
  49842. setTimeout(function () {
  49843. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  49844. }, options.trackerDuration);
  49845. });
  49846. };
  49847. return SceneOptimizer;
  49848. }());
  49849. BABYLON.SceneOptimizer = SceneOptimizer;
  49850. })(BABYLON || (BABYLON = {}));
  49851. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  49852. var BABYLON;
  49853. (function (BABYLON) {
  49854. var Internals;
  49855. (function (Internals) {
  49856. var MeshLODLevel = (function () {
  49857. function MeshLODLevel(distance, mesh) {
  49858. this.distance = distance;
  49859. this.mesh = mesh;
  49860. }
  49861. return MeshLODLevel;
  49862. }());
  49863. Internals.MeshLODLevel = MeshLODLevel;
  49864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49865. })(BABYLON || (BABYLON = {}));
  49866. //# sourceMappingURL=babylon.meshLODLevel.js.map
  49867. var BABYLON;
  49868. (function (BABYLON) {
  49869. var RawTexture = (function (_super) {
  49870. __extends(RawTexture, _super);
  49871. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  49872. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49873. if (invertY === void 0) { invertY = false; }
  49874. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49875. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  49876. _this.format = format;
  49877. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  49878. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49879. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49880. return _this;
  49881. }
  49882. RawTexture.prototype.update = function (data) {
  49883. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  49884. };
  49885. // Statics
  49886. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49887. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49888. if (invertY === void 0) { invertY = false; }
  49889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49890. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  49891. };
  49892. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49893. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49894. if (invertY === void 0) { invertY = false; }
  49895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49896. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49897. };
  49898. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49899. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49900. if (invertY === void 0) { invertY = false; }
  49901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49902. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  49903. };
  49904. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49905. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49906. if (invertY === void 0) { invertY = false; }
  49907. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49908. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  49909. };
  49910. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  49911. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49912. if (invertY === void 0) { invertY = false; }
  49913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49914. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  49915. };
  49916. return RawTexture;
  49917. }(BABYLON.Texture));
  49918. BABYLON.RawTexture = RawTexture;
  49919. })(BABYLON || (BABYLON = {}));
  49920. //# sourceMappingURL=babylon.rawTexture.js.map
  49921. /// <reference path="..\Math\babylon.math.ts" />
  49922. var BABYLON;
  49923. (function (BABYLON) {
  49924. var IndexedVector2 = (function (_super) {
  49925. __extends(IndexedVector2, _super);
  49926. function IndexedVector2(original, index) {
  49927. var _this = _super.call(this, original.x, original.y) || this;
  49928. _this.index = index;
  49929. return _this;
  49930. }
  49931. return IndexedVector2;
  49932. }(BABYLON.Vector2));
  49933. var PolygonPoints = (function () {
  49934. function PolygonPoints() {
  49935. this.elements = new Array();
  49936. }
  49937. PolygonPoints.prototype.add = function (originalPoints) {
  49938. var _this = this;
  49939. var result = new Array();
  49940. originalPoints.forEach(function (point) {
  49941. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  49942. var newPoint = new IndexedVector2(point, _this.elements.length);
  49943. result.push(newPoint);
  49944. _this.elements.push(newPoint);
  49945. }
  49946. });
  49947. return result;
  49948. };
  49949. PolygonPoints.prototype.computeBounds = function () {
  49950. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49951. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  49952. this.elements.forEach(function (point) {
  49953. // x
  49954. if (point.x < lmin.x) {
  49955. lmin.x = point.x;
  49956. }
  49957. else if (point.x > lmax.x) {
  49958. lmax.x = point.x;
  49959. }
  49960. // y
  49961. if (point.y < lmin.y) {
  49962. lmin.y = point.y;
  49963. }
  49964. else if (point.y > lmax.y) {
  49965. lmax.y = point.y;
  49966. }
  49967. });
  49968. return {
  49969. min: lmin,
  49970. max: lmax,
  49971. width: lmax.x - lmin.x,
  49972. height: lmax.y - lmin.y
  49973. };
  49974. };
  49975. return PolygonPoints;
  49976. }());
  49977. var Polygon = (function () {
  49978. function Polygon() {
  49979. }
  49980. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  49981. return [
  49982. new BABYLON.Vector2(xmin, ymin),
  49983. new BABYLON.Vector2(xmax, ymin),
  49984. new BABYLON.Vector2(xmax, ymax),
  49985. new BABYLON.Vector2(xmin, ymax)
  49986. ];
  49987. };
  49988. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  49989. if (cx === void 0) { cx = 0; }
  49990. if (cy === void 0) { cy = 0; }
  49991. if (numberOfSides === void 0) { numberOfSides = 32; }
  49992. var result = new Array();
  49993. var angle = 0;
  49994. var increment = (Math.PI * 2) / numberOfSides;
  49995. for (var i = 0; i < numberOfSides; i++) {
  49996. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  49997. angle -= increment;
  49998. }
  49999. return result;
  50000. };
  50001. Polygon.Parse = function (input) {
  50002. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  50003. var i, result = [];
  50004. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  50005. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  50006. }
  50007. return result;
  50008. };
  50009. Polygon.StartingAt = function (x, y) {
  50010. return BABYLON.Path2.StartingAt(x, y);
  50011. };
  50012. return Polygon;
  50013. }());
  50014. BABYLON.Polygon = Polygon;
  50015. var PolygonMeshBuilder = (function () {
  50016. function PolygonMeshBuilder(name, contours, scene) {
  50017. this._points = new PolygonPoints();
  50018. this._outlinepoints = new PolygonPoints();
  50019. this._holes = [];
  50020. this._epoints = new Array();
  50021. this._eholes = new Array();
  50022. this._name = name;
  50023. this._scene = scene;
  50024. var points;
  50025. if (contours instanceof BABYLON.Path2) {
  50026. points = contours.getPoints();
  50027. }
  50028. else {
  50029. points = contours;
  50030. }
  50031. this._addToepoint(points);
  50032. this._points.add(points);
  50033. this._outlinepoints.add(points);
  50034. }
  50035. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  50036. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  50037. var p = points_1[_i];
  50038. this._epoints.push(p.x, p.y);
  50039. }
  50040. };
  50041. PolygonMeshBuilder.prototype.addHole = function (hole) {
  50042. this._points.add(hole);
  50043. var holepoints = new PolygonPoints();
  50044. holepoints.add(hole);
  50045. this._holes.push(holepoints);
  50046. this._eholes.push(this._epoints.length / 2);
  50047. this._addToepoint(hole);
  50048. return this;
  50049. };
  50050. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  50051. var _this = this;
  50052. if (updatable === void 0) { updatable = false; }
  50053. var result = new BABYLON.Mesh(this._name, this._scene);
  50054. var normals = [];
  50055. var positions = [];
  50056. var uvs = [];
  50057. var bounds = this._points.computeBounds();
  50058. this._points.elements.forEach(function (p) {
  50059. normals.push(0, 1.0, 0);
  50060. positions.push(p.x, 0, p.y);
  50061. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  50062. });
  50063. var indices = [];
  50064. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  50065. for (var i = 0; i < res.length; i++) {
  50066. indices.push(res[i]);
  50067. }
  50068. if (depth > 0) {
  50069. var positionscount = (positions.length / 3); //get the current pointcount
  50070. this._points.elements.forEach(function (p) {
  50071. normals.push(0, -1.0, 0);
  50072. positions.push(p.x, -depth, p.y);
  50073. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  50074. });
  50075. var totalCount = indices.length;
  50076. for (var i = 0; i < totalCount; i += 3) {
  50077. var i0 = indices[i + 0];
  50078. var i1 = indices[i + 1];
  50079. var i2 = indices[i + 2];
  50080. indices.push(i2 + positionscount);
  50081. indices.push(i1 + positionscount);
  50082. indices.push(i0 + positionscount);
  50083. }
  50084. //Add the sides
  50085. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  50086. this._holes.forEach(function (hole) {
  50087. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  50088. });
  50089. }
  50090. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  50091. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  50092. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  50093. result.setIndices(indices);
  50094. return result;
  50095. };
  50096. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  50097. var StartIndex = positions.length / 3;
  50098. var ulength = 0;
  50099. for (var i = 0; i < points.elements.length; i++) {
  50100. var p = points.elements[i];
  50101. var p1;
  50102. if ((i + 1) > points.elements.length - 1) {
  50103. p1 = points.elements[0];
  50104. }
  50105. else {
  50106. p1 = points.elements[i + 1];
  50107. }
  50108. positions.push(p.x, 0, p.y);
  50109. positions.push(p.x, -depth, p.y);
  50110. positions.push(p1.x, 0, p1.y);
  50111. positions.push(p1.x, -depth, p1.y);
  50112. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  50113. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  50114. var v3 = v2.subtract(v1);
  50115. var v4 = new BABYLON.Vector3(0, 1, 0);
  50116. var vn = BABYLON.Vector3.Cross(v3, v4);
  50117. vn = vn.normalize();
  50118. uvs.push(ulength / bounds.width, 0);
  50119. uvs.push(ulength / bounds.width, 1);
  50120. ulength += v3.length();
  50121. uvs.push((ulength / bounds.width), 0);
  50122. uvs.push((ulength / bounds.width), 1);
  50123. if (!flip) {
  50124. normals.push(-vn.x, -vn.y, -vn.z);
  50125. normals.push(-vn.x, -vn.y, -vn.z);
  50126. normals.push(-vn.x, -vn.y, -vn.z);
  50127. normals.push(-vn.x, -vn.y, -vn.z);
  50128. indices.push(StartIndex);
  50129. indices.push(StartIndex + 1);
  50130. indices.push(StartIndex + 2);
  50131. indices.push(StartIndex + 1);
  50132. indices.push(StartIndex + 3);
  50133. indices.push(StartIndex + 2);
  50134. }
  50135. else {
  50136. normals.push(vn.x, vn.y, vn.z);
  50137. normals.push(vn.x, vn.y, vn.z);
  50138. normals.push(vn.x, vn.y, vn.z);
  50139. normals.push(vn.x, vn.y, vn.z);
  50140. indices.push(StartIndex);
  50141. indices.push(StartIndex + 2);
  50142. indices.push(StartIndex + 1);
  50143. indices.push(StartIndex + 1);
  50144. indices.push(StartIndex + 2);
  50145. indices.push(StartIndex + 3);
  50146. }
  50147. StartIndex += 4;
  50148. }
  50149. ;
  50150. };
  50151. return PolygonMeshBuilder;
  50152. }());
  50153. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  50154. })(BABYLON || (BABYLON = {}));
  50155. //# sourceMappingURL=babylon.polygonMesh.js.map
  50156. var BABYLON;
  50157. (function (BABYLON) {
  50158. var Octree = (function () {
  50159. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  50160. if (maxDepth === void 0) { maxDepth = 2; }
  50161. this.maxDepth = maxDepth;
  50162. this.dynamicContent = new Array();
  50163. this._maxBlockCapacity = maxBlockCapacity || 64;
  50164. this._selectionContent = new BABYLON.SmartArray(1024);
  50165. this._creationFunc = creationFunc;
  50166. }
  50167. // Methods
  50168. Octree.prototype.update = function (worldMin, worldMax, entries) {
  50169. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  50170. };
  50171. Octree.prototype.addMesh = function (entry) {
  50172. for (var index = 0; index < this.blocks.length; index++) {
  50173. var block = this.blocks[index];
  50174. block.addEntry(entry);
  50175. }
  50176. };
  50177. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  50178. this._selectionContent.reset();
  50179. for (var index = 0; index < this.blocks.length; index++) {
  50180. var block = this.blocks[index];
  50181. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  50182. }
  50183. if (allowDuplicate) {
  50184. this._selectionContent.concat(this.dynamicContent);
  50185. }
  50186. else {
  50187. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50188. }
  50189. return this._selectionContent;
  50190. };
  50191. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  50192. this._selectionContent.reset();
  50193. for (var index = 0; index < this.blocks.length; index++) {
  50194. var block = this.blocks[index];
  50195. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  50196. }
  50197. if (allowDuplicate) {
  50198. this._selectionContent.concat(this.dynamicContent);
  50199. }
  50200. else {
  50201. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50202. }
  50203. return this._selectionContent;
  50204. };
  50205. Octree.prototype.intersectsRay = function (ray) {
  50206. this._selectionContent.reset();
  50207. for (var index = 0; index < this.blocks.length; index++) {
  50208. var block = this.blocks[index];
  50209. block.intersectsRay(ray, this._selectionContent);
  50210. }
  50211. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  50212. return this._selectionContent;
  50213. };
  50214. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  50215. target.blocks = new Array();
  50216. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  50217. // Segmenting space
  50218. for (var x = 0; x < 2; x++) {
  50219. for (var y = 0; y < 2; y++) {
  50220. for (var z = 0; z < 2; z++) {
  50221. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  50222. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  50223. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  50224. block.addEntries(entries);
  50225. target.blocks.push(block);
  50226. }
  50227. }
  50228. }
  50229. };
  50230. return Octree;
  50231. }());
  50232. Octree.CreationFuncForMeshes = function (entry, block) {
  50233. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50234. block.entries.push(entry);
  50235. }
  50236. };
  50237. Octree.CreationFuncForSubMeshes = function (entry, block) {
  50238. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  50239. block.entries.push(entry);
  50240. }
  50241. };
  50242. BABYLON.Octree = Octree;
  50243. })(BABYLON || (BABYLON = {}));
  50244. //# sourceMappingURL=babylon.octree.js.map
  50245. var BABYLON;
  50246. (function (BABYLON) {
  50247. var OctreeBlock = (function () {
  50248. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  50249. this.entries = new Array();
  50250. this._boundingVectors = new Array();
  50251. this._capacity = capacity;
  50252. this._depth = depth;
  50253. this._maxDepth = maxDepth;
  50254. this._creationFunc = creationFunc;
  50255. this._minPoint = minPoint;
  50256. this._maxPoint = maxPoint;
  50257. this._boundingVectors.push(minPoint.clone());
  50258. this._boundingVectors.push(maxPoint.clone());
  50259. this._boundingVectors.push(minPoint.clone());
  50260. this._boundingVectors[2].x = maxPoint.x;
  50261. this._boundingVectors.push(minPoint.clone());
  50262. this._boundingVectors[3].y = maxPoint.y;
  50263. this._boundingVectors.push(minPoint.clone());
  50264. this._boundingVectors[4].z = maxPoint.z;
  50265. this._boundingVectors.push(maxPoint.clone());
  50266. this._boundingVectors[5].z = minPoint.z;
  50267. this._boundingVectors.push(maxPoint.clone());
  50268. this._boundingVectors[6].x = minPoint.x;
  50269. this._boundingVectors.push(maxPoint.clone());
  50270. this._boundingVectors[7].y = minPoint.y;
  50271. }
  50272. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  50273. // Property
  50274. get: function () {
  50275. return this._capacity;
  50276. },
  50277. enumerable: true,
  50278. configurable: true
  50279. });
  50280. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  50281. get: function () {
  50282. return this._minPoint;
  50283. },
  50284. enumerable: true,
  50285. configurable: true
  50286. });
  50287. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  50288. get: function () {
  50289. return this._maxPoint;
  50290. },
  50291. enumerable: true,
  50292. configurable: true
  50293. });
  50294. // Methods
  50295. OctreeBlock.prototype.addEntry = function (entry) {
  50296. if (this.blocks) {
  50297. for (var index = 0; index < this.blocks.length; index++) {
  50298. var block = this.blocks[index];
  50299. block.addEntry(entry);
  50300. }
  50301. return;
  50302. }
  50303. this._creationFunc(entry, this);
  50304. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  50305. this.createInnerBlocks();
  50306. }
  50307. };
  50308. OctreeBlock.prototype.addEntries = function (entries) {
  50309. for (var index = 0; index < entries.length; index++) {
  50310. var mesh = entries[index];
  50311. this.addEntry(mesh);
  50312. }
  50313. };
  50314. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  50315. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  50316. if (this.blocks) {
  50317. for (var index = 0; index < this.blocks.length; index++) {
  50318. var block = this.blocks[index];
  50319. block.select(frustumPlanes, selection, allowDuplicate);
  50320. }
  50321. return;
  50322. }
  50323. if (allowDuplicate) {
  50324. selection.concat(this.entries);
  50325. }
  50326. else {
  50327. selection.concatWithNoDuplicate(this.entries);
  50328. }
  50329. }
  50330. };
  50331. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  50332. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  50333. if (this.blocks) {
  50334. for (var index = 0; index < this.blocks.length; index++) {
  50335. var block = this.blocks[index];
  50336. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  50337. }
  50338. return;
  50339. }
  50340. if (allowDuplicate) {
  50341. selection.concat(this.entries);
  50342. }
  50343. else {
  50344. selection.concatWithNoDuplicate(this.entries);
  50345. }
  50346. }
  50347. };
  50348. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  50349. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  50350. if (this.blocks) {
  50351. for (var index = 0; index < this.blocks.length; index++) {
  50352. var block = this.blocks[index];
  50353. block.intersectsRay(ray, selection);
  50354. }
  50355. return;
  50356. }
  50357. selection.concatWithNoDuplicate(this.entries);
  50358. }
  50359. };
  50360. OctreeBlock.prototype.createInnerBlocks = function () {
  50361. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  50362. };
  50363. return OctreeBlock;
  50364. }());
  50365. BABYLON.OctreeBlock = OctreeBlock;
  50366. })(BABYLON || (BABYLON = {}));
  50367. //# sourceMappingURL=babylon.octreeBlock.js.map
  50368. var BABYLON;
  50369. (function (BABYLON) {
  50370. var BlurPostProcess = (function (_super) {
  50371. __extends(BlurPostProcess, _super);
  50372. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  50373. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50374. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  50375. _this.direction = direction;
  50376. _this.blurWidth = blurWidth;
  50377. _this.onApplyObservable.add(function (effect) {
  50378. effect.setFloat2("screenSize", _this.width, _this.height);
  50379. effect.setVector2("direction", _this.direction);
  50380. effect.setFloat("blurWidth", _this.blurWidth);
  50381. });
  50382. return _this;
  50383. }
  50384. return BlurPostProcess;
  50385. }(BABYLON.PostProcess));
  50386. BABYLON.BlurPostProcess = BlurPostProcess;
  50387. })(BABYLON || (BABYLON = {}));
  50388. //# sourceMappingURL=babylon.blurPostProcess.js.map
  50389. var BABYLON;
  50390. (function (BABYLON) {
  50391. var RefractionPostProcess = (function (_super) {
  50392. __extends(RefractionPostProcess, _super);
  50393. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  50394. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  50395. _this.color = color;
  50396. _this.depth = depth;
  50397. _this.colorLevel = colorLevel;
  50398. _this.onActivateObservable.add(function (cam) {
  50399. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  50400. });
  50401. _this.onApplyObservable.add(function (effect) {
  50402. effect.setColor3("baseColor", _this.color);
  50403. effect.setFloat("depth", _this.depth);
  50404. effect.setFloat("colorLevel", _this.colorLevel);
  50405. effect.setTexture("refractionSampler", _this._refRexture);
  50406. });
  50407. return _this;
  50408. }
  50409. // Methods
  50410. RefractionPostProcess.prototype.dispose = function (camera) {
  50411. if (this._refRexture) {
  50412. this._refRexture.dispose();
  50413. }
  50414. _super.prototype.dispose.call(this, camera);
  50415. };
  50416. return RefractionPostProcess;
  50417. }(BABYLON.PostProcess));
  50418. BABYLON.RefractionPostProcess = RefractionPostProcess;
  50419. })(BABYLON || (BABYLON = {}));
  50420. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  50421. var BABYLON;
  50422. (function (BABYLON) {
  50423. var BlackAndWhitePostProcess = (function (_super) {
  50424. __extends(BlackAndWhitePostProcess, _super);
  50425. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  50426. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  50427. }
  50428. return BlackAndWhitePostProcess;
  50429. }(BABYLON.PostProcess));
  50430. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  50431. })(BABYLON || (BABYLON = {}));
  50432. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  50433. var BABYLON;
  50434. (function (BABYLON) {
  50435. var ConvolutionPostProcess = (function (_super) {
  50436. __extends(ConvolutionPostProcess, _super);
  50437. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  50438. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  50439. _this.kernel = kernel;
  50440. _this.onApply = function (effect) {
  50441. effect.setFloat2("screenSize", _this.width, _this.height);
  50442. effect.setArray("kernel", _this.kernel);
  50443. };
  50444. return _this;
  50445. }
  50446. return ConvolutionPostProcess;
  50447. }(BABYLON.PostProcess));
  50448. // Statics
  50449. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  50450. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  50451. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  50452. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  50453. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  50454. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  50455. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  50456. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  50457. })(BABYLON || (BABYLON = {}));
  50458. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  50459. var BABYLON;
  50460. (function (BABYLON) {
  50461. var FilterPostProcess = (function (_super) {
  50462. __extends(FilterPostProcess, _super);
  50463. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  50464. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  50465. _this.kernelMatrix = kernelMatrix;
  50466. _this.onApply = function (effect) {
  50467. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  50468. };
  50469. return _this;
  50470. }
  50471. return FilterPostProcess;
  50472. }(BABYLON.PostProcess));
  50473. BABYLON.FilterPostProcess = FilterPostProcess;
  50474. })(BABYLON || (BABYLON = {}));
  50475. //# sourceMappingURL=babylon.filterPostProcess.js.map
  50476. var BABYLON;
  50477. (function (BABYLON) {
  50478. var FxaaPostProcess = (function (_super) {
  50479. __extends(FxaaPostProcess, _super);
  50480. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  50481. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  50482. _this.onSizeChangedObservable.add(function () {
  50483. _this.texelWidth = 1.0 / _this.width;
  50484. _this.texelHeight = 1.0 / _this.height;
  50485. });
  50486. _this.onApplyObservable.add(function (effect) {
  50487. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  50488. });
  50489. return _this;
  50490. }
  50491. return FxaaPostProcess;
  50492. }(BABYLON.PostProcess));
  50493. BABYLON.FxaaPostProcess = FxaaPostProcess;
  50494. })(BABYLON || (BABYLON = {}));
  50495. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  50496. var BABYLON;
  50497. (function (BABYLON) {
  50498. var StereoscopicInterlacePostProcess = (function (_super) {
  50499. __extends(StereoscopicInterlacePostProcess, _super);
  50500. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  50501. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  50502. _this._passedProcess = rigCameras[0]._rigPostProcess;
  50503. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50504. _this.onSizeChangedObservable.add(function () {
  50505. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  50506. });
  50507. _this.onApplyObservable.add(function (effect) {
  50508. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  50509. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  50510. });
  50511. return _this;
  50512. }
  50513. return StereoscopicInterlacePostProcess;
  50514. }(BABYLON.PostProcess));
  50515. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  50516. })(BABYLON || (BABYLON = {}));
  50517. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  50518. var BABYLON;
  50519. (function (BABYLON) {
  50520. var LensFlare = (function () {
  50521. function LensFlare(size, position, color, imgUrl, system) {
  50522. this.size = size;
  50523. this.position = position;
  50524. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  50525. this.dispose = function () {
  50526. if (this.texture) {
  50527. this.texture.dispose();
  50528. }
  50529. // Remove from scene
  50530. var index = this._system.lensFlares.indexOf(this);
  50531. this._system.lensFlares.splice(index, 1);
  50532. };
  50533. this.color = color || new BABYLON.Color3(1, 1, 1);
  50534. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  50535. this._system = system;
  50536. system.lensFlares.push(this);
  50537. }
  50538. return LensFlare;
  50539. }());
  50540. BABYLON.LensFlare = LensFlare;
  50541. })(BABYLON || (BABYLON = {}));
  50542. //# sourceMappingURL=babylon.lensFlare.js.map
  50543. var BABYLON;
  50544. (function (BABYLON) {
  50545. var LensFlareSystem = (function () {
  50546. function LensFlareSystem(name, emitter, scene) {
  50547. this.name = name;
  50548. this.lensFlares = new Array();
  50549. this.borderLimit = 300;
  50550. this.viewportBorder = 0;
  50551. this.layerMask = 0x0FFFFFFF;
  50552. this._vertexBuffers = {};
  50553. this._isEnabled = true;
  50554. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50555. this._emitter = emitter;
  50556. this.id = name;
  50557. scene.lensFlareSystems.push(this);
  50558. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  50559. var engine = scene.getEngine();
  50560. // VBO
  50561. var vertices = [];
  50562. vertices.push(1, 1);
  50563. vertices.push(-1, 1);
  50564. vertices.push(-1, -1);
  50565. vertices.push(1, -1);
  50566. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  50567. // Indices
  50568. var indices = [];
  50569. indices.push(0);
  50570. indices.push(1);
  50571. indices.push(2);
  50572. indices.push(0);
  50573. indices.push(2);
  50574. indices.push(3);
  50575. this._indexBuffer = engine.createIndexBuffer(indices);
  50576. // Effects
  50577. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  50578. }
  50579. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  50580. get: function () {
  50581. return this._isEnabled;
  50582. },
  50583. set: function (value) {
  50584. this._isEnabled = value;
  50585. },
  50586. enumerable: true,
  50587. configurable: true
  50588. });
  50589. LensFlareSystem.prototype.getScene = function () {
  50590. return this._scene;
  50591. };
  50592. LensFlareSystem.prototype.getEmitter = function () {
  50593. return this._emitter;
  50594. };
  50595. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  50596. this._emitter = newEmitter;
  50597. };
  50598. LensFlareSystem.prototype.getEmitterPosition = function () {
  50599. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  50600. };
  50601. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  50602. var position = this.getEmitterPosition();
  50603. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  50604. this._positionX = position.x;
  50605. this._positionY = position.y;
  50606. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  50607. if (this.viewportBorder > 0) {
  50608. globalViewport.x -= this.viewportBorder;
  50609. globalViewport.y -= this.viewportBorder;
  50610. globalViewport.width += this.viewportBorder * 2;
  50611. globalViewport.height += this.viewportBorder * 2;
  50612. position.x += this.viewportBorder;
  50613. position.y += this.viewportBorder;
  50614. this._positionX += this.viewportBorder;
  50615. this._positionY += this.viewportBorder;
  50616. }
  50617. if (position.z > 0) {
  50618. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  50619. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  50620. return true;
  50621. }
  50622. return true;
  50623. }
  50624. return false;
  50625. };
  50626. LensFlareSystem.prototype._isVisible = function () {
  50627. if (!this._isEnabled) {
  50628. return false;
  50629. }
  50630. var emitterPosition = this.getEmitterPosition();
  50631. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  50632. var distance = direction.length();
  50633. direction.normalize();
  50634. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  50635. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  50636. return !pickInfo.hit || pickInfo.distance > distance;
  50637. };
  50638. LensFlareSystem.prototype.render = function () {
  50639. if (!this._effect.isReady())
  50640. return false;
  50641. var engine = this._scene.getEngine();
  50642. var viewport = this._scene.activeCamera.viewport;
  50643. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  50644. // Position
  50645. if (!this.computeEffectivePosition(globalViewport)) {
  50646. return false;
  50647. }
  50648. // Visibility
  50649. if (!this._isVisible()) {
  50650. return false;
  50651. }
  50652. // Intensity
  50653. var awayX;
  50654. var awayY;
  50655. if (this._positionX < this.borderLimit + globalViewport.x) {
  50656. awayX = this.borderLimit + globalViewport.x - this._positionX;
  50657. }
  50658. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  50659. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  50660. }
  50661. else {
  50662. awayX = 0;
  50663. }
  50664. if (this._positionY < this.borderLimit + globalViewport.y) {
  50665. awayY = this.borderLimit + globalViewport.y - this._positionY;
  50666. }
  50667. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  50668. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  50669. }
  50670. else {
  50671. awayY = 0;
  50672. }
  50673. var away = (awayX > awayY) ? awayX : awayY;
  50674. away -= this.viewportBorder;
  50675. if (away > this.borderLimit) {
  50676. away = this.borderLimit;
  50677. }
  50678. var intensity = 1.0 - (away / this.borderLimit);
  50679. if (intensity < 0) {
  50680. return false;
  50681. }
  50682. if (intensity > 1.0) {
  50683. intensity = 1.0;
  50684. }
  50685. if (this.viewportBorder > 0) {
  50686. globalViewport.x += this.viewportBorder;
  50687. globalViewport.y += this.viewportBorder;
  50688. globalViewport.width -= this.viewportBorder * 2;
  50689. globalViewport.height -= this.viewportBorder * 2;
  50690. this._positionX -= this.viewportBorder;
  50691. this._positionY -= this.viewportBorder;
  50692. }
  50693. // Position
  50694. var centerX = globalViewport.x + globalViewport.width / 2;
  50695. var centerY = globalViewport.y + globalViewport.height / 2;
  50696. var distX = centerX - this._positionX;
  50697. var distY = centerY - this._positionY;
  50698. // Effects
  50699. engine.enableEffect(this._effect);
  50700. engine.setState(false);
  50701. engine.setDepthBuffer(false);
  50702. // VBOs
  50703. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50704. // Flares
  50705. for (var index = 0; index < this.lensFlares.length; index++) {
  50706. var flare = this.lensFlares[index];
  50707. engine.setAlphaMode(flare.alphaMode);
  50708. var x = centerX - (distX * flare.position);
  50709. var y = centerY - (distY * flare.position);
  50710. var cw = flare.size;
  50711. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  50712. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  50713. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  50714. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  50715. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  50716. // Texture
  50717. this._effect.setTexture("textureSampler", flare.texture);
  50718. // Color
  50719. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  50720. // Draw order
  50721. engine.draw(true, 0, 6);
  50722. }
  50723. engine.setDepthBuffer(true);
  50724. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50725. return true;
  50726. };
  50727. LensFlareSystem.prototype.dispose = function () {
  50728. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50729. if (vertexBuffer) {
  50730. vertexBuffer.dispose();
  50731. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50732. }
  50733. if (this._indexBuffer) {
  50734. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50735. this._indexBuffer = null;
  50736. }
  50737. while (this.lensFlares.length) {
  50738. this.lensFlares[0].dispose();
  50739. }
  50740. // Remove from scene
  50741. var index = this._scene.lensFlareSystems.indexOf(this);
  50742. this._scene.lensFlareSystems.splice(index, 1);
  50743. };
  50744. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  50745. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  50746. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  50747. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  50748. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  50749. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  50750. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  50751. var parsedFlare = parsedLensFlareSystem.flares[index];
  50752. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  50753. }
  50754. return lensFlareSystem;
  50755. };
  50756. LensFlareSystem.prototype.serialize = function () {
  50757. var serializationObject = {};
  50758. serializationObject.id = this.id;
  50759. serializationObject.name = this.name;
  50760. serializationObject.emitterId = this.getEmitter().id;
  50761. serializationObject.borderLimit = this.borderLimit;
  50762. serializationObject.flares = [];
  50763. for (var index = 0; index < this.lensFlares.length; index++) {
  50764. var flare = this.lensFlares[index];
  50765. serializationObject.flares.push({
  50766. size: flare.size,
  50767. position: flare.position,
  50768. color: flare.color.asArray(),
  50769. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  50770. });
  50771. }
  50772. return serializationObject;
  50773. };
  50774. return LensFlareSystem;
  50775. }());
  50776. BABYLON.LensFlareSystem = LensFlareSystem;
  50777. })(BABYLON || (BABYLON = {}));
  50778. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  50779. /// <reference path="babylon.freeCamera.ts" />
  50780. var BABYLON;
  50781. (function (BABYLON) {
  50782. // We're mainly based on the logic defined into the FreeCamera code
  50783. var DeviceOrientationCamera = (function (_super) {
  50784. __extends(DeviceOrientationCamera, _super);
  50785. function DeviceOrientationCamera(name, position, scene) {
  50786. var _this = _super.call(this, name, position, scene) || this;
  50787. _this._quaternionCache = new BABYLON.Quaternion();
  50788. _this.inputs.addDeviceOrientation();
  50789. return _this;
  50790. }
  50791. DeviceOrientationCamera.prototype.getClassName = function () {
  50792. return "DeviceOrientationCamera";
  50793. };
  50794. DeviceOrientationCamera.prototype._checkInputs = function () {
  50795. _super.prototype._checkInputs.call(this);
  50796. this._quaternionCache.copyFrom(this.rotationQuaternion);
  50797. if (this._initialQuaternion) {
  50798. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50799. }
  50800. };
  50801. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  50802. var _this = this;
  50803. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  50804. //can only work if this camera has a rotation quaternion already.
  50805. if (!this.rotationQuaternion)
  50806. return;
  50807. if (!this._initialQuaternion) {
  50808. this._initialQuaternion = new BABYLON.Quaternion();
  50809. }
  50810. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  50811. ['x', 'y', 'z'].forEach(function (axisName) {
  50812. if (!axis[axisName]) {
  50813. _this._initialQuaternion[axisName] = 0;
  50814. }
  50815. else {
  50816. _this._initialQuaternion[axisName] *= -1;
  50817. }
  50818. });
  50819. this._initialQuaternion.normalize();
  50820. //force rotation update
  50821. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  50822. };
  50823. return DeviceOrientationCamera;
  50824. }(BABYLON.FreeCamera));
  50825. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  50826. })(BABYLON || (BABYLON = {}));
  50827. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  50828. var BABYLON;
  50829. (function (BABYLON) {
  50830. var VRDeviceOrientationFreeCamera = (function (_super) {
  50831. __extends(VRDeviceOrientationFreeCamera, _super);
  50832. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50833. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50834. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50835. var _this = _super.call(this, name, position, scene) || this;
  50836. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50837. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50838. return _this;
  50839. }
  50840. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  50841. return "VRDeviceOrientationFreeCamera";
  50842. };
  50843. return VRDeviceOrientationFreeCamera;
  50844. }(BABYLON.DeviceOrientationCamera));
  50845. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  50846. var VRDeviceOrientationGamepadCamera = (function (_super) {
  50847. __extends(VRDeviceOrientationGamepadCamera, _super);
  50848. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  50849. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50850. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50851. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  50852. _this.inputs.addGamepad();
  50853. return _this;
  50854. }
  50855. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  50856. return "VRDeviceOrientationGamepadCamera";
  50857. };
  50858. return VRDeviceOrientationGamepadCamera;
  50859. }(VRDeviceOrientationFreeCamera));
  50860. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  50861. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  50862. __extends(VRDeviceOrientationArcRotateCamera, _super);
  50863. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  50864. if (compensateDistortion === void 0) { compensateDistortion = true; }
  50865. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  50866. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  50867. vrCameraMetrics.compensateDistortion = compensateDistortion;
  50868. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  50869. _this.inputs.addVRDeviceOrientation();
  50870. return _this;
  50871. }
  50872. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  50873. return "VRDeviceOrientationArcRotateCamera";
  50874. };
  50875. return VRDeviceOrientationArcRotateCamera;
  50876. }(BABYLON.ArcRotateCamera));
  50877. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  50878. })(BABYLON || (BABYLON = {}));
  50879. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  50880. /// <reference path="babylon.touchCamera.ts" />
  50881. var BABYLON;
  50882. (function (BABYLON) {
  50883. // We're mainly based on the logic defined into the FreeCamera code
  50884. var UniversalCamera = (function (_super) {
  50885. __extends(UniversalCamera, _super);
  50886. //-- end properties for backward compatibility for inputs
  50887. function UniversalCamera(name, position, scene) {
  50888. var _this = _super.call(this, name, position, scene) || this;
  50889. _this.inputs.addGamepad();
  50890. return _this;
  50891. }
  50892. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  50893. //-- Begin properties for backward compatibility for inputs
  50894. get: function () {
  50895. var gamepad = this.inputs.attached["gamepad"];
  50896. if (gamepad)
  50897. return gamepad.gamepadAngularSensibility;
  50898. },
  50899. set: function (value) {
  50900. var gamepad = this.inputs.attached["gamepad"];
  50901. if (gamepad)
  50902. gamepad.gamepadAngularSensibility = value;
  50903. },
  50904. enumerable: true,
  50905. configurable: true
  50906. });
  50907. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  50908. get: function () {
  50909. var gamepad = this.inputs.attached["gamepad"];
  50910. if (gamepad)
  50911. return gamepad.gamepadMoveSensibility;
  50912. },
  50913. set: function (value) {
  50914. var gamepad = this.inputs.attached["gamepad"];
  50915. if (gamepad)
  50916. gamepad.gamepadMoveSensibility = value;
  50917. },
  50918. enumerable: true,
  50919. configurable: true
  50920. });
  50921. UniversalCamera.prototype.getClassName = function () {
  50922. return "UniversalCamera";
  50923. };
  50924. return UniversalCamera;
  50925. }(BABYLON.TouchCamera));
  50926. BABYLON.UniversalCamera = UniversalCamera;
  50927. })(BABYLON || (BABYLON = {}));
  50928. //# sourceMappingURL=babylon.universalCamera.js.map
  50929. var BABYLON;
  50930. (function (BABYLON) {
  50931. var Gamepads = (function () {
  50932. function Gamepads(ongamedpadconnected) {
  50933. var _this = this;
  50934. this.babylonGamepads = [];
  50935. this.oneGamepadConnected = false;
  50936. this.isMonitoring = false;
  50937. this.gamepadEventSupported = 'GamepadEvent' in window;
  50938. this.gamepadSupport = (navigator.getGamepads ||
  50939. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50940. this._callbackGamepadConnected = ongamedpadconnected;
  50941. if (this.gamepadSupport) {
  50942. //first add already-connected gamepads
  50943. this._updateGamepadObjects();
  50944. if (this.babylonGamepads.length) {
  50945. this._startMonitoringGamepads();
  50946. }
  50947. // Checking if the gamepad connected event is supported (like in Firefox)
  50948. if (this.gamepadEventSupported) {
  50949. this._onGamepadConnectedEvent = function (evt) {
  50950. _this._onGamepadConnected(evt.gamepad);
  50951. };
  50952. this._onGamepadDisonnectedEvent = function (evt) {
  50953. _this._onGamepadDisconnected(evt);
  50954. };
  50955. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50956. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50957. }
  50958. else {
  50959. this._startMonitoringGamepads();
  50960. }
  50961. }
  50962. }
  50963. Gamepads.prototype.dispose = function () {
  50964. if (Gamepads.gamepadDOMInfo) {
  50965. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50966. }
  50967. if (this._onGamepadConnectedEvent) {
  50968. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50969. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  50970. this._onGamepadConnectedEvent = null;
  50971. this._onGamepadDisonnectedEvent = null;
  50972. }
  50973. };
  50974. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  50975. var newGamepad = this._addNewGamepad(gamepad);
  50976. if (this._callbackGamepadConnected)
  50977. this._callbackGamepadConnected(newGamepad);
  50978. this._startMonitoringGamepads();
  50979. };
  50980. Gamepads.prototype._addNewGamepad = function (gamepad) {
  50981. if (!this.oneGamepadConnected) {
  50982. this.oneGamepadConnected = true;
  50983. if (Gamepads.gamepadDOMInfo) {
  50984. document.body.removeChild(Gamepads.gamepadDOMInfo);
  50985. Gamepads.gamepadDOMInfo = null;
  50986. }
  50987. }
  50988. var newGamepad;
  50989. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  50990. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50991. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  50992. }
  50993. else if (gamepad.pose) {
  50994. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  50995. }
  50996. else {
  50997. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  50998. }
  50999. this.babylonGamepads.push(newGamepad);
  51000. return newGamepad;
  51001. };
  51002. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  51003. // Remove the gamepad from the list of gamepads to monitor.
  51004. for (var i in this.babylonGamepads) {
  51005. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  51006. this.babylonGamepads.splice(+i, 1);
  51007. break;
  51008. }
  51009. }
  51010. // If no gamepads are left, stop the polling loop.
  51011. if (this.babylonGamepads.length == 0) {
  51012. this._stopMonitoringGamepads();
  51013. }
  51014. };
  51015. Gamepads.prototype._startMonitoringGamepads = function () {
  51016. if (!this.isMonitoring) {
  51017. this.isMonitoring = true;
  51018. this._checkGamepadsStatus();
  51019. }
  51020. };
  51021. Gamepads.prototype._stopMonitoringGamepads = function () {
  51022. this.isMonitoring = false;
  51023. };
  51024. Gamepads.prototype._checkGamepadsStatus = function () {
  51025. var _this = this;
  51026. // updating gamepad objects
  51027. this._updateGamepadObjects();
  51028. for (var i in this.babylonGamepads) {
  51029. this.babylonGamepads[i].update();
  51030. }
  51031. if (this.isMonitoring) {
  51032. if (window.requestAnimationFrame) {
  51033. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  51034. }
  51035. else if (window.mozRequestAnimationFrame) {
  51036. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  51037. }
  51038. else if (window.webkitRequestAnimationFrame) {
  51039. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  51040. }
  51041. }
  51042. };
  51043. // This function is called only on Chrome, which does not yet support
  51044. // connection/disconnection events, but requires you to monitor
  51045. // an array for changes.
  51046. Gamepads.prototype._updateGamepadObjects = function () {
  51047. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  51048. for (var i = 0; i < gamepads.length; i++) {
  51049. if (gamepads[i]) {
  51050. if (!(gamepads[i].index in this.babylonGamepads)) {
  51051. var newGamepad = this._addNewGamepad(gamepads[i]);
  51052. if (this._callbackGamepadConnected) {
  51053. this._callbackGamepadConnected(newGamepad);
  51054. }
  51055. }
  51056. else {
  51057. this.babylonGamepads[i].browserGamepad = gamepads[i];
  51058. }
  51059. }
  51060. }
  51061. };
  51062. return Gamepads;
  51063. }());
  51064. BABYLON.Gamepads = Gamepads;
  51065. var StickValues = (function () {
  51066. function StickValues(x, y) {
  51067. this.x = x;
  51068. this.y = y;
  51069. }
  51070. return StickValues;
  51071. }());
  51072. BABYLON.StickValues = StickValues;
  51073. var Gamepad = (function () {
  51074. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  51075. if (leftStickX === void 0) { leftStickX = 0; }
  51076. if (leftStickY === void 0) { leftStickY = 1; }
  51077. if (rightStickX === void 0) { rightStickX = 2; }
  51078. if (rightStickY === void 0) { rightStickY = 3; }
  51079. this.id = id;
  51080. this.index = index;
  51081. this.browserGamepad = browserGamepad;
  51082. this.type = Gamepad.GAMEPAD;
  51083. this._leftStickAxisX = leftStickX;
  51084. this._leftStickAxisY = leftStickY;
  51085. this._rightStickAxisX = rightStickX;
  51086. this._rightStickAxisY = rightStickY;
  51087. if (this.browserGamepad.axes.length >= 2) {
  51088. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51089. }
  51090. if (this.browserGamepad.axes.length >= 4) {
  51091. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51092. }
  51093. }
  51094. Gamepad.prototype.onleftstickchanged = function (callback) {
  51095. this._onleftstickchanged = callback;
  51096. };
  51097. Gamepad.prototype.onrightstickchanged = function (callback) {
  51098. this._onrightstickchanged = callback;
  51099. };
  51100. Object.defineProperty(Gamepad.prototype, "leftStick", {
  51101. get: function () {
  51102. return this._leftStick;
  51103. },
  51104. set: function (newValues) {
  51105. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  51106. this._onleftstickchanged(newValues);
  51107. }
  51108. this._leftStick = newValues;
  51109. },
  51110. enumerable: true,
  51111. configurable: true
  51112. });
  51113. Object.defineProperty(Gamepad.prototype, "rightStick", {
  51114. get: function () {
  51115. return this._rightStick;
  51116. },
  51117. set: function (newValues) {
  51118. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  51119. this._onrightstickchanged(newValues);
  51120. }
  51121. this._rightStick = newValues;
  51122. },
  51123. enumerable: true,
  51124. configurable: true
  51125. });
  51126. Gamepad.prototype.update = function () {
  51127. if (this._leftStick) {
  51128. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  51129. }
  51130. if (this._rightStick) {
  51131. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  51132. }
  51133. };
  51134. return Gamepad;
  51135. }());
  51136. Gamepad.GAMEPAD = 0;
  51137. Gamepad.GENERIC = 1;
  51138. Gamepad.XBOX = 2;
  51139. Gamepad.POSE_ENABLED = 3;
  51140. BABYLON.Gamepad = Gamepad;
  51141. var GenericPad = (function (_super) {
  51142. __extends(GenericPad, _super);
  51143. function GenericPad(id, index, gamepad) {
  51144. var _this = _super.call(this, id, index, gamepad) || this;
  51145. _this.id = id;
  51146. _this.index = index;
  51147. _this.gamepad = gamepad;
  51148. _this.type = Gamepad.GENERIC;
  51149. _this._buttons = new Array(gamepad.buttons.length);
  51150. return _this;
  51151. }
  51152. GenericPad.prototype.onbuttondown = function (callback) {
  51153. this._onbuttondown = callback;
  51154. };
  51155. GenericPad.prototype.onbuttonup = function (callback) {
  51156. this._onbuttonup = callback;
  51157. };
  51158. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  51159. if (newValue !== currentValue) {
  51160. if (this._onbuttondown && newValue === 1) {
  51161. this._onbuttondown(buttonIndex);
  51162. }
  51163. if (this._onbuttonup && newValue === 0) {
  51164. this._onbuttonup(buttonIndex);
  51165. }
  51166. }
  51167. return newValue;
  51168. };
  51169. GenericPad.prototype.update = function () {
  51170. _super.prototype.update.call(this);
  51171. for (var index = 0; index < this._buttons.length; index++) {
  51172. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  51173. }
  51174. };
  51175. return GenericPad;
  51176. }(Gamepad));
  51177. BABYLON.GenericPad = GenericPad;
  51178. var Xbox360Button;
  51179. (function (Xbox360Button) {
  51180. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  51181. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  51182. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  51183. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  51184. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  51185. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  51186. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  51187. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  51188. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  51189. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  51190. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  51191. var Xbox360Dpad;
  51192. (function (Xbox360Dpad) {
  51193. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  51194. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  51195. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  51196. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  51197. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  51198. var Xbox360Pad = (function (_super) {
  51199. __extends(Xbox360Pad, _super);
  51200. function Xbox360Pad(id, index, gamepad, xboxOne) {
  51201. if (xboxOne === void 0) { xboxOne = false; }
  51202. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  51203. _this._leftTrigger = 0;
  51204. _this._rightTrigger = 0;
  51205. _this._buttonA = 0;
  51206. _this._buttonB = 0;
  51207. _this._buttonX = 0;
  51208. _this._buttonY = 0;
  51209. _this._buttonBack = 0;
  51210. _this._buttonStart = 0;
  51211. _this._buttonLB = 0;
  51212. _this._buttonRB = 0;
  51213. _this._buttonLeftStick = 0;
  51214. _this._buttonRightStick = 0;
  51215. _this._dPadUp = 0;
  51216. _this._dPadDown = 0;
  51217. _this._dPadLeft = 0;
  51218. _this._dPadRight = 0;
  51219. _this._isXboxOnePad = false;
  51220. _this.type = Gamepad.XBOX;
  51221. _this._isXboxOnePad = xboxOne;
  51222. return _this;
  51223. }
  51224. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  51225. this._onlefttriggerchanged = callback;
  51226. };
  51227. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  51228. this._onrighttriggerchanged = callback;
  51229. };
  51230. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  51231. get: function () {
  51232. return this._leftTrigger;
  51233. },
  51234. set: function (newValue) {
  51235. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  51236. this._onlefttriggerchanged(newValue);
  51237. }
  51238. this._leftTrigger = newValue;
  51239. },
  51240. enumerable: true,
  51241. configurable: true
  51242. });
  51243. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  51244. get: function () {
  51245. return this._rightTrigger;
  51246. },
  51247. set: function (newValue) {
  51248. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  51249. this._onrighttriggerchanged(newValue);
  51250. }
  51251. this._rightTrigger = newValue;
  51252. },
  51253. enumerable: true,
  51254. configurable: true
  51255. });
  51256. Xbox360Pad.prototype.onbuttondown = function (callback) {
  51257. this._onbuttondown = callback;
  51258. };
  51259. Xbox360Pad.prototype.onbuttonup = function (callback) {
  51260. this._onbuttonup = callback;
  51261. };
  51262. Xbox360Pad.prototype.ondpaddown = function (callback) {
  51263. this._ondpaddown = callback;
  51264. };
  51265. Xbox360Pad.prototype.ondpadup = function (callback) {
  51266. this._ondpadup = callback;
  51267. };
  51268. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  51269. if (newValue !== currentValue) {
  51270. if (this._onbuttondown && newValue === 1) {
  51271. this._onbuttondown(buttonType);
  51272. }
  51273. if (this._onbuttonup && newValue === 0) {
  51274. this._onbuttonup(buttonType);
  51275. }
  51276. }
  51277. return newValue;
  51278. };
  51279. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  51280. if (newValue !== currentValue) {
  51281. if (this._ondpaddown && newValue === 1) {
  51282. this._ondpaddown(buttonType);
  51283. }
  51284. if (this._ondpadup && newValue === 0) {
  51285. this._ondpadup(buttonType);
  51286. }
  51287. }
  51288. return newValue;
  51289. };
  51290. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  51291. get: function () {
  51292. return this._buttonA;
  51293. },
  51294. set: function (value) {
  51295. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  51296. },
  51297. enumerable: true,
  51298. configurable: true
  51299. });
  51300. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  51301. get: function () {
  51302. return this._buttonB;
  51303. },
  51304. set: function (value) {
  51305. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  51306. },
  51307. enumerable: true,
  51308. configurable: true
  51309. });
  51310. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  51311. get: function () {
  51312. return this._buttonX;
  51313. },
  51314. set: function (value) {
  51315. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  51316. },
  51317. enumerable: true,
  51318. configurable: true
  51319. });
  51320. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  51321. get: function () {
  51322. return this._buttonY;
  51323. },
  51324. set: function (value) {
  51325. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  51326. },
  51327. enumerable: true,
  51328. configurable: true
  51329. });
  51330. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  51331. get: function () {
  51332. return this._buttonStart;
  51333. },
  51334. set: function (value) {
  51335. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  51336. },
  51337. enumerable: true,
  51338. configurable: true
  51339. });
  51340. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  51341. get: function () {
  51342. return this._buttonBack;
  51343. },
  51344. set: function (value) {
  51345. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  51346. },
  51347. enumerable: true,
  51348. configurable: true
  51349. });
  51350. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  51351. get: function () {
  51352. return this._buttonLB;
  51353. },
  51354. set: function (value) {
  51355. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  51356. },
  51357. enumerable: true,
  51358. configurable: true
  51359. });
  51360. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  51361. get: function () {
  51362. return this._buttonRB;
  51363. },
  51364. set: function (value) {
  51365. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  51366. },
  51367. enumerable: true,
  51368. configurable: true
  51369. });
  51370. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  51371. get: function () {
  51372. return this._buttonLeftStick;
  51373. },
  51374. set: function (value) {
  51375. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  51376. },
  51377. enumerable: true,
  51378. configurable: true
  51379. });
  51380. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  51381. get: function () {
  51382. return this._buttonRightStick;
  51383. },
  51384. set: function (value) {
  51385. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  51386. },
  51387. enumerable: true,
  51388. configurable: true
  51389. });
  51390. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  51391. get: function () {
  51392. return this._dPadUp;
  51393. },
  51394. set: function (value) {
  51395. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  51396. },
  51397. enumerable: true,
  51398. configurable: true
  51399. });
  51400. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  51401. get: function () {
  51402. return this._dPadDown;
  51403. },
  51404. set: function (value) {
  51405. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  51406. },
  51407. enumerable: true,
  51408. configurable: true
  51409. });
  51410. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  51411. get: function () {
  51412. return this._dPadLeft;
  51413. },
  51414. set: function (value) {
  51415. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  51416. },
  51417. enumerable: true,
  51418. configurable: true
  51419. });
  51420. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  51421. get: function () {
  51422. return this._dPadRight;
  51423. },
  51424. set: function (value) {
  51425. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  51426. },
  51427. enumerable: true,
  51428. configurable: true
  51429. });
  51430. Xbox360Pad.prototype.update = function () {
  51431. _super.prototype.update.call(this);
  51432. if (this._isXboxOnePad) {
  51433. this.buttonA = this.browserGamepad.buttons[0].value;
  51434. this.buttonB = this.browserGamepad.buttons[1].value;
  51435. this.buttonX = this.browserGamepad.buttons[2].value;
  51436. this.buttonY = this.browserGamepad.buttons[3].value;
  51437. this.buttonLB = this.browserGamepad.buttons[4].value;
  51438. this.buttonRB = this.browserGamepad.buttons[5].value;
  51439. this.leftTrigger = this.browserGamepad.axes[2];
  51440. this.rightTrigger = this.browserGamepad.axes[5];
  51441. this.buttonBack = this.browserGamepad.buttons[9].value;
  51442. this.buttonStart = this.browserGamepad.buttons[8].value;
  51443. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  51444. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  51445. this.dPadUp = this.browserGamepad.buttons[11].value;
  51446. this.dPadDown = this.browserGamepad.buttons[12].value;
  51447. this.dPadLeft = this.browserGamepad.buttons[13].value;
  51448. this.dPadRight = this.browserGamepad.buttons[14].value;
  51449. }
  51450. else {
  51451. this.buttonA = this.browserGamepad.buttons[0].value;
  51452. this.buttonB = this.browserGamepad.buttons[1].value;
  51453. this.buttonX = this.browserGamepad.buttons[2].value;
  51454. this.buttonY = this.browserGamepad.buttons[3].value;
  51455. this.buttonLB = this.browserGamepad.buttons[4].value;
  51456. this.buttonRB = this.browserGamepad.buttons[5].value;
  51457. this.leftTrigger = this.browserGamepad.buttons[6].value;
  51458. this.rightTrigger = this.browserGamepad.buttons[7].value;
  51459. this.buttonBack = this.browserGamepad.buttons[8].value;
  51460. this.buttonStart = this.browserGamepad.buttons[9].value;
  51461. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  51462. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  51463. this.dPadUp = this.browserGamepad.buttons[12].value;
  51464. this.dPadDown = this.browserGamepad.buttons[13].value;
  51465. this.dPadLeft = this.browserGamepad.buttons[14].value;
  51466. this.dPadRight = this.browserGamepad.buttons[15].value;
  51467. }
  51468. };
  51469. return Xbox360Pad;
  51470. }(Gamepad));
  51471. BABYLON.Xbox360Pad = Xbox360Pad;
  51472. })(BABYLON || (BABYLON = {}));
  51473. //# sourceMappingURL=babylon.gamepads.js.map
  51474. var BABYLON;
  51475. (function (BABYLON) {
  51476. var PoseEnabledControllerType;
  51477. (function (PoseEnabledControllerType) {
  51478. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  51479. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  51480. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  51481. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  51482. var PoseEnabledControllerHelper = (function () {
  51483. function PoseEnabledControllerHelper() {
  51484. }
  51485. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  51486. // for now, only Oculus and Vive are supported
  51487. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  51488. return new OculusTouchController(vrGamepad);
  51489. }
  51490. else {
  51491. return new ViveController(vrGamepad);
  51492. }
  51493. };
  51494. return PoseEnabledControllerHelper;
  51495. }());
  51496. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  51497. var PoseEnabledController = (function (_super) {
  51498. __extends(PoseEnabledController, _super);
  51499. function PoseEnabledController(vrGamepad) {
  51500. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  51501. _this.vrGamepad = vrGamepad;
  51502. _this.deviceScaleFactor = 1;
  51503. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  51504. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  51505. _this.controllerType = PoseEnabledControllerType.GENERIC;
  51506. _this.position = BABYLON.Vector3.Zero();
  51507. _this.rotationQuaternion = new BABYLON.Quaternion();
  51508. _this.devicePosition = BABYLON.Vector3.Zero();
  51509. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  51510. _this._calculatedPosition = BABYLON.Vector3.Zero();
  51511. _this._calculatedRotation = new BABYLON.Quaternion();
  51512. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  51513. return _this;
  51514. }
  51515. PoseEnabledController.prototype.update = function () {
  51516. _super.prototype.update.call(this);
  51517. // update this device's offset position from the attached camera, if provided
  51518. //if (this._poseControlledCamera && this._poseControlledCamera.deviceScaleFactor) {
  51519. //this.position.copyFrom(this._poseControlledCamera.position);
  51520. //this.rotationQuaternion.copyFrom(this._poseControlledCamera.rotationQuaternion);
  51521. //this.deviceScaleFactor = this._poseControlledCamera.deviceScaleFactor;
  51522. //}
  51523. var pose = this.vrGamepad.pose;
  51524. this.updateFromDevice(pose);
  51525. if (this._mesh) {
  51526. this._mesh.position.copyFrom(this._calculatedPosition);
  51527. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  51528. }
  51529. };
  51530. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  51531. if (poseData) {
  51532. this.rawPose = poseData;
  51533. if (poseData.position) {
  51534. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  51535. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  51536. this.devicePosition.z *= -1;
  51537. }
  51538. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  51539. this._calculatedPosition.addInPlace(this.position);
  51540. // scale the position using the scale factor, add the device's position
  51541. /*if (this._poseControlledCamera) {
  51542. // this allows total positioning freedom - the device, the camera and the mesh can be individually controlled.
  51543. this._calculatedPosition.addInPlace(this._poseControlledCamera.position);
  51544. }*/
  51545. }
  51546. if (poseData.orientation) {
  51547. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  51548. if (this._mesh) {
  51549. if (this._mesh.getScene().useRightHandedSystem) {
  51550. this.deviceRotationQuaternion.z *= -1;
  51551. this.deviceRotationQuaternion.w *= -1;
  51552. }
  51553. else {
  51554. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  51555. }
  51556. }
  51557. // if the camera is set, rotate to the camera's rotation
  51558. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  51559. /*if (this._poseControlledCamera) {
  51560. Matrix.ScalingToRef(1, 1, 1, Tmp.Matrix[1]);
  51561. this._calculatedRotation.toRotationMatrix(Tmp.Matrix[0]);
  51562. Matrix.TranslationToRef(this._calculatedPosition.x, this._calculatedPosition.y, this._calculatedPosition.z, Tmp.Matrix[2]);
  51563. //Matrix.Identity().multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  51564. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  51565. this._poseControlledCamera.getWorldMatrix().getTranslationToRef(Tmp.Vector3[0])
  51566. Matrix.ComposeToRef(new Vector3(this.deviceScaleFactor, this.deviceScaleFactor, this.deviceScaleFactor), this._poseControlledCamera.rotationQuaternion, Tmp.Vector3[0], Tmp.Matrix[4]);
  51567. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], Tmp.Matrix[1]);
  51568. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[4], Tmp.Matrix[2]);
  51569. Tmp.Matrix[2].decompose(Tmp.Vector3[0], this._calculatedRotation, this._calculatedPosition);
  51570. }*/
  51571. }
  51572. }
  51573. };
  51574. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  51575. if (this._mesh) {
  51576. this._mesh.parent = undefined;
  51577. }
  51578. this._mesh = mesh;
  51579. if (this._poseControlledCamera) {
  51580. this._mesh.parent = this._poseControlledCamera;
  51581. }
  51582. if (!this._mesh.rotationQuaternion) {
  51583. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  51584. }
  51585. };
  51586. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  51587. this._poseControlledCamera = camera;
  51588. if (this._mesh) {
  51589. this._mesh.parent = this._poseControlledCamera;
  51590. }
  51591. };
  51592. PoseEnabledController.prototype.detachMesh = function () {
  51593. this._mesh = undefined;
  51594. };
  51595. return PoseEnabledController;
  51596. }(BABYLON.Gamepad));
  51597. BABYLON.PoseEnabledController = PoseEnabledController;
  51598. var WebVRController = (function (_super) {
  51599. __extends(WebVRController, _super);
  51600. function WebVRController(vrGamepad) {
  51601. var _this = _super.call(this, vrGamepad) || this;
  51602. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  51603. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51604. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51605. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51606. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51607. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51608. _this.pad = { x: 0, y: 0 };
  51609. // avoid GC, store state in a tmp object
  51610. _this._changes = {
  51611. pressChanged: false,
  51612. touchChanged: false,
  51613. valueChanged: false,
  51614. changed: false
  51615. };
  51616. _this._buttons = new Array(vrGamepad.buttons.length);
  51617. _this.hand = vrGamepad.hand;
  51618. return _this;
  51619. }
  51620. WebVRController.prototype.onButtonStateChange = function (callback) {
  51621. this._onButtonStateChange = callback;
  51622. };
  51623. WebVRController.prototype.update = function () {
  51624. _super.prototype.update.call(this);
  51625. for (var index = 0; index < this._buttons.length; index++) {
  51626. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51627. }
  51628. ;
  51629. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51630. this.pad.x = this.leftStick.x;
  51631. this.pad.y = this.leftStick.y;
  51632. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51633. }
  51634. };
  51635. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51636. if (!currentState) {
  51637. this._buttons[buttonIndex] = {
  51638. pressed: newState.pressed,
  51639. touched: newState.touched,
  51640. value: newState.value
  51641. };
  51642. return;
  51643. }
  51644. this._checkChanges(newState, currentState);
  51645. if (this._changes.changed) {
  51646. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51647. this.handleButtonChange(buttonIndex, newState, this._changes);
  51648. }
  51649. this._buttons[buttonIndex].pressed = newState.pressed;
  51650. this._buttons[buttonIndex].touched = newState.touched;
  51651. // oculus triggers are never 0, thou not touched.
  51652. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51653. };
  51654. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51655. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51656. this._changes.touchChanged = newState.touched !== currentState.touched;
  51657. this._changes.valueChanged = newState.value !== currentState.value;
  51658. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51659. return this._changes;
  51660. };
  51661. return WebVRController;
  51662. }(PoseEnabledController));
  51663. BABYLON.WebVRController = WebVRController;
  51664. var OculusTouchController = (function (_super) {
  51665. __extends(OculusTouchController, _super);
  51666. function OculusTouchController(vrGamepad) {
  51667. var _this = _super.call(this, vrGamepad) || this;
  51668. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51669. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51670. _this.controllerType = PoseEnabledControllerType.OCULUS;
  51671. return _this;
  51672. }
  51673. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51674. var _this = this;
  51675. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51676. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51677. /*
  51678. Parent Mesh name: oculus_touch_left
  51679. - body
  51680. - trigger
  51681. - thumbstick
  51682. - grip
  51683. - button_y
  51684. - button_x
  51685. - button_enter
  51686. */
  51687. _this._defaultModel = newMeshes[1];
  51688. if (meshLoaded) {
  51689. meshLoaded(_this._defaultModel);
  51690. }
  51691. _this.attachToMesh(_this._defaultModel);
  51692. });
  51693. };
  51694. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51695. // helper getters for left and right hand.
  51696. get: function () {
  51697. if (this.hand === 'right') {
  51698. return this.onMainButtonStateChangedObservable;
  51699. }
  51700. else {
  51701. throw new Error('No A button on left hand');
  51702. }
  51703. },
  51704. enumerable: true,
  51705. configurable: true
  51706. });
  51707. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51708. get: function () {
  51709. if (this.hand === 'right') {
  51710. return this.onSecondaryButtonStateChangedObservable;
  51711. }
  51712. else {
  51713. throw new Error('No B button on left hand');
  51714. }
  51715. },
  51716. enumerable: true,
  51717. configurable: true
  51718. });
  51719. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51720. get: function () {
  51721. if (this.hand === 'left') {
  51722. return this.onMainButtonStateChangedObservable;
  51723. }
  51724. else {
  51725. throw new Error('No X button on right hand');
  51726. }
  51727. },
  51728. enumerable: true,
  51729. configurable: true
  51730. });
  51731. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51732. get: function () {
  51733. if (this.hand === 'left') {
  51734. return this.onSecondaryButtonStateChangedObservable;
  51735. }
  51736. else {
  51737. throw new Error('No Y button on right hand');
  51738. }
  51739. },
  51740. enumerable: true,
  51741. configurable: true
  51742. });
  51743. /*
  51744. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51745. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51746. 2) secondary trigger (same)
  51747. 3) A (right) X (left), touch, pressed = value
  51748. 4) B / Y
  51749. 5) thumb rest
  51750. */
  51751. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51752. var notifyObject = state; //{ state: state, changes: changes };
  51753. switch (buttonIdx) {
  51754. case 0:
  51755. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51756. return;
  51757. case 1:
  51758. if (this._defaultModel) {
  51759. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51760. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51761. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51762. }
  51763. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51764. return;
  51765. case 2:
  51766. if (this._defaultModel) {
  51767. (this._defaultModel.getChildren()[4]).position.x = notifyObject.value * 0.0035;
  51768. }
  51769. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51770. return;
  51771. case 3:
  51772. if (this._defaultModel) {
  51773. if (notifyObject.pressed) {
  51774. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51775. }
  51776. else {
  51777. (this._defaultModel.getChildren()[1]).position.y = 0;
  51778. }
  51779. }
  51780. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51781. return;
  51782. case 4:
  51783. if (this._defaultModel) {
  51784. if (notifyObject.pressed) {
  51785. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51786. }
  51787. else {
  51788. (this._defaultModel.getChildren()[2]).position.y = 0;
  51789. }
  51790. }
  51791. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51792. return;
  51793. case 5:
  51794. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51795. return;
  51796. }
  51797. };
  51798. return OculusTouchController;
  51799. }(WebVRController));
  51800. BABYLON.OculusTouchController = OculusTouchController;
  51801. var ViveController = (function (_super) {
  51802. __extends(ViveController, _super);
  51803. function ViveController(vrGamepad) {
  51804. var _this = _super.call(this, vrGamepad) || this;
  51805. _this.controllerType = PoseEnabledControllerType.VIVE;
  51806. return _this;
  51807. }
  51808. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51809. var _this = this;
  51810. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  51811. /*
  51812. Parent Mesh name: ViveWand
  51813. - body
  51814. - r_gripper
  51815. - l_gripper
  51816. - menu_button
  51817. - system_button
  51818. - trackpad
  51819. - trigger
  51820. - LED
  51821. */
  51822. _this._defaultModel = newMeshes[1];
  51823. if (meshLoaded) {
  51824. meshLoaded(_this._defaultModel);
  51825. }
  51826. _this.attachToMesh(_this._defaultModel);
  51827. });
  51828. };
  51829. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  51830. get: function () {
  51831. return this.onMainButtonStateChangedObservable;
  51832. },
  51833. enumerable: true,
  51834. configurable: true
  51835. });
  51836. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  51837. get: function () {
  51838. return this.onMainButtonStateChangedObservable;
  51839. },
  51840. enumerable: true,
  51841. configurable: true
  51842. });
  51843. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  51844. get: function () {
  51845. return this.onSecondaryButtonStateChangedObservable;
  51846. },
  51847. enumerable: true,
  51848. configurable: true
  51849. });
  51850. /**
  51851. * Vive mapping:
  51852. * 0: touchpad
  51853. * 1: trigger
  51854. * 2: left AND right buttons
  51855. * 3: menu button
  51856. */
  51857. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51858. var notifyObject = state; //{ state: state, changes: changes };
  51859. switch (buttonIdx) {
  51860. case 0:
  51861. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51862. return;
  51863. case 1:
  51864. if (this._defaultModel) {
  51865. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  51866. }
  51867. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51868. return;
  51869. case 2:
  51870. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51871. return;
  51872. case 3:
  51873. if (this._defaultModel) {
  51874. if (notifyObject.pressed) {
  51875. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51876. }
  51877. else {
  51878. (this._defaultModel.getChildren()[2]).position.y = 0;
  51879. }
  51880. }
  51881. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51882. return;
  51883. }
  51884. };
  51885. return ViveController;
  51886. }(WebVRController));
  51887. BABYLON.ViveController = ViveController;
  51888. })(BABYLON || (BABYLON = {}));
  51889. //# sourceMappingURL=babylon.extendedGamepad.js.map
  51890. /// <reference path="babylon.universalCamera.ts" />
  51891. var BABYLON;
  51892. (function (BABYLON) {
  51893. // We're mainly based on the logic defined into the FreeCamera code
  51894. var GamepadCamera = (function (_super) {
  51895. __extends(GamepadCamera, _super);
  51896. //-- end properties for backward compatibility for inputs
  51897. function GamepadCamera(name, position, scene) {
  51898. return _super.call(this, name, position, scene) || this;
  51899. }
  51900. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51901. //-- Begin properties for backward compatibility for inputs
  51902. get: function () {
  51903. var gamepad = this.inputs.attached["gamepad"];
  51904. if (gamepad)
  51905. return gamepad.gamepadAngularSensibility;
  51906. },
  51907. set: function (value) {
  51908. var gamepad = this.inputs.attached["gamepad"];
  51909. if (gamepad)
  51910. gamepad.gamepadAngularSensibility = value;
  51911. },
  51912. enumerable: true,
  51913. configurable: true
  51914. });
  51915. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51916. get: function () {
  51917. var gamepad = this.inputs.attached["gamepad"];
  51918. if (gamepad)
  51919. return gamepad.gamepadMoveSensibility;
  51920. },
  51921. set: function (value) {
  51922. var gamepad = this.inputs.attached["gamepad"];
  51923. if (gamepad)
  51924. gamepad.gamepadMoveSensibility = value;
  51925. },
  51926. enumerable: true,
  51927. configurable: true
  51928. });
  51929. GamepadCamera.prototype.getClassName = function () {
  51930. return "GamepadCamera";
  51931. };
  51932. return GamepadCamera;
  51933. }(BABYLON.UniversalCamera));
  51934. BABYLON.GamepadCamera = GamepadCamera;
  51935. })(BABYLON || (BABYLON = {}));
  51936. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51937. var BABYLON;
  51938. (function (BABYLON) {
  51939. var Analyser = (function () {
  51940. function Analyser(scene) {
  51941. this.SMOOTHING = 0.75;
  51942. this.FFT_SIZE = 512;
  51943. this.BARGRAPHAMPLITUDE = 256;
  51944. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51945. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51946. this._scene = scene;
  51947. this._audioEngine = BABYLON.Engine.audioEngine;
  51948. if (this._audioEngine.canUseWebAudio) {
  51949. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51950. this._webAudioAnalyser.minDecibels = -140;
  51951. this._webAudioAnalyser.maxDecibels = 0;
  51952. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51953. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51954. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51955. }
  51956. }
  51957. Analyser.prototype.getFrequencyBinCount = function () {
  51958. if (this._audioEngine.canUseWebAudio) {
  51959. return this._webAudioAnalyser.frequencyBinCount;
  51960. }
  51961. else {
  51962. return 0;
  51963. }
  51964. };
  51965. Analyser.prototype.getByteFrequencyData = function () {
  51966. if (this._audioEngine.canUseWebAudio) {
  51967. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51968. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51969. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51970. }
  51971. return this._byteFreqs;
  51972. };
  51973. Analyser.prototype.getByteTimeDomainData = function () {
  51974. if (this._audioEngine.canUseWebAudio) {
  51975. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51976. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51977. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51978. }
  51979. return this._byteTime;
  51980. };
  51981. Analyser.prototype.getFloatFrequencyData = function () {
  51982. if (this._audioEngine.canUseWebAudio) {
  51983. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51984. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51985. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51986. }
  51987. return this._floatFreqs;
  51988. };
  51989. Analyser.prototype.drawDebugCanvas = function () {
  51990. var _this = this;
  51991. if (this._audioEngine.canUseWebAudio) {
  51992. if (!this._debugCanvas) {
  51993. this._debugCanvas = document.createElement("canvas");
  51994. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51995. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51996. this._debugCanvas.style.position = "absolute";
  51997. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51998. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51999. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  52000. document.body.appendChild(this._debugCanvas);
  52001. this._registerFunc = function () {
  52002. _this.drawDebugCanvas();
  52003. };
  52004. this._scene.registerBeforeRender(this._registerFunc);
  52005. }
  52006. if (this._registerFunc) {
  52007. var workingArray = this.getByteFrequencyData();
  52008. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  52009. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  52010. // Draw the frequency domain chart.
  52011. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  52012. var value = workingArray[i];
  52013. var percent = value / this.BARGRAPHAMPLITUDE;
  52014. var height = this.DEBUGCANVASSIZE.height * percent;
  52015. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  52016. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  52017. var hue = i / this.getFrequencyBinCount() * 360;
  52018. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  52019. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  52020. }
  52021. }
  52022. }
  52023. };
  52024. Analyser.prototype.stopDebugCanvas = function () {
  52025. if (this._debugCanvas) {
  52026. this._scene.unregisterBeforeRender(this._registerFunc);
  52027. this._registerFunc = null;
  52028. document.body.removeChild(this._debugCanvas);
  52029. this._debugCanvas = null;
  52030. this._debugCanvasContext = null;
  52031. }
  52032. };
  52033. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  52034. if (this._audioEngine.canUseWebAudio) {
  52035. inputAudioNode.connect(this._webAudioAnalyser);
  52036. this._webAudioAnalyser.connect(outputAudioNode);
  52037. }
  52038. };
  52039. Analyser.prototype.dispose = function () {
  52040. if (this._audioEngine.canUseWebAudio) {
  52041. this._webAudioAnalyser.disconnect();
  52042. }
  52043. };
  52044. return Analyser;
  52045. }());
  52046. BABYLON.Analyser = Analyser;
  52047. })(BABYLON || (BABYLON = {}));
  52048. //# sourceMappingURL=babylon.analyser.js.map
  52049. var BABYLON;
  52050. (function (BABYLON) {
  52051. var DepthRenderer = (function () {
  52052. function DepthRenderer(scene, type) {
  52053. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  52054. var _this = this;
  52055. this._viewMatrix = BABYLON.Matrix.Zero();
  52056. this._projectionMatrix = BABYLON.Matrix.Zero();
  52057. this._transformMatrix = BABYLON.Matrix.Zero();
  52058. this._worldViewProjection = BABYLON.Matrix.Zero();
  52059. this._scene = scene;
  52060. var engine = scene.getEngine();
  52061. // Render target
  52062. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  52063. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52064. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52065. this._depthMap.refreshRate = 1;
  52066. this._depthMap.renderParticles = false;
  52067. this._depthMap.renderList = null;
  52068. // set default depth value to 1.0 (far away)
  52069. this._depthMap.onClearObservable.add(function (engine) {
  52070. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52071. });
  52072. // Custom render function
  52073. var renderSubMesh = function (subMesh) {
  52074. var mesh = subMesh.getRenderingMesh();
  52075. var scene = _this._scene;
  52076. var engine = scene.getEngine();
  52077. // Culling
  52078. engine.setState(subMesh.getMaterial().backFaceCulling);
  52079. // Managing instances
  52080. var batch = mesh._getInstancesRenderList(subMesh._id);
  52081. if (batch.mustReturn) {
  52082. return;
  52083. }
  52084. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52085. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52086. engine.enableEffect(_this._effect);
  52087. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52088. var material = subMesh.getMaterial();
  52089. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52090. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  52091. // Alpha test
  52092. if (material && material.needAlphaTesting()) {
  52093. var alphaTexture = material.getAlphaTestTexture();
  52094. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52095. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52096. }
  52097. // Bones
  52098. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52099. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52100. }
  52101. // Draw
  52102. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52103. }
  52104. };
  52105. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  52106. var index;
  52107. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52108. renderSubMesh(opaqueSubMeshes.data[index]);
  52109. }
  52110. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52111. renderSubMesh(alphaTestSubMeshes.data[index]);
  52112. }
  52113. };
  52114. }
  52115. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  52116. var material = subMesh.getMaterial();
  52117. if (material.disableDepthWrite) {
  52118. return false;
  52119. }
  52120. var defines = [];
  52121. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52122. var mesh = subMesh.getMesh();
  52123. var scene = mesh.getScene();
  52124. // Alpha test
  52125. if (material && material.needAlphaTesting()) {
  52126. defines.push("#define ALPHATEST");
  52127. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52128. attribs.push(BABYLON.VertexBuffer.UVKind);
  52129. defines.push("#define UV1");
  52130. }
  52131. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52132. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52133. defines.push("#define UV2");
  52134. }
  52135. }
  52136. // Bones
  52137. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52138. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52139. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52140. if (mesh.numBoneInfluencers > 4) {
  52141. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52142. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52143. }
  52144. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52145. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52146. }
  52147. else {
  52148. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52149. }
  52150. // Instances
  52151. if (useInstances) {
  52152. defines.push("#define INSTANCES");
  52153. attribs.push("world0");
  52154. attribs.push("world1");
  52155. attribs.push("world2");
  52156. attribs.push("world3");
  52157. }
  52158. // Get correct effect
  52159. var join = defines.join("\n");
  52160. if (this._cachedDefines !== join) {
  52161. this._cachedDefines = join;
  52162. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  52163. }
  52164. return this._effect.isReady();
  52165. };
  52166. DepthRenderer.prototype.getDepthMap = function () {
  52167. return this._depthMap;
  52168. };
  52169. // Methods
  52170. DepthRenderer.prototype.dispose = function () {
  52171. this._depthMap.dispose();
  52172. };
  52173. return DepthRenderer;
  52174. }());
  52175. BABYLON.DepthRenderer = DepthRenderer;
  52176. })(BABYLON || (BABYLON = {}));
  52177. //# sourceMappingURL=babylon.depthRenderer.js.map
  52178. var BABYLON;
  52179. (function (BABYLON) {
  52180. var SSAORenderingPipeline = (function (_super) {
  52181. __extends(SSAORenderingPipeline, _super);
  52182. /**
  52183. * @constructor
  52184. * @param {string} name - The rendering pipeline name
  52185. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52186. * @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 }
  52187. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52188. */
  52189. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52190. var _this = _super.call(this, scene.getEngine(), name) || this;
  52191. // Members
  52192. /**
  52193. * The PassPostProcess id in the pipeline that contains the original scene color
  52194. * @type {string}
  52195. */
  52196. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52197. /**
  52198. * The SSAO PostProcess id in the pipeline
  52199. * @type {string}
  52200. */
  52201. _this.SSAORenderEffect = "SSAORenderEffect";
  52202. /**
  52203. * The horizontal blur PostProcess id in the pipeline
  52204. * @type {string}
  52205. */
  52206. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52207. /**
  52208. * The vertical blur PostProcess id in the pipeline
  52209. * @type {string}
  52210. */
  52211. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52212. /**
  52213. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52214. * @type {string}
  52215. */
  52216. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52217. /**
  52218. * The output strength of the SSAO post-process. Default value is 1.0.
  52219. * @type {number}
  52220. */
  52221. _this.totalStrength = 1.0;
  52222. /**
  52223. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52224. * @type {number}
  52225. */
  52226. _this.radius = 0.0001;
  52227. /**
  52228. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52229. * Must not be equal to fallOff and superior to fallOff.
  52230. * Default value is 0.975
  52231. * @type {number}
  52232. */
  52233. _this.area = 0.0075;
  52234. /**
  52235. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52236. * Must not be equal to area and inferior to area.
  52237. * Default value is 0.0
  52238. * @type {number}
  52239. */
  52240. _this.fallOff = 0.000001;
  52241. /**
  52242. * The base color of the SSAO post-process
  52243. * The final result is "base + ssao" between [0, 1]
  52244. * @type {number}
  52245. */
  52246. _this.base = 0.5;
  52247. _this._firstUpdate = true;
  52248. _this._scene = scene;
  52249. // Set up assets
  52250. _this._createRandomTexture();
  52251. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52252. var ssaoRatio = ratio.ssaoRatio || ratio;
  52253. var combineRatio = ratio.combineRatio || ratio;
  52254. _this._ratio = {
  52255. ssaoRatio: ssaoRatio,
  52256. combineRatio: combineRatio
  52257. };
  52258. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52259. _this._createSSAOPostProcess(ssaoRatio);
  52260. _this._createBlurPostProcess(ssaoRatio);
  52261. _this._createSSAOCombinePostProcess(combineRatio);
  52262. // Set up pipeline
  52263. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52264. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52265. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52266. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52267. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52268. // Finish
  52269. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52270. if (cameras)
  52271. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52272. return _this;
  52273. }
  52274. // Public Methods
  52275. /**
  52276. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52277. */
  52278. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52279. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52280. for (var i = 0; i < this._scene.cameras.length; i++) {
  52281. var camera = this._scene.cameras[i];
  52282. this._originalColorPostProcess.dispose(camera);
  52283. this._ssaoPostProcess.dispose(camera);
  52284. this._blurHPostProcess.dispose(camera);
  52285. this._blurVPostProcess.dispose(camera);
  52286. this._ssaoCombinePostProcess.dispose(camera);
  52287. }
  52288. this._randomTexture.dispose();
  52289. if (disableDepthRender)
  52290. this._scene.disableDepthRenderer();
  52291. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52292. _super.prototype.dispose.call(this);
  52293. };
  52294. // Private Methods
  52295. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52296. var _this = this;
  52297. /*
  52298. var samplerOffsets = [
  52299. -8.0, -6.0, -4.0, -2.0,
  52300. 0.0,
  52301. 2.0, 4.0, 6.0, 8.0
  52302. ];
  52303. */
  52304. var samples = 16;
  52305. var samplerOffsets = [];
  52306. for (var i = -8; i < 8; i++) {
  52307. samplerOffsets.push(i * 2);
  52308. }
  52309. 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");
  52310. this._blurHPostProcess.onApply = function (effect) {
  52311. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52312. effect.setTexture("depthSampler", _this._depthTexture);
  52313. if (_this._firstUpdate) {
  52314. effect.setArray("samplerOffsets", samplerOffsets);
  52315. }
  52316. };
  52317. 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");
  52318. this._blurVPostProcess.onApply = function (effect) {
  52319. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52320. effect.setTexture("depthSampler", _this._depthTexture);
  52321. if (_this._firstUpdate) {
  52322. effect.setArray("samplerOffsets", samplerOffsets);
  52323. _this._firstUpdate = false;
  52324. }
  52325. };
  52326. };
  52327. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52328. var _this = this;
  52329. var numSamples = 16;
  52330. var sampleSphere = [
  52331. 0.5381, 0.1856, -0.4319,
  52332. 0.1379, 0.2486, 0.4430,
  52333. 0.3371, 0.5679, -0.0057,
  52334. -0.6999, -0.0451, -0.0019,
  52335. 0.0689, -0.1598, -0.8547,
  52336. 0.0560, 0.0069, -0.1843,
  52337. -0.0146, 0.1402, 0.0762,
  52338. 0.0100, -0.1924, -0.0344,
  52339. -0.3577, -0.5301, -0.4358,
  52340. -0.3169, 0.1063, 0.0158,
  52341. 0.0103, -0.5869, 0.0046,
  52342. -0.0897, -0.4940, 0.3287,
  52343. 0.7119, -0.0154, -0.0918,
  52344. -0.0533, 0.0596, -0.5411,
  52345. 0.0352, -0.0631, 0.5460,
  52346. -0.4776, 0.2847, -0.0271
  52347. ];
  52348. var samplesFactor = 1.0 / numSamples;
  52349. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52350. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52351. "area", "fallOff", "base", "range", "viewport"
  52352. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52353. var viewport = new BABYLON.Vector2(0, 0);
  52354. this._ssaoPostProcess.onApply = function (effect) {
  52355. if (_this._firstUpdate) {
  52356. effect.setArray3("sampleSphere", sampleSphere);
  52357. effect.setFloat("samplesFactor", samplesFactor);
  52358. effect.setFloat("randTextureTiles", 4.0);
  52359. }
  52360. effect.setFloat("totalStrength", _this.totalStrength);
  52361. effect.setFloat("radius", _this.radius);
  52362. effect.setFloat("area", _this.area);
  52363. effect.setFloat("fallOff", _this.fallOff);
  52364. effect.setFloat("base", _this.base);
  52365. effect.setTexture("textureSampler", _this._depthTexture);
  52366. effect.setTexture("randomSampler", _this._randomTexture);
  52367. };
  52368. };
  52369. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52370. var _this = this;
  52371. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52372. this._ssaoCombinePostProcess.onApply = function (effect) {
  52373. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52374. };
  52375. };
  52376. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52377. var size = 512;
  52378. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52379. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52380. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52381. var context = this._randomTexture.getContext();
  52382. var rand = function (min, max) {
  52383. return Math.random() * (max - min) + min;
  52384. };
  52385. var randVector = BABYLON.Vector3.Zero();
  52386. for (var x = 0; x < size; x++) {
  52387. for (var y = 0; y < size; y++) {
  52388. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52389. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52390. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52391. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52392. context.fillRect(x, y, 1, 1);
  52393. }
  52394. }
  52395. this._randomTexture.update(false);
  52396. };
  52397. return SSAORenderingPipeline;
  52398. }(BABYLON.PostProcessRenderPipeline));
  52399. __decorate([
  52400. BABYLON.serialize()
  52401. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52402. __decorate([
  52403. BABYLON.serialize()
  52404. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52405. __decorate([
  52406. BABYLON.serialize()
  52407. ], SSAORenderingPipeline.prototype, "area", void 0);
  52408. __decorate([
  52409. BABYLON.serialize()
  52410. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52411. __decorate([
  52412. BABYLON.serialize()
  52413. ], SSAORenderingPipeline.prototype, "base", void 0);
  52414. __decorate([
  52415. BABYLON.serialize()
  52416. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52417. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52418. })(BABYLON || (BABYLON = {}));
  52419. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  52420. var BABYLON;
  52421. (function (BABYLON) {
  52422. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  52423. var VolumetricLightScatteringPostProcess = (function (_super) {
  52424. __extends(VolumetricLightScatteringPostProcess, _super);
  52425. /**
  52426. * @constructor
  52427. * @param {string} name - The post-process name
  52428. * @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)
  52429. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  52430. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  52431. * @param {number} samples - The post-process quality, default 100
  52432. * @param {number} samplingMode - The post-process filtering mode
  52433. * @param {BABYLON.Engine} engine - The babylon engine
  52434. * @param {boolean} reusable - If the post-process is reusable
  52435. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  52436. */
  52437. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  52438. if (samples === void 0) { samples = 100; }
  52439. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52440. 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;
  52441. _this._screenCoordinates = BABYLON.Vector2.Zero();
  52442. /**
  52443. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  52444. * @type {Vector3}
  52445. */
  52446. _this.customMeshPosition = BABYLON.Vector3.Zero();
  52447. /**
  52448. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  52449. * @type {boolean}
  52450. */
  52451. _this.useCustomMeshPosition = false;
  52452. /**
  52453. * If the post-process should inverse the light scattering direction
  52454. * @type {boolean}
  52455. */
  52456. _this.invert = true;
  52457. /**
  52458. * Array containing the excluded meshes not rendered in the internal pass
  52459. */
  52460. _this.excludedMeshes = new Array();
  52461. /**
  52462. * Controls the overall intensity of the post-process
  52463. * @type {number}
  52464. */
  52465. _this.exposure = 0.3;
  52466. /**
  52467. * Dissipates each sample's contribution in range [0, 1]
  52468. * @type {number}
  52469. */
  52470. _this.decay = 0.96815;
  52471. /**
  52472. * Controls the overall intensity of each sample
  52473. * @type {number}
  52474. */
  52475. _this.weight = 0.58767;
  52476. /**
  52477. * Controls the density of each sample
  52478. * @type {number}
  52479. */
  52480. _this.density = 0.926;
  52481. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  52482. var engine = scene.getEngine();
  52483. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52484. // Configure mesh
  52485. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  52486. // Configure
  52487. _this._createPass(scene, ratio.passRatio || ratio);
  52488. _this.onActivate = function (camera) {
  52489. if (!_this.isSupported) {
  52490. _this.dispose(camera);
  52491. }
  52492. _this.onActivate = null;
  52493. };
  52494. _this.onApplyObservable.add(function (effect) {
  52495. _this._updateMeshScreenCoordinates(scene);
  52496. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  52497. effect.setFloat("exposure", _this.exposure);
  52498. effect.setFloat("decay", _this.decay);
  52499. effect.setFloat("weight", _this.weight);
  52500. effect.setFloat("density", _this.density);
  52501. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  52502. });
  52503. return _this;
  52504. }
  52505. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  52506. get: function () {
  52507. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52508. return false;
  52509. },
  52510. set: function (useDiffuseColor) {
  52511. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  52512. },
  52513. enumerable: true,
  52514. configurable: true
  52515. });
  52516. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  52517. var mesh = subMesh.getMesh();
  52518. // Render this.mesh as default
  52519. if (mesh === this.mesh) {
  52520. return mesh.material.isReady(mesh);
  52521. }
  52522. var defines = [];
  52523. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52524. var material = subMesh.getMaterial();
  52525. var needUV = false;
  52526. // Alpha test
  52527. if (material) {
  52528. if (material.needAlphaTesting()) {
  52529. defines.push("#define ALPHATEST");
  52530. }
  52531. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52532. attribs.push(BABYLON.VertexBuffer.UVKind);
  52533. defines.push("#define UV1");
  52534. }
  52535. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52536. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52537. defines.push("#define UV2");
  52538. }
  52539. }
  52540. // Bones
  52541. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52542. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52543. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52544. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52545. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52546. }
  52547. else {
  52548. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52549. }
  52550. // Instances
  52551. if (useInstances) {
  52552. defines.push("#define INSTANCES");
  52553. attribs.push("world0");
  52554. attribs.push("world1");
  52555. attribs.push("world2");
  52556. attribs.push("world3");
  52557. }
  52558. // Get correct effect
  52559. var join = defines.join("\n");
  52560. if (this._cachedDefines !== join) {
  52561. this._cachedDefines = join;
  52562. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  52563. }
  52564. return this._volumetricLightScatteringPass.isReady();
  52565. };
  52566. /**
  52567. * Sets the new light position for light scattering effect
  52568. * @param {BABYLON.Vector3} The new custom light position
  52569. */
  52570. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  52571. this.customMeshPosition = position;
  52572. };
  52573. /**
  52574. * Returns the light position for light scattering effect
  52575. * @return {BABYLON.Vector3} The custom light position
  52576. */
  52577. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  52578. return this.customMeshPosition;
  52579. };
  52580. /**
  52581. * Disposes the internal assets and detaches the post-process from the camera
  52582. */
  52583. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  52584. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  52585. if (rttIndex !== -1) {
  52586. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  52587. }
  52588. this._volumetricLightScatteringRTT.dispose();
  52589. _super.prototype.dispose.call(this, camera);
  52590. };
  52591. /**
  52592. * Returns the render target texture used by the post-process
  52593. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  52594. */
  52595. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  52596. return this._volumetricLightScatteringRTT;
  52597. };
  52598. // Private methods
  52599. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  52600. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  52601. return true;
  52602. }
  52603. return false;
  52604. };
  52605. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  52606. var _this = this;
  52607. var engine = scene.getEngine();
  52608. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52609. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52610. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52611. this._volumetricLightScatteringRTT.renderList = null;
  52612. this._volumetricLightScatteringRTT.renderParticles = false;
  52613. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  52614. // Custom render function for submeshes
  52615. var renderSubMesh = function (subMesh) {
  52616. var mesh = subMesh.getRenderingMesh();
  52617. if (_this._meshExcluded(mesh)) {
  52618. return;
  52619. }
  52620. var scene = mesh.getScene();
  52621. var engine = scene.getEngine();
  52622. // Culling
  52623. engine.setState(subMesh.getMaterial().backFaceCulling);
  52624. // Managing instances
  52625. var batch = mesh._getInstancesRenderList(subMesh._id);
  52626. if (batch.mustReturn) {
  52627. return;
  52628. }
  52629. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  52630. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52631. var effect = _this._volumetricLightScatteringPass;
  52632. if (mesh === _this.mesh) {
  52633. effect = subMesh.getMaterial().getEffect();
  52634. }
  52635. engine.enableEffect(effect);
  52636. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  52637. if (mesh === _this.mesh) {
  52638. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  52639. }
  52640. else {
  52641. var material = subMesh.getMaterial();
  52642. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  52643. // Alpha test
  52644. if (material && material.needAlphaTesting()) {
  52645. var alphaTexture = material.getAlphaTestTexture();
  52646. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  52647. if (alphaTexture) {
  52648. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52649. }
  52650. }
  52651. // Bones
  52652. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52653. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52654. }
  52655. }
  52656. // Draw
  52657. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  52658. }
  52659. };
  52660. // Render target texture callbacks
  52661. var savedSceneClearColor;
  52662. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  52663. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  52664. savedSceneClearColor = scene.clearColor;
  52665. scene.clearColor = sceneClearColor;
  52666. });
  52667. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  52668. scene.clearColor = savedSceneClearColor;
  52669. });
  52670. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  52671. var engine = scene.getEngine();
  52672. var index;
  52673. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52674. renderSubMesh(opaqueSubMeshes.data[index]);
  52675. }
  52676. engine.setAlphaTesting(true);
  52677. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52678. renderSubMesh(alphaTestSubMeshes.data[index]);
  52679. }
  52680. engine.setAlphaTesting(false);
  52681. if (transparentSubMeshes.length) {
  52682. // Sort sub meshes
  52683. for (index = 0; index < transparentSubMeshes.length; index++) {
  52684. var submesh = transparentSubMeshes.data[index];
  52685. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  52686. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  52687. }
  52688. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  52689. sortedArray.sort(function (a, b) {
  52690. // Alpha index first
  52691. if (a._alphaIndex > b._alphaIndex) {
  52692. return 1;
  52693. }
  52694. if (a._alphaIndex < b._alphaIndex) {
  52695. return -1;
  52696. }
  52697. // Then distance to camera
  52698. if (a._distanceToCamera < b._distanceToCamera) {
  52699. return 1;
  52700. }
  52701. if (a._distanceToCamera > b._distanceToCamera) {
  52702. return -1;
  52703. }
  52704. return 0;
  52705. });
  52706. // Render sub meshes
  52707. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52708. for (index = 0; index < sortedArray.length; index++) {
  52709. renderSubMesh(sortedArray[index]);
  52710. }
  52711. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52712. }
  52713. };
  52714. };
  52715. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  52716. var transform = scene.getTransformMatrix();
  52717. var meshPosition;
  52718. if (this.useCustomMeshPosition) {
  52719. meshPosition = this.customMeshPosition;
  52720. }
  52721. else if (this.attachedNode) {
  52722. meshPosition = this.attachedNode.position;
  52723. }
  52724. else {
  52725. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  52726. }
  52727. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  52728. this._screenCoordinates.x = pos.x / this._viewPort.width;
  52729. this._screenCoordinates.y = pos.y / this._viewPort.height;
  52730. if (this.invert)
  52731. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  52732. };
  52733. // Static methods
  52734. /**
  52735. * Creates a default mesh for the Volumeric Light Scattering post-process
  52736. * @param {string} The mesh name
  52737. * @param {BABYLON.Scene} The scene where to create the mesh
  52738. * @return {BABYLON.Mesh} the default mesh
  52739. */
  52740. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  52741. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  52742. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  52743. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  52744. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  52745. mesh.material = material;
  52746. return mesh;
  52747. };
  52748. return VolumetricLightScatteringPostProcess;
  52749. }(BABYLON.PostProcess));
  52750. __decorate([
  52751. BABYLON.serializeAsVector3()
  52752. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  52753. __decorate([
  52754. BABYLON.serialize()
  52755. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  52756. __decorate([
  52757. BABYLON.serialize()
  52758. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  52759. __decorate([
  52760. BABYLON.serializeAsMeshReference()
  52761. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  52762. __decorate([
  52763. BABYLON.serialize()
  52764. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  52765. __decorate([
  52766. BABYLON.serialize()
  52767. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  52768. __decorate([
  52769. BABYLON.serialize()
  52770. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  52771. __decorate([
  52772. BABYLON.serialize()
  52773. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  52774. __decorate([
  52775. BABYLON.serialize()
  52776. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  52777. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  52778. })(BABYLON || (BABYLON = {}));
  52779. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  52780. // BABYLON.JS Chromatic Aberration GLSL Shader
  52781. // Author: Olivier Guyot
  52782. // Separates very slightly R, G and B colors on the edges of the screen
  52783. // Inspired by Francois Tarlier & Martins Upitis
  52784. var BABYLON;
  52785. (function (BABYLON) {
  52786. var LensRenderingPipeline = (function (_super) {
  52787. __extends(LensRenderingPipeline, _super);
  52788. /**
  52789. * @constructor
  52790. *
  52791. * Effect parameters are as follow:
  52792. * {
  52793. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52794. * edge_blur: number; // from 0 to x (1 for realism)
  52795. * distortion: number; // from 0 to x (1 for realism)
  52796. * grain_amount: number; // from 0 to 1
  52797. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52798. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52799. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52800. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52801. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52802. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52803. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52804. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52805. * }
  52806. * Note: if an effect parameter is unset, effect is disabled
  52807. *
  52808. * @param {string} name - The rendering pipeline name
  52809. * @param {object} parameters - An object containing all parameters (see above)
  52810. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52811. * @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)
  52812. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52813. */
  52814. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52815. if (ratio === void 0) { ratio = 1.0; }
  52816. var _this = _super.call(this, scene.getEngine(), name) || this;
  52817. // Lens effects can be of the following:
  52818. // - chromatic aberration (slight shift of RGB colors)
  52819. // - blur on the edge of the lens
  52820. // - lens distortion
  52821. // - depth-of-field blur & highlights enhancing
  52822. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52823. // - grain effect (noise or custom texture)
  52824. // Two additional texture samplers are needed:
  52825. // - depth map (for depth-of-field)
  52826. // - grain texture
  52827. /**
  52828. * The chromatic aberration PostProcess id in the pipeline
  52829. * @type {string}
  52830. */
  52831. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52832. /**
  52833. * The highlights enhancing PostProcess id in the pipeline
  52834. * @type {string}
  52835. */
  52836. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52837. /**
  52838. * The depth-of-field PostProcess id in the pipeline
  52839. * @type {string}
  52840. */
  52841. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52842. _this._scene = scene;
  52843. // Fetch texture samplers
  52844. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52845. if (parameters.grain_texture) {
  52846. _this._grainTexture = parameters.grain_texture;
  52847. }
  52848. else {
  52849. _this._createGrainTexture();
  52850. }
  52851. // save parameters
  52852. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52853. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52854. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52855. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  52856. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52857. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52858. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52859. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52860. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52861. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52862. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52863. // Create effects
  52864. _this._createChromaticAberrationPostProcess(ratio);
  52865. _this._createHighlightsPostProcess(ratio);
  52866. _this._createDepthOfFieldPostProcess(ratio / 4);
  52867. // Set up pipeline
  52868. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52869. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52870. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52871. if (_this._highlightsGain === -1) {
  52872. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52873. }
  52874. // Finish
  52875. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52876. if (cameras) {
  52877. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52878. }
  52879. return _this;
  52880. }
  52881. // public methods (self explanatory)
  52882. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52883. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52884. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52885. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52886. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52887. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52888. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52889. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52890. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52891. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52892. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52893. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52894. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52895. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52896. };
  52897. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52898. this._highlightsPostProcess.updateEffect();
  52899. };
  52900. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52901. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52902. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52903. this._highlightsGain = amount;
  52904. };
  52905. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52906. if (this._highlightsGain === -1) {
  52907. this._highlightsGain = 1.0;
  52908. }
  52909. this._highlightsThreshold = amount;
  52910. };
  52911. LensRenderingPipeline.prototype.disableHighlights = function () {
  52912. this._highlightsGain = -1;
  52913. };
  52914. /**
  52915. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52916. */
  52917. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52918. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52919. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52920. this._chromaticAberrationPostProcess = undefined;
  52921. this._highlightsPostProcess = undefined;
  52922. this._depthOfFieldPostProcess = undefined;
  52923. this._grainTexture.dispose();
  52924. if (disableDepthRender)
  52925. this._scene.disableDepthRenderer();
  52926. };
  52927. // colors shifting and distortion
  52928. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52929. var _this = this;
  52930. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52931. [], // samplers
  52932. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52933. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52934. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52935. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52936. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52937. };
  52938. };
  52939. // highlights enhancing
  52940. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52941. var _this = this;
  52942. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52943. [], // samplers
  52944. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52945. this._highlightsPostProcess.onApply = function (effect) {
  52946. effect.setFloat('gain', _this._highlightsGain);
  52947. effect.setFloat('threshold', _this._highlightsThreshold);
  52948. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52949. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52950. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52951. };
  52952. };
  52953. // colors shifting and distortion
  52954. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52955. var _this = this;
  52956. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52957. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52958. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52959. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52960. this._depthOfFieldPostProcess.onApply = function (effect) {
  52961. effect.setTexture("depthSampler", _this._depthTexture);
  52962. effect.setTexture("grainSampler", _this._grainTexture);
  52963. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52964. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52965. effect.setFloat('grain_amount', _this._grainAmount);
  52966. effect.setBool('blur_noise', _this._blurNoise);
  52967. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52968. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52969. effect.setFloat('distortion', _this._distortion);
  52970. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52971. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52972. effect.setFloat('aperture', _this._dofAperture);
  52973. effect.setFloat('darken', _this._dofDarken);
  52974. effect.setFloat('edge_blur', _this._edgeBlur);
  52975. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52976. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52977. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52978. };
  52979. };
  52980. // creates a black and white random noise texture, 512x512
  52981. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52982. var size = 512;
  52983. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52984. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52985. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52986. var context = this._grainTexture.getContext();
  52987. var rand = function (min, max) {
  52988. return Math.random() * (max - min) + min;
  52989. };
  52990. var value;
  52991. for (var x = 0; x < size; x++) {
  52992. for (var y = 0; y < size; y++) {
  52993. value = Math.floor(rand(0.42, 0.58) * 255);
  52994. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52995. context.fillRect(x, y, 1, 1);
  52996. }
  52997. }
  52998. this._grainTexture.update(false);
  52999. };
  53000. return LensRenderingPipeline;
  53001. }(BABYLON.PostProcessRenderPipeline));
  53002. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  53003. })(BABYLON || (BABYLON = {}));
  53004. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  53005. //
  53006. // This post-process allows the modification of rendered colors by using
  53007. // a 'look-up table' (LUT). This effect is also called Color Grading.
  53008. //
  53009. // The object needs to be provided an url to a texture containing the color
  53010. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  53011. // Use an image editing software to tweak the LUT to match your needs.
  53012. //
  53013. // For an example of a color LUT, see here:
  53014. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  53015. // For explanations on color grading, see here:
  53016. // http://udn.epicgames.com/Three/ColorGrading.html
  53017. //
  53018. var BABYLON;
  53019. (function (BABYLON) {
  53020. var ColorCorrectionPostProcess = (function (_super) {
  53021. __extends(ColorCorrectionPostProcess, _super);
  53022. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  53023. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  53024. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  53025. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  53026. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53027. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53028. _this.onApply = function (effect) {
  53029. effect.setTexture("colorTable", _this._colorTableTexture);
  53030. };
  53031. return _this;
  53032. }
  53033. return ColorCorrectionPostProcess;
  53034. }(BABYLON.PostProcess));
  53035. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  53036. })(BABYLON || (BABYLON = {}));
  53037. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  53038. /// <reference path="babylon.freeCamera.ts" />
  53039. /// <reference path="babylon.arcRotateCamera.ts" />
  53040. /// <reference path="babylon.gamepadCamera.ts" />
  53041. /// <reference path="babylon.universalCamera.ts" />
  53042. var BABYLON;
  53043. (function (BABYLON) {
  53044. var AnaglyphFreeCamera = (function (_super) {
  53045. __extends(AnaglyphFreeCamera, _super);
  53046. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  53047. var _this = _super.call(this, name, position, scene) || this;
  53048. _this.interaxialDistance = interaxialDistance;
  53049. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53050. return _this;
  53051. }
  53052. AnaglyphFreeCamera.prototype.getClassName = function () {
  53053. return "AnaglyphFreeCamera";
  53054. };
  53055. return AnaglyphFreeCamera;
  53056. }(BABYLON.FreeCamera));
  53057. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  53058. var AnaglyphArcRotateCamera = (function (_super) {
  53059. __extends(AnaglyphArcRotateCamera, _super);
  53060. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  53061. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  53062. _this.interaxialDistance = interaxialDistance;
  53063. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53064. return _this;
  53065. }
  53066. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  53067. return "AnaglyphArcRotateCamera";
  53068. };
  53069. return AnaglyphArcRotateCamera;
  53070. }(BABYLON.ArcRotateCamera));
  53071. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  53072. var AnaglyphGamepadCamera = (function (_super) {
  53073. __extends(AnaglyphGamepadCamera, _super);
  53074. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  53075. var _this = _super.call(this, name, position, scene) || this;
  53076. _this.interaxialDistance = interaxialDistance;
  53077. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53078. return _this;
  53079. }
  53080. AnaglyphGamepadCamera.prototype.getClassName = function () {
  53081. return "AnaglyphGamepadCamera";
  53082. };
  53083. return AnaglyphGamepadCamera;
  53084. }(BABYLON.GamepadCamera));
  53085. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  53086. var AnaglyphUniversalCamera = (function (_super) {
  53087. __extends(AnaglyphUniversalCamera, _super);
  53088. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  53089. var _this = _super.call(this, name, position, scene) || this;
  53090. _this.interaxialDistance = interaxialDistance;
  53091. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  53092. return _this;
  53093. }
  53094. AnaglyphUniversalCamera.prototype.getClassName = function () {
  53095. return "AnaglyphUniversalCamera";
  53096. };
  53097. return AnaglyphUniversalCamera;
  53098. }(BABYLON.UniversalCamera));
  53099. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  53100. var StereoscopicFreeCamera = (function (_super) {
  53101. __extends(StereoscopicFreeCamera, _super);
  53102. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53103. var _this = _super.call(this, name, position, scene) || this;
  53104. _this.interaxialDistance = interaxialDistance;
  53105. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53106. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53107. return _this;
  53108. }
  53109. StereoscopicFreeCamera.prototype.getClassName = function () {
  53110. return "StereoscopicFreeCamera";
  53111. };
  53112. return StereoscopicFreeCamera;
  53113. }(BABYLON.FreeCamera));
  53114. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  53115. var StereoscopicArcRotateCamera = (function (_super) {
  53116. __extends(StereoscopicArcRotateCamera, _super);
  53117. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  53118. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  53119. _this.interaxialDistance = interaxialDistance;
  53120. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53121. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53122. return _this;
  53123. }
  53124. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  53125. return "StereoscopicArcRotateCamera";
  53126. };
  53127. return StereoscopicArcRotateCamera;
  53128. }(BABYLON.ArcRotateCamera));
  53129. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  53130. var StereoscopicGamepadCamera = (function (_super) {
  53131. __extends(StereoscopicGamepadCamera, _super);
  53132. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53133. var _this = _super.call(this, name, position, scene) || this;
  53134. _this.interaxialDistance = interaxialDistance;
  53135. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53136. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53137. return _this;
  53138. }
  53139. StereoscopicGamepadCamera.prototype.getClassName = function () {
  53140. return "StereoscopicGamepadCamera";
  53141. };
  53142. return StereoscopicGamepadCamera;
  53143. }(BABYLON.GamepadCamera));
  53144. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  53145. var StereoscopicUniversalCamera = (function (_super) {
  53146. __extends(StereoscopicUniversalCamera, _super);
  53147. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  53148. var _this = _super.call(this, name, position, scene) || this;
  53149. _this.interaxialDistance = interaxialDistance;
  53150. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  53151. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  53152. return _this;
  53153. }
  53154. StereoscopicUniversalCamera.prototype.getClassName = function () {
  53155. return "StereoscopicUniversalCamera";
  53156. };
  53157. return StereoscopicUniversalCamera;
  53158. }(BABYLON.UniversalCamera));
  53159. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  53160. })(BABYLON || (BABYLON = {}));
  53161. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  53162. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  53163. var BABYLON;
  53164. (function (BABYLON) {
  53165. var HDRRenderingPipeline = (function (_super) {
  53166. __extends(HDRRenderingPipeline, _super);
  53167. /**
  53168. * @constructor
  53169. * @param {string} name - The rendering pipeline name
  53170. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53171. * @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)
  53172. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53173. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53174. */
  53175. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53176. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53177. var _this = _super.call(this, scene.getEngine(), name) || this;
  53178. /**
  53179. * Public members
  53180. */
  53181. // Gaussian Blur
  53182. /**
  53183. * Gaussian blur coefficient
  53184. * @type {number}
  53185. */
  53186. _this.gaussCoeff = 0.3;
  53187. /**
  53188. * Gaussian blur mean
  53189. * @type {number}
  53190. */
  53191. _this.gaussMean = 1.0;
  53192. /**
  53193. * Gaussian blur standard deviation
  53194. * @type {number}
  53195. */
  53196. _this.gaussStandDev = 0.8;
  53197. /**
  53198. * Gaussian blur multiplier. Multiplies the blur effect
  53199. * @type {number}
  53200. */
  53201. _this.gaussMultiplier = 4.0;
  53202. // HDR
  53203. /**
  53204. * Exposure, controls the overall intensity of the pipeline
  53205. * @type {number}
  53206. */
  53207. _this.exposure = 1.0;
  53208. /**
  53209. * Minimum luminance that the post-process can output. Luminance is >= 0
  53210. * @type {number}
  53211. */
  53212. _this.minimumLuminance = 1.0;
  53213. /**
  53214. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  53215. * @type {number}
  53216. */
  53217. _this.maximumLuminance = 1e20;
  53218. /**
  53219. * Increase rate for luminance: eye adaptation speed to dark
  53220. * @type {number}
  53221. */
  53222. _this.luminanceIncreaserate = 0.5;
  53223. /**
  53224. * Decrease rate for luminance: eye adaptation speed to bright
  53225. * @type {number}
  53226. */
  53227. _this.luminanceDecreaseRate = 0.5;
  53228. // Bright pass
  53229. /**
  53230. * Minimum luminance needed to compute HDR
  53231. * @type {number}
  53232. */
  53233. _this.brightThreshold = 0.8;
  53234. _this._needUpdate = true;
  53235. _this._scene = scene;
  53236. // Bright pass
  53237. _this._createBrightPassPostProcess(scene, ratio);
  53238. // Down sample X4
  53239. _this._createDownSampleX4PostProcess(scene, ratio);
  53240. // Create gaussian blur post-processes
  53241. _this._createGaussianBlurPostProcess(scene, ratio);
  53242. // Texture adder
  53243. _this._createTextureAdderPostProcess(scene, ratio);
  53244. // Luminance generator
  53245. _this._createLuminanceGeneratorPostProcess(scene);
  53246. // HDR
  53247. _this._createHDRPostProcess(scene, ratio);
  53248. // Pass postprocess
  53249. if (originalPostProcess === null) {
  53250. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  53251. }
  53252. else {
  53253. _this._originalPostProcess = originalPostProcess;
  53254. }
  53255. // Configure pipeline
  53256. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  53257. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  53258. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  53259. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  53260. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  53261. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  53262. var addDownSamplerPostProcess = function (id) {
  53263. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  53264. };
  53265. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  53266. addDownSamplerPostProcess(i);
  53267. }
  53268. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  53269. // Finish
  53270. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53271. if (cameras !== null) {
  53272. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53273. }
  53274. _this.update();
  53275. return _this;
  53276. }
  53277. /**
  53278. * Tells the pipeline to update its post-processes
  53279. */
  53280. HDRRenderingPipeline.prototype.update = function () {
  53281. this._needUpdate = true;
  53282. };
  53283. /**
  53284. * Returns the current calculated luminance
  53285. */
  53286. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  53287. return this._hdrCurrentLuminance;
  53288. };
  53289. /**
  53290. * Returns the currently drawn luminance
  53291. */
  53292. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  53293. return this._hdrOutputLuminance;
  53294. };
  53295. /**
  53296. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  53297. */
  53298. HDRRenderingPipeline.prototype.dispose = function () {
  53299. for (var i = 0; i < this._scene.cameras.length; i++) {
  53300. var camera = this._scene.cameras[i];
  53301. this._originalPostProcess.dispose(camera);
  53302. this._brightPassPostProcess.dispose(camera);
  53303. this._downSampleX4PostProcess.dispose(camera);
  53304. this._guassianBlurHPostProcess.dispose(camera);
  53305. this._guassianBlurVPostProcess.dispose(camera);
  53306. this._textureAdderPostProcess.dispose(camera);
  53307. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  53308. this._downSamplePostProcesses[j].dispose(camera);
  53309. }
  53310. this._hdrPostProcess.dispose(camera);
  53311. }
  53312. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  53313. _super.prototype.dispose.call(this);
  53314. };
  53315. /**
  53316. * Creates the HDR post-process and computes the luminance adaptation
  53317. */
  53318. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  53319. var _this = this;
  53320. var hdrLastLuminance = 0.0;
  53321. this._hdrOutputLuminance = -1.0;
  53322. this._hdrCurrentLuminance = 1.0;
  53323. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  53324. this._hdrPostProcess.onApply = function (effect) {
  53325. if (_this._hdrOutputLuminance < 0.0) {
  53326. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53327. }
  53328. else {
  53329. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  53330. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  53331. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  53332. }
  53333. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  53334. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  53335. }
  53336. else {
  53337. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  53338. }
  53339. }
  53340. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  53341. hdrLastLuminance += scene.getEngine().getDeltaTime();
  53342. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53343. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53344. effect.setFloat("exposure", _this.exposure);
  53345. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  53346. _this._needUpdate = false;
  53347. };
  53348. };
  53349. /**
  53350. * Texture Adder post-process
  53351. */
  53352. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53353. var _this = this;
  53354. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  53355. this._textureAdderPostProcess.onApply = function (effect) {
  53356. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  53357. };
  53358. };
  53359. /**
  53360. * Down sample X4 post-process
  53361. */
  53362. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53363. var _this = this;
  53364. var downSampleX4Offsets = new Array(32);
  53365. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  53366. this._downSampleX4PostProcess.onApply = function (effect) {
  53367. if (_this._needUpdate) {
  53368. var id = 0;
  53369. for (var i = -2; i < 2; i++) {
  53370. for (var j = -2; j < 2; j++) {
  53371. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  53372. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  53373. id += 2;
  53374. }
  53375. }
  53376. }
  53377. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53378. };
  53379. };
  53380. /**
  53381. * Bright pass post-process
  53382. */
  53383. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53384. var _this = this;
  53385. var brightOffsets = new Array(8);
  53386. var brightPassCallback = function (effect) {
  53387. if (_this._needUpdate) {
  53388. var sU = (1.0 / _this._brightPassPostProcess.width);
  53389. var sV = (1.0 / _this._brightPassPostProcess.height);
  53390. brightOffsets[0] = -0.5 * sU;
  53391. brightOffsets[1] = 0.5 * sV;
  53392. brightOffsets[2] = 0.5 * sU;
  53393. brightOffsets[3] = 0.5 * sV;
  53394. brightOffsets[4] = -0.5 * sU;
  53395. brightOffsets[5] = -0.5 * sV;
  53396. brightOffsets[6] = 0.5 * sU;
  53397. brightOffsets[7] = -0.5 * sV;
  53398. }
  53399. effect.setArray2("dsOffsets", brightOffsets);
  53400. effect.setFloat("brightThreshold", _this.brightThreshold);
  53401. };
  53402. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  53403. this._brightPassPostProcess.onApply = brightPassCallback;
  53404. };
  53405. /**
  53406. * Luminance generator. Creates the luminance post-process and down sample post-processes
  53407. */
  53408. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  53409. var _this = this;
  53410. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  53411. var luminanceOffsets = new Array(8);
  53412. var downSampleOffsets = new Array(18);
  53413. var halfDestPixelSize;
  53414. this._downSamplePostProcesses = new Array(lumSteps);
  53415. // Utils for luminance
  53416. var luminanceUpdateSourceOffsets = function (width, height) {
  53417. var sU = (1.0 / width);
  53418. var sV = (1.0 / height);
  53419. luminanceOffsets[0] = -0.5 * sU;
  53420. luminanceOffsets[1] = 0.5 * sV;
  53421. luminanceOffsets[2] = 0.5 * sU;
  53422. luminanceOffsets[3] = 0.5 * sV;
  53423. luminanceOffsets[4] = -0.5 * sU;
  53424. luminanceOffsets[5] = -0.5 * sV;
  53425. luminanceOffsets[6] = 0.5 * sU;
  53426. luminanceOffsets[7] = -0.5 * sV;
  53427. };
  53428. var luminanceUpdateDestOffsets = function (width, height) {
  53429. var id = 0;
  53430. for (var x = -1; x < 2; x++) {
  53431. for (var y = -1; y < 2; y++) {
  53432. downSampleOffsets[id] = (x) / width;
  53433. downSampleOffsets[id + 1] = (y) / height;
  53434. id += 2;
  53435. }
  53436. }
  53437. };
  53438. // Luminance callback
  53439. var luminanceCallback = function (effect) {
  53440. if (_this._needUpdate) {
  53441. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  53442. }
  53443. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  53444. effect.setArray2("lumOffsets", luminanceOffsets);
  53445. };
  53446. // Down sample callbacks
  53447. var downSampleCallback = function (indice) {
  53448. var i = indice;
  53449. return function (effect) {
  53450. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53451. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  53452. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  53453. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  53454. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  53455. effect.setArray2("dsOffsets", downSampleOffsets);
  53456. };
  53457. };
  53458. var downSampleAfterRenderCallback = function (effect) {
  53459. // Unpack result
  53460. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53461. 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);
  53462. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53463. };
  53464. // Create luminance post-process
  53465. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  53466. 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);
  53467. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  53468. // Create down sample post-processes
  53469. for (var i = lumSteps - 2; i >= 0; i--) {
  53470. var length = Math.pow(3, i);
  53471. ratio = { width: length, height: length };
  53472. var defines = "#define DOWN_SAMPLE\n";
  53473. if (i === 0) {
  53474. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  53475. }
  53476. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  53477. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  53478. if (i === 0) {
  53479. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  53480. }
  53481. }
  53482. };
  53483. /**
  53484. * Gaussian blur post-processes. Horizontal and Vertical
  53485. */
  53486. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  53487. var _this = this;
  53488. var blurOffsetsW = new Array(9);
  53489. var blurOffsetsH = new Array(9);
  53490. var blurWeights = new Array(9);
  53491. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  53492. // Utils for gaussian blur
  53493. var calculateBlurOffsets = function (height) {
  53494. var lastOutputDimensions = {
  53495. width: scene.getEngine().getRenderWidth(),
  53496. height: scene.getEngine().getRenderHeight()
  53497. };
  53498. for (var i = 0; i < 9; i++) {
  53499. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53500. if (height) {
  53501. blurOffsetsH[i] = value;
  53502. }
  53503. else {
  53504. blurOffsetsW[i] = value;
  53505. }
  53506. }
  53507. };
  53508. var calculateWeights = function () {
  53509. var x = 0.0;
  53510. for (var i = 0; i < 9; i++) {
  53511. x = (i - 4.0) / 4.0;
  53512. 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));
  53513. }
  53514. };
  53515. // Callback
  53516. var gaussianBlurCallback = function (height) {
  53517. return function (effect) {
  53518. if (_this._needUpdate) {
  53519. calculateWeights();
  53520. calculateBlurOffsets(height);
  53521. }
  53522. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  53523. effect.setArray("blurWeights", blurWeights);
  53524. effect.setFloat("multiplier", _this.gaussMultiplier);
  53525. };
  53526. };
  53527. // Create horizontal gaussian blur post-processes
  53528. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  53529. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  53530. // Create vertical gaussian blur post-process
  53531. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  53532. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  53533. };
  53534. return HDRRenderingPipeline;
  53535. }(BABYLON.PostProcessRenderPipeline));
  53536. // Luminance generator
  53537. HDRRenderingPipeline.LUM_STEPS = 6;
  53538. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  53539. })(BABYLON || (BABYLON = {}));
  53540. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  53541. var BABYLON;
  53542. (function (BABYLON) {
  53543. var FaceAdjacencies = (function () {
  53544. function FaceAdjacencies() {
  53545. this.edges = new Array();
  53546. this.edgesConnectedCount = 0;
  53547. }
  53548. return FaceAdjacencies;
  53549. }());
  53550. var EdgesRenderer = (function () {
  53551. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  53552. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  53553. if (epsilon === void 0) { epsilon = 0.95; }
  53554. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  53555. this.edgesWidthScalerForOrthographic = 1000.0;
  53556. this.edgesWidthScalerForPerspective = 50.0;
  53557. this._linesPositions = new Array();
  53558. this._linesNormals = new Array();
  53559. this._linesIndices = new Array();
  53560. this._buffers = {};
  53561. this._checkVerticesInsteadOfIndices = false;
  53562. this._source = source;
  53563. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  53564. this._epsilon = epsilon;
  53565. this._prepareRessources();
  53566. this._generateEdgesLines();
  53567. }
  53568. EdgesRenderer.prototype._prepareRessources = function () {
  53569. if (this._lineShader) {
  53570. return;
  53571. }
  53572. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  53573. attributes: ["position", "normal"],
  53574. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  53575. });
  53576. this._lineShader.disableDepthWrite = true;
  53577. this._lineShader.backFaceCulling = false;
  53578. };
  53579. EdgesRenderer.prototype.dispose = function () {
  53580. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  53581. if (buffer) {
  53582. buffer.dispose();
  53583. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  53584. }
  53585. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  53586. if (buffer) {
  53587. buffer.dispose();
  53588. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  53589. }
  53590. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  53591. this._lineShader.dispose();
  53592. };
  53593. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  53594. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  53595. return 0;
  53596. }
  53597. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  53598. return 1;
  53599. }
  53600. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  53601. return 2;
  53602. }
  53603. return -1;
  53604. };
  53605. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  53606. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  53607. return 0;
  53608. }
  53609. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  53610. return 1;
  53611. }
  53612. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  53613. return 2;
  53614. }
  53615. return -1;
  53616. };
  53617. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  53618. var needToCreateLine;
  53619. if (edge === undefined) {
  53620. needToCreateLine = true;
  53621. }
  53622. else {
  53623. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  53624. needToCreateLine = dotProduct < this._epsilon;
  53625. }
  53626. if (needToCreateLine) {
  53627. var offset = this._linesPositions.length / 3;
  53628. var normal = p0.subtract(p1);
  53629. normal.normalize();
  53630. // Positions
  53631. this._linesPositions.push(p0.x);
  53632. this._linesPositions.push(p0.y);
  53633. this._linesPositions.push(p0.z);
  53634. this._linesPositions.push(p0.x);
  53635. this._linesPositions.push(p0.y);
  53636. this._linesPositions.push(p0.z);
  53637. this._linesPositions.push(p1.x);
  53638. this._linesPositions.push(p1.y);
  53639. this._linesPositions.push(p1.z);
  53640. this._linesPositions.push(p1.x);
  53641. this._linesPositions.push(p1.y);
  53642. this._linesPositions.push(p1.z);
  53643. // Normals
  53644. this._linesNormals.push(p1.x);
  53645. this._linesNormals.push(p1.y);
  53646. this._linesNormals.push(p1.z);
  53647. this._linesNormals.push(-1);
  53648. this._linesNormals.push(p1.x);
  53649. this._linesNormals.push(p1.y);
  53650. this._linesNormals.push(p1.z);
  53651. this._linesNormals.push(1);
  53652. this._linesNormals.push(p0.x);
  53653. this._linesNormals.push(p0.y);
  53654. this._linesNormals.push(p0.z);
  53655. this._linesNormals.push(-1);
  53656. this._linesNormals.push(p0.x);
  53657. this._linesNormals.push(p0.y);
  53658. this._linesNormals.push(p0.z);
  53659. this._linesNormals.push(1);
  53660. // Indices
  53661. this._linesIndices.push(offset);
  53662. this._linesIndices.push(offset + 1);
  53663. this._linesIndices.push(offset + 2);
  53664. this._linesIndices.push(offset);
  53665. this._linesIndices.push(offset + 2);
  53666. this._linesIndices.push(offset + 3);
  53667. }
  53668. };
  53669. EdgesRenderer.prototype._generateEdgesLines = function () {
  53670. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53671. var indices = this._source.getIndices();
  53672. // First let's find adjacencies
  53673. var adjacencies = new Array();
  53674. var faceNormals = new Array();
  53675. var index;
  53676. var faceAdjacencies;
  53677. // Prepare faces
  53678. for (index = 0; index < indices.length; index += 3) {
  53679. faceAdjacencies = new FaceAdjacencies();
  53680. var p0Index = indices[index];
  53681. var p1Index = indices[index + 1];
  53682. var p2Index = indices[index + 2];
  53683. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  53684. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  53685. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  53686. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  53687. faceNormal.normalize();
  53688. faceNormals.push(faceNormal);
  53689. adjacencies.push(faceAdjacencies);
  53690. }
  53691. // Scan
  53692. for (index = 0; index < adjacencies.length; index++) {
  53693. faceAdjacencies = adjacencies[index];
  53694. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  53695. var otherFaceAdjacencies = adjacencies[otherIndex];
  53696. if (faceAdjacencies.edgesConnectedCount === 3) {
  53697. break;
  53698. }
  53699. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  53700. continue;
  53701. }
  53702. var otherP0 = indices[otherIndex * 3];
  53703. var otherP1 = indices[otherIndex * 3 + 1];
  53704. var otherP2 = indices[otherIndex * 3 + 2];
  53705. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  53706. var otherEdgeIndex;
  53707. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  53708. continue;
  53709. }
  53710. switch (edgeIndex) {
  53711. case 0:
  53712. if (this._checkVerticesInsteadOfIndices) {
  53713. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53714. }
  53715. else {
  53716. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  53717. }
  53718. break;
  53719. case 1:
  53720. if (this._checkVerticesInsteadOfIndices) {
  53721. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53722. }
  53723. else {
  53724. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  53725. }
  53726. break;
  53727. case 2:
  53728. if (this._checkVerticesInsteadOfIndices) {
  53729. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  53730. }
  53731. else {
  53732. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  53733. }
  53734. break;
  53735. }
  53736. if (otherEdgeIndex === -1) {
  53737. continue;
  53738. }
  53739. faceAdjacencies.edges[edgeIndex] = otherIndex;
  53740. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  53741. faceAdjacencies.edgesConnectedCount++;
  53742. otherFaceAdjacencies.edgesConnectedCount++;
  53743. if (faceAdjacencies.edgesConnectedCount === 3) {
  53744. break;
  53745. }
  53746. }
  53747. }
  53748. }
  53749. // Create lines
  53750. for (index = 0; index < adjacencies.length; index++) {
  53751. // 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
  53752. var current = adjacencies[index];
  53753. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  53754. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  53755. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  53756. }
  53757. // Merge into a single mesh
  53758. var engine = this._source.getScene().getEngine();
  53759. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  53760. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  53761. this._ib = engine.createIndexBuffer(this._linesIndices);
  53762. this._indicesCount = this._linesIndices.length;
  53763. };
  53764. EdgesRenderer.prototype.render = function () {
  53765. if (!this._lineShader.isReady()) {
  53766. return;
  53767. }
  53768. var scene = this._source.getScene();
  53769. var engine = scene.getEngine();
  53770. this._lineShader._preBind();
  53771. // VBOs
  53772. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  53773. scene.resetCachedMaterial();
  53774. this._lineShader.setColor4("color", this._source.edgesColor);
  53775. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  53776. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  53777. }
  53778. else {
  53779. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  53780. }
  53781. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  53782. this._lineShader.bind(this._source.getWorldMatrix());
  53783. // Draw order
  53784. engine.draw(true, 0, this._indicesCount);
  53785. this._lineShader.unbind();
  53786. engine.setDepthWrite(true);
  53787. };
  53788. return EdgesRenderer;
  53789. }());
  53790. BABYLON.EdgesRenderer = EdgesRenderer;
  53791. })(BABYLON || (BABYLON = {}));
  53792. //# sourceMappingURL=babylon.edgesRenderer.js.map
  53793. var BABYLON;
  53794. (function (BABYLON) {
  53795. var TonemappingOperator;
  53796. (function (TonemappingOperator) {
  53797. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  53798. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  53799. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  53800. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  53801. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  53802. ;
  53803. var TonemapPostProcess = (function (_super) {
  53804. __extends(TonemapPostProcess, _super);
  53805. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  53806. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53807. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53808. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  53809. _this._operator = _operator;
  53810. _this.exposureAdjustment = exposureAdjustment;
  53811. var defines = "#define ";
  53812. if (_this._operator === TonemappingOperator.Hable)
  53813. defines += "HABLE_TONEMAPPING";
  53814. else if (_this._operator === TonemappingOperator.Reinhard)
  53815. defines += "REINHARD_TONEMAPPING";
  53816. else if (_this._operator === TonemappingOperator.HejiDawson)
  53817. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  53818. else if (_this._operator === TonemappingOperator.Photographic)
  53819. defines += "PHOTOGRAPHIC_TONEMAPPING";
  53820. //sadly a second call to create the effect.
  53821. _this.updateEffect(defines);
  53822. _this.onApply = function (effect) {
  53823. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  53824. };
  53825. return _this;
  53826. }
  53827. return TonemapPostProcess;
  53828. }(BABYLON.PostProcess));
  53829. BABYLON.TonemapPostProcess = TonemapPostProcess;
  53830. })(BABYLON || (BABYLON = {}));
  53831. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  53832. var BABYLON;
  53833. (function (BABYLON) {
  53834. var ReflectionProbe = (function () {
  53835. function ReflectionProbe(name, size, scene, generateMipMaps) {
  53836. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53837. var _this = this;
  53838. this.name = name;
  53839. this._viewMatrix = BABYLON.Matrix.Identity();
  53840. this._target = BABYLON.Vector3.Zero();
  53841. this._add = BABYLON.Vector3.Zero();
  53842. this.invertYAxis = false;
  53843. this.position = BABYLON.Vector3.Zero();
  53844. this._scene = scene;
  53845. this._scene.reflectionProbes.push(this);
  53846. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  53847. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  53848. switch (faceIndex) {
  53849. case 0:
  53850. _this._add.copyFromFloats(1, 0, 0);
  53851. break;
  53852. case 1:
  53853. _this._add.copyFromFloats(-1, 0, 0);
  53854. break;
  53855. case 2:
  53856. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  53857. break;
  53858. case 3:
  53859. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  53860. break;
  53861. case 4:
  53862. _this._add.copyFromFloats(0, 0, 1);
  53863. break;
  53864. case 5:
  53865. _this._add.copyFromFloats(0, 0, -1);
  53866. break;
  53867. }
  53868. if (_this._attachedMesh) {
  53869. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  53870. }
  53871. _this.position.addToRef(_this._add, _this._target);
  53872. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  53873. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  53874. });
  53875. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  53876. scene.updateTransformMatrix(true);
  53877. });
  53878. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  53879. }
  53880. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  53881. get: function () {
  53882. return this._renderTargetTexture.samples;
  53883. },
  53884. set: function (value) {
  53885. this._renderTargetTexture.samples = value;
  53886. },
  53887. enumerable: true,
  53888. configurable: true
  53889. });
  53890. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  53891. get: function () {
  53892. return this._renderTargetTexture.refreshRate;
  53893. },
  53894. set: function (value) {
  53895. this._renderTargetTexture.refreshRate = value;
  53896. },
  53897. enumerable: true,
  53898. configurable: true
  53899. });
  53900. ReflectionProbe.prototype.getScene = function () {
  53901. return this._scene;
  53902. };
  53903. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  53904. get: function () {
  53905. return this._renderTargetTexture;
  53906. },
  53907. enumerable: true,
  53908. configurable: true
  53909. });
  53910. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  53911. get: function () {
  53912. return this._renderTargetTexture.renderList;
  53913. },
  53914. enumerable: true,
  53915. configurable: true
  53916. });
  53917. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  53918. this._attachedMesh = mesh;
  53919. };
  53920. ReflectionProbe.prototype.dispose = function () {
  53921. var index = this._scene.reflectionProbes.indexOf(this);
  53922. if (index !== -1) {
  53923. // Remove from the scene if found
  53924. this._scene.reflectionProbes.splice(index, 1);
  53925. }
  53926. if (this._renderTargetTexture) {
  53927. this._renderTargetTexture.dispose();
  53928. this._renderTargetTexture = null;
  53929. }
  53930. };
  53931. return ReflectionProbe;
  53932. }());
  53933. BABYLON.ReflectionProbe = ReflectionProbe;
  53934. })(BABYLON || (BABYLON = {}));
  53935. //# sourceMappingURL=babylon.reflectionProbe.js.map
  53936. var BABYLON;
  53937. (function (BABYLON) {
  53938. var SolidParticle = (function () {
  53939. /**
  53940. * Creates a Solid Particle object.
  53941. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53942. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53943. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53944. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  53945. * `shapeId` (integer) is the model shape identifier in the SPS.
  53946. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53947. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  53948. */
  53949. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53950. this.idx = 0; // particle global index
  53951. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  53952. this.position = BABYLON.Vector3.Zero(); // position
  53953. this.rotation = BABYLON.Vector3.Zero(); // rotation
  53954. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  53955. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  53956. this.velocity = BABYLON.Vector3.Zero(); // velocity
  53957. this.alive = true; // alive
  53958. this.isVisible = true; // visibility
  53959. this._pos = 0; // index of this particle in the global "positions" array
  53960. this.shapeId = 0; // model shape id
  53961. this.idxInShape = 0; // index of the particle in its shape id
  53962. this.idx = particleIndex;
  53963. this._pos = positionIndex;
  53964. this._model = model;
  53965. this.shapeId = shapeId;
  53966. this.idxInShape = idxInShape;
  53967. this._sps = sps;
  53968. if (modelBoundingInfo) {
  53969. this._modelBoundingInfo = modelBoundingInfo;
  53970. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53971. }
  53972. }
  53973. Object.defineProperty(SolidParticle.prototype, "scale", {
  53974. /**
  53975. * legacy support, changed scale to scaling
  53976. */
  53977. get: function () {
  53978. return this.scaling;
  53979. },
  53980. set: function (scale) {
  53981. this.scaling = scale;
  53982. },
  53983. enumerable: true,
  53984. configurable: true
  53985. });
  53986. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53987. /**
  53988. * legacy support, changed quaternion to rotationQuaternion
  53989. */
  53990. get: function () {
  53991. return this.rotationQuaternion;
  53992. },
  53993. set: function (q) {
  53994. this.rotationQuaternion = q;
  53995. },
  53996. enumerable: true,
  53997. configurable: true
  53998. });
  53999. /**
  54000. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54001. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54002. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  54003. */
  54004. SolidParticle.prototype.intersectsMesh = function (target) {
  54005. if (!this._boundingInfo || !target._boundingInfo) {
  54006. return false;
  54007. }
  54008. if (this._sps._bSphereOnly) {
  54009. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54010. }
  54011. return this._boundingInfo.intersects(target._boundingInfo, false);
  54012. };
  54013. return SolidParticle;
  54014. }());
  54015. BABYLON.SolidParticle = SolidParticle;
  54016. var ModelShape = (function () {
  54017. /**
  54018. * 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.
  54019. * SPS internal tool, don't use it manually.
  54020. */
  54021. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  54022. this.shapeID = id;
  54023. this._shape = shape;
  54024. this._shapeUV = shapeUV;
  54025. this._positionFunction = posFunction;
  54026. this._vertexFunction = vtxFunction;
  54027. }
  54028. return ModelShape;
  54029. }());
  54030. BABYLON.ModelShape = ModelShape;
  54031. })(BABYLON || (BABYLON = {}));
  54032. //# sourceMappingURL=babylon.solidParticle.js.map
  54033. var BABYLON;
  54034. (function (BABYLON) {
  54035. /**
  54036. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54037. */
  54038. var SolidParticleSystem = (function () {
  54039. /**
  54040. * Creates a SPS (Solid Particle System) object.
  54041. * `name` (String) is the SPS name, this will be the underlying mesh name.
  54042. * `scene` (Scene) is the scene in which the SPS is added.
  54043. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  54044. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  54045. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  54046. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54047. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54048. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54049. */
  54050. function SolidParticleSystem(name, scene, options) {
  54051. // public members
  54052. /**
  54053. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54054. * Example : var p = SPS.particles[i];
  54055. */
  54056. this.particles = new Array();
  54057. /**
  54058. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54059. */
  54060. this.nbParticles = 0;
  54061. /**
  54062. * If the particles must ever face the camera (default false). Useful for planar particles.
  54063. */
  54064. this.billboard = false;
  54065. /**
  54066. * Recompute normals when adding a shape
  54067. */
  54068. this.recomputeNormals = true;
  54069. /**
  54070. * This a counter ofr your own usage. It's not set by any SPS functions.
  54071. */
  54072. this.counter = 0;
  54073. /**
  54074. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54075. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54076. */
  54077. this.vars = {};
  54078. this._positions = new Array();
  54079. this._indices = new Array();
  54080. this._normals = new Array();
  54081. this._colors = new Array();
  54082. this._uvs = new Array();
  54083. this._index = 0; // indices index
  54084. this._updatable = true;
  54085. this._pickable = false;
  54086. this._isVisibilityBoxLocked = false;
  54087. this._alwaysVisible = false;
  54088. this._shapeCounter = 0;
  54089. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  54090. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54091. this._computeParticleColor = true;
  54092. this._computeParticleTexture = true;
  54093. this._computeParticleRotation = true;
  54094. this._computeParticleVertex = false;
  54095. this._computeBoundingBox = false;
  54096. this._cam_axisZ = BABYLON.Vector3.Zero();
  54097. this._cam_axisY = BABYLON.Vector3.Zero();
  54098. this._cam_axisX = BABYLON.Vector3.Zero();
  54099. this._axisX = BABYLON.Axis.X;
  54100. this._axisY = BABYLON.Axis.Y;
  54101. this._axisZ = BABYLON.Axis.Z;
  54102. this._camDir = BABYLON.Vector3.Zero();
  54103. this._rotMatrix = new BABYLON.Matrix();
  54104. this._invertMatrix = new BABYLON.Matrix();
  54105. this._rotated = BABYLON.Vector3.Zero();
  54106. this._quaternion = new BABYLON.Quaternion();
  54107. this._vertex = BABYLON.Vector3.Zero();
  54108. this._normal = BABYLON.Vector3.Zero();
  54109. this._yaw = 0.0;
  54110. this._pitch = 0.0;
  54111. this._roll = 0.0;
  54112. this._halfroll = 0.0;
  54113. this._halfpitch = 0.0;
  54114. this._halfyaw = 0.0;
  54115. this._sinRoll = 0.0;
  54116. this._cosRoll = 0.0;
  54117. this._sinPitch = 0.0;
  54118. this._cosPitch = 0.0;
  54119. this._sinYaw = 0.0;
  54120. this._cosYaw = 0.0;
  54121. this._w = 0.0;
  54122. this._mustUnrotateFixedNormals = false;
  54123. this._minimum = BABYLON.Tmp.Vector3[0];
  54124. this._maximum = BABYLON.Tmp.Vector3[1];
  54125. this._scale = BABYLON.Tmp.Vector3[2];
  54126. this._translation = BABYLON.Tmp.Vector3[3];
  54127. this._minBbox = BABYLON.Tmp.Vector3[4];
  54128. this._maxBbox = BABYLON.Tmp.Vector3[5];
  54129. this._particlesIntersect = false;
  54130. this._bSphereOnly = false;
  54131. this._bSphereRadiusFactor = 1.0;
  54132. this.name = name;
  54133. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54134. this._camera = scene.activeCamera;
  54135. this._pickable = options ? options.isPickable : false;
  54136. this._particlesIntersect = options ? options.particleIntersection : false;
  54137. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54138. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54139. if (options && options.updatable) {
  54140. this._updatable = options.updatable;
  54141. }
  54142. else {
  54143. this._updatable = true;
  54144. }
  54145. if (this._pickable) {
  54146. this.pickedParticles = [];
  54147. }
  54148. }
  54149. /**
  54150. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54151. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54152. */
  54153. SolidParticleSystem.prototype.buildMesh = function () {
  54154. if (this.nbParticles === 0) {
  54155. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54156. this.addShape(triangle, 1);
  54157. triangle.dispose();
  54158. }
  54159. this._positions32 = new Float32Array(this._positions);
  54160. this._uvs32 = new Float32Array(this._uvs);
  54161. this._colors32 = new Float32Array(this._colors);
  54162. if (this.recomputeNormals) {
  54163. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  54164. }
  54165. this._normals32 = new Float32Array(this._normals);
  54166. this._fixedNormal32 = new Float32Array(this._normals);
  54167. if (this._mustUnrotateFixedNormals) {
  54168. this._unrotateFixedNormals();
  54169. }
  54170. var vertexData = new BABYLON.VertexData();
  54171. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54172. vertexData.indices = this._indices;
  54173. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54174. if (this._uvs32) {
  54175. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54176. ;
  54177. }
  54178. if (this._colors32) {
  54179. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54180. }
  54181. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54182. vertexData.applyToMesh(mesh, this._updatable);
  54183. this.mesh = mesh;
  54184. this.mesh.isPickable = this._pickable;
  54185. // free memory
  54186. this._positions = null;
  54187. this._normals = null;
  54188. this._uvs = null;
  54189. this._colors = null;
  54190. if (!this._updatable) {
  54191. this.particles.length = 0;
  54192. }
  54193. return mesh;
  54194. };
  54195. /**
  54196. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54197. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54198. * Thus the particles generated from `digest()` have their property `position` set yet.
  54199. * `mesh` ( Mesh ) is the mesh to be digested
  54200. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  54201. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54202. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54203. */
  54204. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54205. var size = (options && options.facetNb) || 1;
  54206. var number = (options && options.number);
  54207. var delta = (options && options.delta) || 0;
  54208. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54209. var meshInd = mesh.getIndices();
  54210. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54211. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54212. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54213. var f = 0; // facet counter
  54214. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54215. // compute size from number
  54216. if (number) {
  54217. number = (number > totalFacets) ? totalFacets : number;
  54218. size = Math.round(totalFacets / number);
  54219. delta = 0;
  54220. }
  54221. else {
  54222. size = (size > totalFacets) ? totalFacets : size;
  54223. }
  54224. var facetPos = []; // submesh positions
  54225. var facetInd = []; // submesh indices
  54226. var facetUV = []; // submesh UV
  54227. var facetCol = []; // submesh colors
  54228. var barycenter = BABYLON.Tmp.Vector3[0];
  54229. var rand;
  54230. var sizeO = size;
  54231. while (f < totalFacets) {
  54232. size = sizeO + Math.floor((1 + delta) * Math.random());
  54233. if (f > totalFacets - size) {
  54234. size = totalFacets - f;
  54235. }
  54236. // reset temp arrays
  54237. facetPos.length = 0;
  54238. facetInd.length = 0;
  54239. facetUV.length = 0;
  54240. facetCol.length = 0;
  54241. // iterate over "size" facets
  54242. var fi = 0;
  54243. for (var j = f * 3; j < (f + size) * 3; j++) {
  54244. facetInd.push(fi);
  54245. var i = meshInd[j];
  54246. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54247. if (meshUV) {
  54248. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54249. }
  54250. if (meshCol) {
  54251. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54252. }
  54253. fi++;
  54254. }
  54255. // create a model shape for each single particle
  54256. var idx = this.nbParticles;
  54257. var shape = this._posToShape(facetPos);
  54258. var shapeUV = this._uvsToShapeUV(facetUV);
  54259. // compute the barycenter of the shape
  54260. var v;
  54261. for (v = 0; v < shape.length; v++) {
  54262. barycenter.addInPlace(shape[v]);
  54263. }
  54264. barycenter.scaleInPlace(1 / shape.length);
  54265. // shift the shape from its barycenter to the origin
  54266. for (v = 0; v < shape.length; v++) {
  54267. shape[v].subtractInPlace(barycenter);
  54268. }
  54269. var bInfo;
  54270. if (this._particlesIntersect) {
  54271. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54272. }
  54273. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  54274. // add the particle in the SPS
  54275. var currentPos = this._positions.length;
  54276. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54277. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  54278. // initialize the particle position
  54279. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54280. this._index += shape.length;
  54281. idx++;
  54282. this.nbParticles++;
  54283. this._shapeCounter++;
  54284. f += size;
  54285. }
  54286. return this;
  54287. };
  54288. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54289. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54290. var index = 0;
  54291. var idx = 0;
  54292. for (var p = 0; p < this.particles.length; p++) {
  54293. this._particle = this.particles[p];
  54294. this._shape = this._particle._model._shape;
  54295. if (this._particle.rotationQuaternion) {
  54296. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54297. }
  54298. else {
  54299. this._yaw = this._particle.rotation.y;
  54300. this._pitch = this._particle.rotation.x;
  54301. this._roll = this._particle.rotation.z;
  54302. this._quaternionRotationYPR();
  54303. }
  54304. this._quaternionToRotationMatrix();
  54305. this._rotMatrix.invertToRef(this._invertMatrix);
  54306. for (var pt = 0; pt < this._shape.length; pt++) {
  54307. idx = index + pt * 3;
  54308. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54309. this._fixedNormal32[idx] = this._normal.x;
  54310. this._fixedNormal32[idx + 1] = this._normal.y;
  54311. this._fixedNormal32[idx + 2] = this._normal.z;
  54312. }
  54313. index = idx + 3;
  54314. }
  54315. };
  54316. //reset copy
  54317. SolidParticleSystem.prototype._resetCopy = function () {
  54318. this._copy.position.x = 0;
  54319. this._copy.position.y = 0;
  54320. this._copy.position.z = 0;
  54321. this._copy.rotation.x = 0;
  54322. this._copy.rotation.y = 0;
  54323. this._copy.rotation.z = 0;
  54324. this._copy.rotationQuaternion = null;
  54325. this._copy.scaling.x = 1;
  54326. this._copy.scaling.y = 1;
  54327. this._copy.scaling.z = 1;
  54328. this._copy.uvs.x = 0;
  54329. this._copy.uvs.y = 0;
  54330. this._copy.uvs.z = 1;
  54331. this._copy.uvs.w = 1;
  54332. this._copy.color = null;
  54333. };
  54334. // _meshBuilder : inserts the shape model in the global SPS mesh
  54335. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54336. var i;
  54337. var u = 0;
  54338. var c = 0;
  54339. var n = 0;
  54340. this._resetCopy();
  54341. if (options && options.positionFunction) {
  54342. options.positionFunction(this._copy, idx, idxInShape);
  54343. this._mustUnrotateFixedNormals = true;
  54344. }
  54345. if (this._copy.rotationQuaternion) {
  54346. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54347. }
  54348. else {
  54349. this._yaw = this._copy.rotation.y;
  54350. this._pitch = this._copy.rotation.x;
  54351. this._roll = this._copy.rotation.z;
  54352. this._quaternionRotationYPR();
  54353. }
  54354. this._quaternionToRotationMatrix();
  54355. for (i = 0; i < shape.length; i++) {
  54356. this._vertex.x = shape[i].x;
  54357. this._vertex.y = shape[i].y;
  54358. this._vertex.z = shape[i].z;
  54359. if (options && options.vertexFunction) {
  54360. options.vertexFunction(this._copy, this._vertex, i);
  54361. }
  54362. this._vertex.x *= this._copy.scaling.x;
  54363. this._vertex.y *= this._copy.scaling.y;
  54364. this._vertex.z *= this._copy.scaling.z;
  54365. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54366. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54367. if (meshUV) {
  54368. 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);
  54369. u += 2;
  54370. }
  54371. if (this._copy.color) {
  54372. this._color = this._copy.color;
  54373. }
  54374. else if (meshCol && meshCol[c] !== undefined) {
  54375. this._color.r = meshCol[c];
  54376. this._color.g = meshCol[c + 1];
  54377. this._color.b = meshCol[c + 2];
  54378. this._color.a = meshCol[c + 3];
  54379. }
  54380. else {
  54381. this._color.r = 1;
  54382. this._color.g = 1;
  54383. this._color.b = 1;
  54384. this._color.a = 1;
  54385. }
  54386. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54387. c += 4;
  54388. if (!this.recomputeNormals && meshNor) {
  54389. this._normal.x = meshNor[n];
  54390. this._normal.y = meshNor[n + 1];
  54391. this._normal.z = meshNor[n + 2];
  54392. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54393. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54394. n += 3;
  54395. }
  54396. }
  54397. for (i = 0; i < meshInd.length; i++) {
  54398. indices.push(p + meshInd[i]);
  54399. }
  54400. if (this._pickable) {
  54401. var nbfaces = meshInd.length / 3;
  54402. for (i = 0; i < nbfaces; i++) {
  54403. this.pickedParticles.push({ idx: idx, faceId: i });
  54404. }
  54405. }
  54406. return this._copy;
  54407. };
  54408. // returns a shape array from positions array
  54409. SolidParticleSystem.prototype._posToShape = function (positions) {
  54410. var shape = [];
  54411. for (var i = 0; i < positions.length; i += 3) {
  54412. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54413. }
  54414. return shape;
  54415. };
  54416. // returns a shapeUV array from a Vector4 uvs
  54417. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54418. var shapeUV = [];
  54419. if (uvs) {
  54420. for (var i = 0; i < uvs.length; i++)
  54421. shapeUV.push(uvs[i]);
  54422. }
  54423. return shapeUV;
  54424. };
  54425. // adds a new particle object in the particles array
  54426. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  54427. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  54428. this.particles.push(sp);
  54429. return sp;
  54430. };
  54431. /**
  54432. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54433. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54434. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  54435. * `nb` (positive integer) the number of particles to be created from this model
  54436. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  54437. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  54438. */
  54439. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54440. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54441. var meshInd = mesh.getIndices();
  54442. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54443. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54444. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54445. var bbInfo;
  54446. if (this._particlesIntersect) {
  54447. bbInfo = mesh.getBoundingInfo();
  54448. }
  54449. var shape = this._posToShape(meshPos);
  54450. var shapeUV = this._uvsToShapeUV(meshUV);
  54451. var posfunc = options ? options.positionFunction : null;
  54452. var vtxfunc = options ? options.vertexFunction : null;
  54453. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  54454. // particles
  54455. var sp;
  54456. var currentCopy;
  54457. var idx = this.nbParticles;
  54458. for (var i = 0; i < nb; i++) {
  54459. var currentPos = this._positions.length;
  54460. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54461. if (this._updatable) {
  54462. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  54463. sp.position.copyFrom(currentCopy.position);
  54464. sp.rotation.copyFrom(currentCopy.rotation);
  54465. if (currentCopy.rotationQuaternion) {
  54466. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54467. }
  54468. if (currentCopy.color) {
  54469. sp.color.copyFrom(currentCopy.color);
  54470. }
  54471. sp.scaling.copyFrom(currentCopy.scaling);
  54472. sp.uvs.copyFrom(currentCopy.uvs);
  54473. }
  54474. this._index += shape.length;
  54475. idx++;
  54476. }
  54477. this.nbParticles += nb;
  54478. this._shapeCounter++;
  54479. return this._shapeCounter - 1;
  54480. };
  54481. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54482. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54483. this._resetCopy();
  54484. if (particle._model._positionFunction) {
  54485. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54486. }
  54487. if (this._copy.rotationQuaternion) {
  54488. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54489. }
  54490. else {
  54491. this._yaw = this._copy.rotation.y;
  54492. this._pitch = this._copy.rotation.x;
  54493. this._roll = this._copy.rotation.z;
  54494. this._quaternionRotationYPR();
  54495. }
  54496. this._quaternionToRotationMatrix();
  54497. this._shape = particle._model._shape;
  54498. for (var pt = 0; pt < this._shape.length; pt++) {
  54499. this._vertex.x = this._shape[pt].x;
  54500. this._vertex.y = this._shape[pt].y;
  54501. this._vertex.z = this._shape[pt].z;
  54502. if (particle._model._vertexFunction) {
  54503. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54504. }
  54505. this._vertex.x *= this._copy.scaling.x;
  54506. this._vertex.y *= this._copy.scaling.y;
  54507. this._vertex.z *= this._copy.scaling.z;
  54508. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54509. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54510. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54511. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54512. }
  54513. particle.position.x = 0.0;
  54514. particle.position.y = 0.0;
  54515. particle.position.z = 0.0;
  54516. particle.rotation.x = 0.0;
  54517. particle.rotation.y = 0.0;
  54518. particle.rotation.z = 0.0;
  54519. particle.rotationQuaternion = null;
  54520. particle.scaling.x = 1.0;
  54521. particle.scaling.y = 1.0;
  54522. particle.scaling.z = 1.0;
  54523. };
  54524. /**
  54525. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54526. * Returns the SPS.
  54527. */
  54528. SolidParticleSystem.prototype.rebuildMesh = function () {
  54529. for (var p = 0; p < this.particles.length; p++) {
  54530. this._rebuildParticle(this.particles[p]);
  54531. }
  54532. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54533. return this;
  54534. };
  54535. /**
  54536. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54537. * This method calls `updateParticle()` for each particle of the SPS.
  54538. * For an animated SPS, it is usually called within the render loop.
  54539. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54540. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54541. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54542. * Returns the SPS.
  54543. */
  54544. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54545. if (start === void 0) { start = 0; }
  54546. if (end === void 0) { end = this.nbParticles - 1; }
  54547. if (update === void 0) { update = true; }
  54548. if (!this._updatable) {
  54549. return;
  54550. }
  54551. // custom beforeUpdate
  54552. this.beforeUpdateParticles(start, end, update);
  54553. this._cam_axisX.x = 1.0;
  54554. this._cam_axisX.y = 0.0;
  54555. this._cam_axisX.z = 0.0;
  54556. this._cam_axisY.x = 0.0;
  54557. this._cam_axisY.y = 1.0;
  54558. this._cam_axisY.z = 0.0;
  54559. this._cam_axisZ.x = 0.0;
  54560. this._cam_axisZ.y = 0.0;
  54561. this._cam_axisZ.z = 1.0;
  54562. // if the particles will always face the camera
  54563. if (this.billboard) {
  54564. this.mesh.computeWorldMatrix(true);
  54565. // compute the camera position and un-rotate it by the current mesh rotation
  54566. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  54567. this._quaternionToRotationMatrix();
  54568. this._rotMatrix.invertToRef(this._invertMatrix);
  54569. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  54570. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54571. this._cam_axisZ.normalize();
  54572. // same for camera up vector extracted from the cam view matrix
  54573. var view = this._camera.getViewMatrix(true);
  54574. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54575. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54576. this._cam_axisY.normalize();
  54577. this._cam_axisX.normalize();
  54578. }
  54579. }
  54580. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54581. var idx = 0; // current position index in the global array positions32
  54582. var index = 0; // position start index in the global array positions32 of the current particle
  54583. var colidx = 0; // current color index in the global array colors32
  54584. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54585. var uvidx = 0; // current uv index in the global array uvs32
  54586. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54587. var pt = 0; // current index in the particle model shape
  54588. if (this.mesh.isFacetDataEnabled) {
  54589. this._computeBoundingBox = true;
  54590. }
  54591. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54592. if (this._computeBoundingBox) {
  54593. if (start == 0 && end == this.nbParticles - 1) {
  54594. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54595. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54596. }
  54597. else {
  54598. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54599. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54600. }
  54601. }
  54602. // particle loop
  54603. index = this.particles[start]._pos;
  54604. var vpos = (index / 3) | 0;
  54605. colorIndex = vpos * 4;
  54606. uvIndex = vpos * 2;
  54607. for (var p = start; p <= end; p++) {
  54608. this._particle = this.particles[p];
  54609. this._shape = this._particle._model._shape;
  54610. this._shapeUV = this._particle._model._shapeUV;
  54611. // call to custom user function to update the particle properties
  54612. this.updateParticle(this._particle);
  54613. if (this._particle.isVisible) {
  54614. // particle rotation matrix
  54615. if (this.billboard) {
  54616. this._particle.rotation.x = 0.0;
  54617. this._particle.rotation.y = 0.0;
  54618. }
  54619. if (this._computeParticleRotation || this.billboard) {
  54620. if (this._particle.rotationQuaternion) {
  54621. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54622. }
  54623. else {
  54624. this._yaw = this._particle.rotation.y;
  54625. this._pitch = this._particle.rotation.x;
  54626. this._roll = this._particle.rotation.z;
  54627. this._quaternionRotationYPR();
  54628. }
  54629. this._quaternionToRotationMatrix();
  54630. }
  54631. // particle vertex loop
  54632. for (pt = 0; pt < this._shape.length; pt++) {
  54633. idx = index + pt * 3;
  54634. colidx = colorIndex + pt * 4;
  54635. uvidx = uvIndex + pt * 2;
  54636. this._vertex.x = this._shape[pt].x;
  54637. this._vertex.y = this._shape[pt].y;
  54638. this._vertex.z = this._shape[pt].z;
  54639. if (this._computeParticleVertex) {
  54640. this.updateParticleVertex(this._particle, this._vertex, pt);
  54641. }
  54642. // positions
  54643. this._vertex.x *= this._particle.scaling.x;
  54644. this._vertex.y *= this._particle.scaling.y;
  54645. this._vertex.z *= this._particle.scaling.z;
  54646. 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];
  54647. 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;
  54648. 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;
  54649. 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;
  54650. 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;
  54651. 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;
  54652. 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;
  54653. if (this._computeBoundingBox) {
  54654. if (this._positions32[idx] < this._minimum.x) {
  54655. this._minimum.x = this._positions32[idx];
  54656. }
  54657. if (this._positions32[idx] > this._maximum.x) {
  54658. this._maximum.x = this._positions32[idx];
  54659. }
  54660. if (this._positions32[idx + 1] < this._minimum.y) {
  54661. this._minimum.y = this._positions32[idx + 1];
  54662. }
  54663. if (this._positions32[idx + 1] > this._maximum.y) {
  54664. this._maximum.y = this._positions32[idx + 1];
  54665. }
  54666. if (this._positions32[idx + 2] < this._minimum.z) {
  54667. this._minimum.z = this._positions32[idx + 2];
  54668. }
  54669. if (this._positions32[idx + 2] > this._maximum.z) {
  54670. this._maximum.z = this._positions32[idx + 2];
  54671. }
  54672. }
  54673. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54674. if (!this._computeParticleVertex) {
  54675. this._normal.x = this._fixedNormal32[idx];
  54676. this._normal.y = this._fixedNormal32[idx + 1];
  54677. this._normal.z = this._fixedNormal32[idx + 2];
  54678. 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]);
  54679. 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]);
  54680. 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]);
  54681. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54682. 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;
  54683. 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;
  54684. }
  54685. if (this._computeParticleColor) {
  54686. this._colors32[colidx] = this._particle.color.r;
  54687. this._colors32[colidx + 1] = this._particle.color.g;
  54688. this._colors32[colidx + 2] = this._particle.color.b;
  54689. this._colors32[colidx + 3] = this._particle.color.a;
  54690. }
  54691. if (this._computeParticleTexture) {
  54692. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54693. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54694. }
  54695. }
  54696. }
  54697. else {
  54698. for (pt = 0; pt < this._shape.length; pt++) {
  54699. idx = index + pt * 3;
  54700. colidx = colorIndex + pt * 4;
  54701. uvidx = uvIndex + pt * 2;
  54702. this._positions32[idx] = this._camera.position.x;
  54703. this._positions32[idx + 1] = this._camera.position.y;
  54704. this._positions32[idx + 2] = this._camera.position.z;
  54705. this._normals32[idx] = 0.0;
  54706. this._normals32[idx + 1] = 0.0;
  54707. this._normals32[idx + 2] = 0.0;
  54708. if (this._computeParticleColor) {
  54709. this._colors32[colidx] = this._particle.color.r;
  54710. this._colors32[colidx + 1] = this._particle.color.g;
  54711. this._colors32[colidx + 2] = this._particle.color.b;
  54712. this._colors32[colidx + 3] = this._particle.color.a;
  54713. }
  54714. if (this._computeParticleTexture) {
  54715. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54716. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54717. }
  54718. }
  54719. }
  54720. // if the particle intersections must be computed : update the bbInfo
  54721. if (this._particlesIntersect) {
  54722. var bInfo = this._particle._boundingInfo;
  54723. var bBox = bInfo.boundingBox;
  54724. var bSphere = bInfo.boundingSphere;
  54725. if (!this._bSphereOnly) {
  54726. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54727. for (var b = 0; b < bBox.vectors.length; b++) {
  54728. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54729. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54730. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54731. 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];
  54732. 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;
  54733. 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;
  54734. 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;
  54735. 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;
  54736. 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;
  54737. 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;
  54738. }
  54739. bBox._update(this.mesh._worldMatrix);
  54740. }
  54741. // place and scale the particle bouding sphere in the SPS local system, then update it
  54742. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54743. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54744. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54745. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54746. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54747. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54748. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54749. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54750. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54751. 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));
  54752. bSphere._update(this.mesh._worldMatrix);
  54753. }
  54754. // increment indexes for the next particle
  54755. index = idx + 3;
  54756. colorIndex = colidx + 4;
  54757. uvIndex = uvidx + 2;
  54758. }
  54759. // if the VBO must be updated
  54760. if (update) {
  54761. if (this._computeParticleColor) {
  54762. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54763. }
  54764. if (this._computeParticleTexture) {
  54765. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54766. }
  54767. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54768. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54769. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54770. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54771. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54772. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  54773. for (var i = 0; i < this._normals32.length; i++) {
  54774. this._fixedNormal32[i] = this._normals32[i];
  54775. }
  54776. }
  54777. if (!this.mesh.areNormalsFrozen) {
  54778. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54779. }
  54780. }
  54781. }
  54782. if (this._computeBoundingBox) {
  54783. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54784. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54785. }
  54786. this.afterUpdateParticles(start, end, update);
  54787. return this;
  54788. };
  54789. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54790. this._halfroll = this._roll * 0.5;
  54791. this._halfpitch = this._pitch * 0.5;
  54792. this._halfyaw = this._yaw * 0.5;
  54793. this._sinRoll = Math.sin(this._halfroll);
  54794. this._cosRoll = Math.cos(this._halfroll);
  54795. this._sinPitch = Math.sin(this._halfpitch);
  54796. this._cosPitch = Math.cos(this._halfpitch);
  54797. this._sinYaw = Math.sin(this._halfyaw);
  54798. this._cosYaw = Math.cos(this._halfyaw);
  54799. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  54800. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  54801. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  54802. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  54803. };
  54804. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54805. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54806. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54807. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54808. this._rotMatrix.m[3] = 0;
  54809. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54810. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54811. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54812. this._rotMatrix.m[7] = 0;
  54813. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54814. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54815. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54816. this._rotMatrix.m[11] = 0;
  54817. this._rotMatrix.m[12] = 0;
  54818. this._rotMatrix.m[13] = 0;
  54819. this._rotMatrix.m[14] = 0;
  54820. this._rotMatrix.m[15] = 1.0;
  54821. };
  54822. /**
  54823. * Disposes the SPS.
  54824. * Returns nothing.
  54825. */
  54826. SolidParticleSystem.prototype.dispose = function () {
  54827. this.mesh.dispose();
  54828. this.vars = null;
  54829. // drop references to internal big arrays for the GC
  54830. this._positions = null;
  54831. this._indices = null;
  54832. this._normals = null;
  54833. this._uvs = null;
  54834. this._colors = null;
  54835. this._positions32 = null;
  54836. this._normals32 = null;
  54837. this._fixedNormal32 = null;
  54838. this._uvs32 = null;
  54839. this._colors32 = null;
  54840. this.pickedParticles = null;
  54841. };
  54842. /**
  54843. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54844. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54845. * Returns the SPS.
  54846. */
  54847. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54848. if (!this._isVisibilityBoxLocked) {
  54849. this.mesh.refreshBoundingInfo();
  54850. }
  54851. return this;
  54852. };
  54853. /**
  54854. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54855. * @param size the size (float) of the visibility box
  54856. * note : this doesn't lock the SPS mesh bounding box.
  54857. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54858. */
  54859. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54860. var vis = size / 2;
  54861. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54862. };
  54863. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54864. // getter and setter
  54865. get: function () {
  54866. return this._alwaysVisible;
  54867. },
  54868. /**
  54869. * Sets the SPS as always visible or not
  54870. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54871. */
  54872. set: function (val) {
  54873. this._alwaysVisible = val;
  54874. this.mesh.alwaysSelectAsActiveMesh = val;
  54875. },
  54876. enumerable: true,
  54877. configurable: true
  54878. });
  54879. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54880. get: function () {
  54881. return this._isVisibilityBoxLocked;
  54882. },
  54883. /**
  54884. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54885. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54886. */
  54887. set: function (val) {
  54888. this._isVisibilityBoxLocked = val;
  54889. this.mesh.getBoundingInfo().isLocked = val;
  54890. },
  54891. enumerable: true,
  54892. configurable: true
  54893. });
  54894. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54895. // getters
  54896. get: function () {
  54897. return this._computeParticleRotation;
  54898. },
  54899. // Optimizer setters
  54900. /**
  54901. * Tells to `setParticles()` to compute the particle rotations or not.
  54902. * Default value : true. The SPS is faster when it's set to false.
  54903. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54904. */
  54905. set: function (val) {
  54906. this._computeParticleRotation = val;
  54907. },
  54908. enumerable: true,
  54909. configurable: true
  54910. });
  54911. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54912. get: function () {
  54913. return this._computeParticleColor;
  54914. },
  54915. /**
  54916. * Tells to `setParticles()` to compute the particle colors or not.
  54917. * Default value : true. The SPS is faster when it's set to false.
  54918. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54919. */
  54920. set: function (val) {
  54921. this._computeParticleColor = val;
  54922. },
  54923. enumerable: true,
  54924. configurable: true
  54925. });
  54926. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54927. get: function () {
  54928. return this._computeParticleTexture;
  54929. },
  54930. /**
  54931. * Tells to `setParticles()` to compute the particle textures or not.
  54932. * Default value : true. The SPS is faster when it's set to false.
  54933. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54934. */
  54935. set: function (val) {
  54936. this._computeParticleTexture = val;
  54937. },
  54938. enumerable: true,
  54939. configurable: true
  54940. });
  54941. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54942. get: function () {
  54943. return this._computeParticleVertex;
  54944. },
  54945. /**
  54946. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54947. * Default value : false. The SPS is faster when it's set to false.
  54948. * Note : the particle custom vertex positions aren't stored values.
  54949. */
  54950. set: function (val) {
  54951. this._computeParticleVertex = val;
  54952. },
  54953. enumerable: true,
  54954. configurable: true
  54955. });
  54956. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54957. get: function () {
  54958. return this._computeBoundingBox;
  54959. },
  54960. /**
  54961. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54962. */
  54963. set: function (val) {
  54964. this._computeBoundingBox = val;
  54965. },
  54966. enumerable: true,
  54967. configurable: true
  54968. });
  54969. // =======================================================================
  54970. // Particle behavior logic
  54971. // these following methods may be overwritten by the user to fit his needs
  54972. /**
  54973. * This function does nothing. It may be overwritten to set all the particle first values.
  54974. * The SPS doesn't call this function, you may have to call it by your own.
  54975. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54976. */
  54977. SolidParticleSystem.prototype.initParticles = function () {
  54978. };
  54979. /**
  54980. * This function does nothing. It may be overwritten to recycle a particle.
  54981. * The SPS doesn't call this function, you may have to call it by your own.
  54982. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54983. */
  54984. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54985. return particle;
  54986. };
  54987. /**
  54988. * Updates a particle : this function should be overwritten by the user.
  54989. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54990. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54991. * ex : just set a particle position or velocity and recycle conditions
  54992. */
  54993. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54994. return particle;
  54995. };
  54996. /**
  54997. * Updates a vertex of a particle : it can be overwritten by the user.
  54998. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54999. * @param particle the current particle
  55000. * @param vertex the current index of the current particle
  55001. * @param pt the index of the current vertex in the particle shape
  55002. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55003. * ex : just set a vertex particle position
  55004. */
  55005. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55006. return vertex;
  55007. };
  55008. /**
  55009. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55010. * This does nothing and may be overwritten by the user.
  55011. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55012. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55013. * @param update the boolean update value actually passed to setParticles()
  55014. */
  55015. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55016. };
  55017. /**
  55018. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55019. * This will be passed three parameters.
  55020. * This does nothing and may be overwritten by the user.
  55021. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55022. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55023. * @param update the boolean update value actually passed to setParticles()
  55024. */
  55025. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55026. };
  55027. return SolidParticleSystem;
  55028. }());
  55029. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55030. })(BABYLON || (BABYLON = {}));
  55031. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55032. var BABYLON;
  55033. (function (BABYLON) {
  55034. var Internals;
  55035. (function (Internals) {
  55036. var FileFaceOrientation = (function () {
  55037. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  55038. this.name = name;
  55039. this.worldAxisForNormal = worldAxisForNormal;
  55040. this.worldAxisForFileX = worldAxisForFileX;
  55041. this.worldAxisForFileY = worldAxisForFileY;
  55042. }
  55043. return FileFaceOrientation;
  55044. }());
  55045. ;
  55046. /**
  55047. * Helper class dealing with the extraction of spherical polynomial dataArray
  55048. * from a cube map.
  55049. */
  55050. var CubeMapToSphericalPolynomialTools = (function () {
  55051. function CubeMapToSphericalPolynomialTools() {
  55052. }
  55053. /**
  55054. * Converts a cubemap to the according Spherical Polynomial data.
  55055. * This extracts the first 3 orders only as they are the only one used in the lighting.
  55056. *
  55057. * @param cubeInfo The Cube map to extract the information from.
  55058. * @return The Spherical Polynomial data.
  55059. */
  55060. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  55061. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  55062. var totalSolidAngle = 0.0;
  55063. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  55064. var du = 2.0 / cubeInfo.size;
  55065. var dv = du;
  55066. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  55067. var minUV = du * 0.5 - 1.0;
  55068. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  55069. var fileFace = this.FileFaces[faceIndex];
  55070. var dataArray = cubeInfo[fileFace.name];
  55071. var v = minUV;
  55072. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  55073. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  55074. // Because SP is still linear, so summation is fine in that basis.
  55075. for (var y = 0; y < cubeInfo.size; y++) {
  55076. var u = minUV;
  55077. for (var x = 0; x < cubeInfo.size; x++) {
  55078. // World direction (not normalised)
  55079. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  55080. worldDirection.normalize();
  55081. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  55082. if (1) {
  55083. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  55084. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  55085. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  55086. var color = new BABYLON.Color3(r, g, b);
  55087. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55088. }
  55089. else {
  55090. if (faceIndex == 0) {
  55091. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55092. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55093. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55094. }
  55095. else if (faceIndex == 1) {
  55096. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55097. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55098. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55099. }
  55100. else if (faceIndex == 2) {
  55101. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55102. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55103. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55104. }
  55105. else if (faceIndex == 3) {
  55106. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55107. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55108. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  55109. }
  55110. else if (faceIndex == 4) {
  55111. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  55112. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  55113. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55114. }
  55115. else if (faceIndex == 5) {
  55116. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  55117. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  55118. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  55119. }
  55120. 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]);
  55121. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  55122. }
  55123. totalSolidAngle += deltaSolidAngle;
  55124. u += du;
  55125. }
  55126. v += dv;
  55127. }
  55128. }
  55129. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  55130. var correction = correctSolidAngle / totalSolidAngle;
  55131. sphericalHarmonics.scale(correction);
  55132. // Additionally scale by pi -- audit needed
  55133. sphericalHarmonics.scale(1.0 / Math.PI);
  55134. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  55135. };
  55136. return CubeMapToSphericalPolynomialTools;
  55137. }());
  55138. CubeMapToSphericalPolynomialTools.FileFaces = [
  55139. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  55140. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  55141. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  55142. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  55143. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  55144. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  55145. ];
  55146. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  55147. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55148. })(BABYLON || (BABYLON = {}));
  55149. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  55150. var BABYLON;
  55151. (function (BABYLON) {
  55152. var Internals;
  55153. (function (Internals) {
  55154. /**
  55155. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  55156. */
  55157. var PanoramaToCubeMapTools = (function () {
  55158. function PanoramaToCubeMapTools() {
  55159. }
  55160. /**
  55161. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  55162. *
  55163. * @param float32Array The source data.
  55164. * @param inputWidth The width of the input panorama.
  55165. * @param inputhHeight The height of the input panorama.
  55166. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  55167. * @return The cubemap data
  55168. */
  55169. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  55170. if (!float32Array) {
  55171. throw "ConvertPanoramaToCubemap: input cannot be null";
  55172. }
  55173. if (float32Array.length != inputWidth * inputHeight * 3) {
  55174. throw "ConvertPanoramaToCubemap: input size is wrong";
  55175. }
  55176. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  55177. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  55178. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  55179. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  55180. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  55181. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  55182. return {
  55183. front: textureFront,
  55184. back: textureBack,
  55185. left: textureLeft,
  55186. right: textureRight,
  55187. up: textureUp,
  55188. down: textureDown,
  55189. size: size
  55190. };
  55191. };
  55192. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  55193. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  55194. var textureArray = new Float32Array(buffer);
  55195. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  55196. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  55197. var dy = 1 / texSize;
  55198. var fy = 0;
  55199. for (var y = 0; y < texSize; y++) {
  55200. var xv1 = faceData[0];
  55201. var xv2 = faceData[2];
  55202. for (var x = 0; x < texSize; x++) {
  55203. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  55204. v.normalize();
  55205. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  55206. // 3 channels per pixels
  55207. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  55208. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  55209. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  55210. xv1 = xv1.add(rotDX1);
  55211. xv2 = xv2.add(rotDX2);
  55212. }
  55213. fy += dy;
  55214. }
  55215. return textureArray;
  55216. };
  55217. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  55218. var theta = Math.atan2(vDir.z, vDir.x);
  55219. var phi = Math.acos(vDir.y);
  55220. while (theta < -Math.PI)
  55221. theta += 2 * Math.PI;
  55222. while (theta > Math.PI)
  55223. theta -= 2 * Math.PI;
  55224. var dx = theta / Math.PI;
  55225. var dy = phi / Math.PI;
  55226. // recenter.
  55227. dx = dx * 0.5 + 0.5;
  55228. var px = Math.round(dx * inputWidth);
  55229. if (px < 0)
  55230. px = 0;
  55231. else if (px >= inputWidth)
  55232. px = inputWidth - 1;
  55233. var py = Math.round(dy * inputHeight);
  55234. if (py < 0)
  55235. py = 0;
  55236. else if (py >= inputHeight)
  55237. py = inputHeight - 1;
  55238. var inputY = (inputHeight - py - 1);
  55239. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  55240. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  55241. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  55242. return {
  55243. r: r,
  55244. g: g,
  55245. b: b
  55246. };
  55247. };
  55248. return PanoramaToCubeMapTools;
  55249. }());
  55250. PanoramaToCubeMapTools.FACE_FRONT = [
  55251. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55252. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55253. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55254. new BABYLON.Vector3(1.0, 1.0, -1.0)
  55255. ];
  55256. PanoramaToCubeMapTools.FACE_BACK = [
  55257. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55258. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55259. new BABYLON.Vector3(1.0, 1.0, 1.0),
  55260. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  55261. ];
  55262. PanoramaToCubeMapTools.FACE_RIGHT = [
  55263. new BABYLON.Vector3(1.0, -1.0, -1.0),
  55264. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55265. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55266. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55267. ];
  55268. PanoramaToCubeMapTools.FACE_LEFT = [
  55269. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55270. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55271. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55272. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  55273. ];
  55274. PanoramaToCubeMapTools.FACE_DOWN = [
  55275. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  55276. new BABYLON.Vector3(1.0, 1.0, -1.0),
  55277. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  55278. new BABYLON.Vector3(1.0, 1.0, 1.0)
  55279. ];
  55280. PanoramaToCubeMapTools.FACE_UP = [
  55281. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  55282. new BABYLON.Vector3(1.0, -1.0, 1.0),
  55283. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  55284. new BABYLON.Vector3(1.0, -1.0, -1.0)
  55285. ];
  55286. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  55287. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55288. })(BABYLON || (BABYLON = {}));
  55289. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  55290. var BABYLON;
  55291. (function (BABYLON) {
  55292. var Internals;
  55293. (function (Internals) {
  55294. ;
  55295. /**
  55296. * This groups tools to convert HDR texture to native colors array.
  55297. */
  55298. var HDRTools = (function () {
  55299. function HDRTools() {
  55300. }
  55301. HDRTools.Ldexp = function (mantissa, exponent) {
  55302. if (exponent > 1023) {
  55303. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  55304. }
  55305. if (exponent < -1074) {
  55306. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  55307. }
  55308. return mantissa * Math.pow(2, exponent);
  55309. };
  55310. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  55311. if (exponent > 0) {
  55312. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  55313. float32array[index + 0] = red * exponent;
  55314. float32array[index + 1] = green * exponent;
  55315. float32array[index + 2] = blue * exponent;
  55316. }
  55317. else {
  55318. float32array[index + 0] = 0;
  55319. float32array[index + 1] = 0;
  55320. float32array[index + 2] = 0;
  55321. }
  55322. };
  55323. HDRTools.readStringLine = function (uint8array, startIndex) {
  55324. var line = "";
  55325. var character = "";
  55326. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  55327. character = String.fromCharCode(uint8array[i]);
  55328. if (character == "\n") {
  55329. break;
  55330. }
  55331. line += character;
  55332. }
  55333. return line;
  55334. };
  55335. /**
  55336. * Reads header information from an RGBE texture stored in a native array.
  55337. * More information on this format are available here:
  55338. * https://en.wikipedia.org/wiki/RGBE_image_format
  55339. *
  55340. * @param uint8array The binary file stored in native array.
  55341. * @return The header information.
  55342. */
  55343. HDRTools.RGBE_ReadHeader = function (uint8array) {
  55344. var height = 0;
  55345. var width = 0;
  55346. var line = this.readStringLine(uint8array, 0);
  55347. if (line[0] != '#' || line[1] != '?') {
  55348. throw "Bad HDR Format.";
  55349. }
  55350. var endOfHeader = false;
  55351. var findFormat = false;
  55352. var lineIndex = 0;
  55353. do {
  55354. lineIndex += (line.length + 1);
  55355. line = this.readStringLine(uint8array, lineIndex);
  55356. if (line == "FORMAT=32-bit_rle_rgbe") {
  55357. findFormat = true;
  55358. }
  55359. else if (line.length == 0) {
  55360. endOfHeader = true;
  55361. }
  55362. } while (!endOfHeader);
  55363. if (!findFormat) {
  55364. throw "HDR Bad header format, unsupported FORMAT";
  55365. }
  55366. lineIndex += (line.length + 1);
  55367. line = this.readStringLine(uint8array, lineIndex);
  55368. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  55369. var match = sizeRegexp.exec(line);
  55370. // TODO. Support +Y and -X if needed.
  55371. if (match.length < 3) {
  55372. throw "HDR Bad header format, no size";
  55373. }
  55374. width = parseInt(match[2]);
  55375. height = parseInt(match[1]);
  55376. if (width < 8 || width > 0x7fff) {
  55377. throw "HDR Bad header format, unsupported size";
  55378. }
  55379. lineIndex += (line.length + 1);
  55380. return {
  55381. height: height,
  55382. width: width,
  55383. dataPosition: lineIndex
  55384. };
  55385. };
  55386. /**
  55387. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  55388. * This RGBE texture needs to store the information as a panorama.
  55389. *
  55390. * More information on this format are available here:
  55391. * https://en.wikipedia.org/wiki/RGBE_image_format
  55392. *
  55393. * @param buffer The binary file stored in an array buffer.
  55394. * @param size The expected size of the extracted cubemap.
  55395. * @return The Cube Map information.
  55396. */
  55397. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  55398. var uint8array = new Uint8Array(buffer);
  55399. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  55400. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55401. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  55402. return cubeMapData;
  55403. };
  55404. /**
  55405. * Returns the pixels data extracted from an RGBE texture.
  55406. * This pixels will be stored left to right up to down in the R G B order in one array.
  55407. *
  55408. * More information on this format are available here:
  55409. * https://en.wikipedia.org/wiki/RGBE_image_format
  55410. *
  55411. * @param uint8array The binary file stored in an array buffer.
  55412. * @param hdrInfo The header information of the file.
  55413. * @return The pixels data in RGB right to left up to down order.
  55414. */
  55415. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  55416. // Keep for multi format supports.
  55417. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  55418. };
  55419. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  55420. var num_scanlines = hdrInfo.height;
  55421. var scanline_width = hdrInfo.width;
  55422. var a, b, c, d, count;
  55423. var dataIndex = hdrInfo.dataPosition;
  55424. var index = 0, endIndex = 0, i = 0;
  55425. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  55426. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  55427. // 3 channels of 4 bytes per pixel in float.
  55428. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  55429. var resultArray = new Float32Array(resultBuffer);
  55430. // read in each successive scanline
  55431. while (num_scanlines > 0) {
  55432. a = uint8array[dataIndex++];
  55433. b = uint8array[dataIndex++];
  55434. c = uint8array[dataIndex++];
  55435. d = uint8array[dataIndex++];
  55436. if (a != 2 || b != 2 || (c & 0x80)) {
  55437. // this file is not run length encoded
  55438. throw "HDR Bad header format, not RLE";
  55439. }
  55440. if (((c << 8) | d) != scanline_width) {
  55441. throw "HDR Bad header format, wrong scan line width";
  55442. }
  55443. index = 0;
  55444. // read each of the four channels for the scanline into the buffer
  55445. for (i = 0; i < 4; i++) {
  55446. endIndex = (i + 1) * scanline_width;
  55447. while (index < endIndex) {
  55448. a = uint8array[dataIndex++];
  55449. b = uint8array[dataIndex++];
  55450. if (a > 128) {
  55451. // a run of the same value
  55452. count = a - 128;
  55453. if ((count == 0) || (count > endIndex - index)) {
  55454. throw "HDR Bad Format, bad scanline data (run)";
  55455. }
  55456. while (count-- > 0) {
  55457. scanLineArray[index++] = b;
  55458. }
  55459. }
  55460. else {
  55461. // a non-run
  55462. count = a;
  55463. if ((count == 0) || (count > endIndex - index)) {
  55464. throw "HDR Bad Format, bad scanline data (non-run)";
  55465. }
  55466. scanLineArray[index++] = b;
  55467. if (--count > 0) {
  55468. for (var j = 0; j < count; j++) {
  55469. scanLineArray[index++] = uint8array[dataIndex++];
  55470. }
  55471. }
  55472. }
  55473. }
  55474. }
  55475. // now convert data from buffer into floats
  55476. for (i = 0; i < scanline_width; i++) {
  55477. a = scanLineArray[i];
  55478. b = scanLineArray[i + scanline_width];
  55479. c = scanLineArray[i + 2 * scanline_width];
  55480. d = scanLineArray[i + 3 * scanline_width];
  55481. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  55482. }
  55483. num_scanlines--;
  55484. }
  55485. return resultArray;
  55486. };
  55487. return HDRTools;
  55488. }());
  55489. Internals.HDRTools = HDRTools;
  55490. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55491. })(BABYLON || (BABYLON = {}));
  55492. //# sourceMappingURL=babylon.tools.hdr.js.map
  55493. //_______________________________________________________________
  55494. // Extracted from CubeMapGen:
  55495. // https://code.google.com/archive/p/cubemapgen/
  55496. //
  55497. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55498. //_______________________________________________________________
  55499. var BABYLON;
  55500. (function (BABYLON) {
  55501. var Internals;
  55502. (function (Internals) {
  55503. /**
  55504. * The bounding box information used during the conversion process.
  55505. */
  55506. var CMGBoundinBox = (function () {
  55507. function CMGBoundinBox() {
  55508. this.min = new BABYLON.Vector3(0, 0, 0);
  55509. this.max = new BABYLON.Vector3(0, 0, 0);
  55510. this.clear();
  55511. }
  55512. CMGBoundinBox.prototype.clear = function () {
  55513. this.min.x = CMGBoundinBox.MAX;
  55514. this.min.y = CMGBoundinBox.MAX;
  55515. this.min.z = CMGBoundinBox.MAX;
  55516. this.max.x = CMGBoundinBox.MIN;
  55517. this.max.y = CMGBoundinBox.MIN;
  55518. this.max.z = CMGBoundinBox.MIN;
  55519. };
  55520. CMGBoundinBox.prototype.augment = function (x, y, z) {
  55521. this.min.x = Math.min(this.min.x, x);
  55522. this.min.y = Math.min(this.min.y, y);
  55523. this.min.z = Math.min(this.min.z, z);
  55524. this.max.x = Math.max(this.max.x, x);
  55525. this.max.y = Math.max(this.max.y, y);
  55526. this.max.z = Math.max(this.max.z, z);
  55527. };
  55528. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  55529. this.min.x = Math.max(this.min.x, x);
  55530. this.min.y = Math.max(this.min.y, y);
  55531. this.min.z = Math.max(this.min.z, z);
  55532. };
  55533. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  55534. this.max.x = Math.min(this.max.x, x);
  55535. this.max.y = Math.min(this.max.y, y);
  55536. this.max.z = Math.min(this.max.z, z);
  55537. };
  55538. CMGBoundinBox.prototype.empty = function () {
  55539. if ((this.min.x > this.max.y) ||
  55540. (this.min.y > this.max.y) ||
  55541. (this.min.z > this.max.y)) {
  55542. return true;
  55543. }
  55544. else {
  55545. return false;
  55546. }
  55547. };
  55548. return CMGBoundinBox;
  55549. }());
  55550. CMGBoundinBox.MAX = Number.MAX_VALUE;
  55551. CMGBoundinBox.MIN = Number.MIN_VALUE;
  55552. /**
  55553. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  55554. * required by the glossinees of a material.
  55555. *
  55556. * This only supports the cosine drop power as well as Warp fixup generation method.
  55557. *
  55558. * This is using the process from CubeMapGen described here:
  55559. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  55560. */
  55561. var PMREMGenerator = (function () {
  55562. /**
  55563. * Constructor of the generator.
  55564. *
  55565. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  55566. * @param inputSize The size of the cubemap faces
  55567. * @param outputSize The size of the output cubemap faces
  55568. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  55569. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  55570. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  55571. * @param specularPower The max specular level of the desired cubemap
  55572. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  55573. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  55574. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  55575. */
  55576. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  55577. this.input = input;
  55578. this.inputSize = inputSize;
  55579. this.outputSize = outputSize;
  55580. this.maxNumMipLevels = maxNumMipLevels;
  55581. this.numChannels = numChannels;
  55582. this.isFloat = isFloat;
  55583. this.specularPower = specularPower;
  55584. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  55585. this.excludeBase = excludeBase;
  55586. this.fixup = fixup;
  55587. this._outputSurface = [];
  55588. this._numMipLevels = 0;
  55589. }
  55590. /**
  55591. * Launches the filter process and return the result.
  55592. *
  55593. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  55594. */
  55595. PMREMGenerator.prototype.filterCubeMap = function () {
  55596. // Init cubemap processor
  55597. this.init();
  55598. // Filters the cubemap
  55599. this.filterCubeMapMipChain();
  55600. // Returns the filtered mips.
  55601. return this._outputSurface;
  55602. };
  55603. PMREMGenerator.prototype.init = function () {
  55604. var i;
  55605. var j;
  55606. var mipLevelSize;
  55607. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  55608. if (this.maxNumMipLevels == 0) {
  55609. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  55610. }
  55611. //first miplevel size
  55612. mipLevelSize = this.outputSize;
  55613. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  55614. for (j = 0; j < this.maxNumMipLevels; j++) {
  55615. this._outputSurface.length++;
  55616. this._outputSurface[j] = [];
  55617. //Iterate over faces for output images
  55618. for (i = 0; i < 6; i++) {
  55619. this._outputSurface[j].length++;
  55620. // Initializes a new array for the output.
  55621. if (this.isFloat) {
  55622. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55623. }
  55624. else {
  55625. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  55626. }
  55627. }
  55628. //next mip level is half size
  55629. mipLevelSize >>= 1;
  55630. this._numMipLevels++;
  55631. //terminate if mip chain becomes too small
  55632. if (mipLevelSize == 0) {
  55633. this.maxNumMipLevels = j;
  55634. return;
  55635. }
  55636. }
  55637. };
  55638. //--------------------------------------------------------------------------------------
  55639. //Cube map filtering and mip chain generation.
  55640. // the cube map filtereing is specified using a number of parameters:
  55641. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  55642. // indicates the region of the hemisphere to filter over for each tap.
  55643. //
  55644. // Note that the top mip level is also a filtered version of the original input images
  55645. // as well in order to create mip chains for diffuse environment illumination.
  55646. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  55647. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  55648. //
  55649. // Then the mip angle used to genreate the next level of the mip chain from the first level
  55650. // is a_InitialMipAngle
  55651. //
  55652. // The angle for the subsequent levels of the mip chain are specified by their parents
  55653. // filtering angle and a per-level scale and bias
  55654. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  55655. //
  55656. //--------------------------------------------------------------------------------------
  55657. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  55658. // First, take count of the lighting model to modify SpecularPower
  55659. // 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;
  55660. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  55661. //Cone angle start (for generating subsequent mip levels)
  55662. var currentSpecularPower = this.specularPower;
  55663. //Build filter lookup tables based on the source miplevel size
  55664. this.precomputeFilterLookupTables(this.inputSize);
  55665. // Note that we need to filter the first level before generating mipmap
  55666. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  55667. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  55668. // TODO : Write a function to copy and scale the base mipmap in output
  55669. // I am just lazy here and just put a high specular power value, and do some if.
  55670. if (this.excludeBase && (levelIndex == 0)) {
  55671. // 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).
  55672. currentSpecularPower = 100000.0;
  55673. }
  55674. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  55675. var srcCubeImage = this.input;
  55676. var dstCubeImage = this._outputSurface[levelIndex];
  55677. var dstSize = this.outputSize >> levelIndex;
  55678. // Compute required angle.
  55679. var angle = this.getBaseFilterAngle(currentSpecularPower);
  55680. // filter cube surfaces
  55681. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  55682. // fix seams
  55683. if (this.fixup) {
  55684. this.fixupCubeEdges(dstCubeImage, dstSize);
  55685. }
  55686. // Decrease the specular power to generate the mipmap chain
  55687. // TODO : Use another method for Exclude (see first comment at start of the function
  55688. if (this.excludeBase && (levelIndex == 0)) {
  55689. currentSpecularPower = this.specularPower;
  55690. }
  55691. currentSpecularPower *= this.cosinePowerDropPerMip;
  55692. }
  55693. };
  55694. //--------------------------------------------------------------------------------------
  55695. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  55696. // It allow to optimize the texel to access base on the specular power.
  55697. //--------------------------------------------------------------------------------------
  55698. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  55699. // We want to find the alpha such that:
  55700. // cos(alpha)^cosinePower = epsilon
  55701. // That's: acos(epsilon^(1/cosinePower))
  55702. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  55703. var angle = 180.0;
  55704. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  55705. angle *= 180.0 / Math.PI; // Convert to degree
  55706. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  55707. return angle;
  55708. };
  55709. //--------------------------------------------------------------------------------------
  55710. //Builds the following lookup tables prior to filtering:
  55711. // -normalizer cube map
  55712. // -tap weight lookup table
  55713. //
  55714. //--------------------------------------------------------------------------------------
  55715. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  55716. var srcTexelAngle;
  55717. var iCubeFace;
  55718. //clear pre-existing normalizer cube map
  55719. this._normCubeMap = [];
  55720. //Normalized vectors per cubeface and per-texel solid angle
  55721. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  55722. };
  55723. //--------------------------------------------------------------------------------------
  55724. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  55725. //
  55726. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  55727. //
  55728. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  55729. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  55730. // below
  55731. //--------------------------------------------------------------------------------------
  55732. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  55733. var iCubeFace;
  55734. var u;
  55735. var v;
  55736. //iterate over cube faces
  55737. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55738. //First three channels for norm cube, and last channel for solid angle
  55739. this._normCubeMap.push(new Float32Array(size * size * 4));
  55740. //fast texture walk, build normalizer cube map
  55741. var facesData = this.input[iCubeFace];
  55742. for (v = 0; v < size; v++) {
  55743. for (u = 0; u < size; u++) {
  55744. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  55745. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  55746. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  55747. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  55748. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  55749. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  55750. }
  55751. }
  55752. }
  55753. };
  55754. //--------------------------------------------------------------------------------------
  55755. // Convert cubemap face texel coordinates and face idx to 3D vector
  55756. // note the U and V coords are integer coords and range from 0 to size-1
  55757. // this routine can be used to generate a normalizer cube map
  55758. //--------------------------------------------------------------------------------------
  55759. // SL BEGIN
  55760. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  55761. var nvcU;
  55762. var nvcV;
  55763. var tempVec;
  55764. // Change from original AMD code
  55765. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55766. // + 0.5f is for texel center addressing
  55767. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  55768. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  55769. // warp fixup
  55770. if (fixup && size > 1) {
  55771. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  55772. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  55773. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  55774. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  55775. }
  55776. // Get current vector
  55777. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  55778. // U contribution
  55779. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55780. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  55781. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  55782. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  55783. // V contribution and Sum
  55784. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55785. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  55786. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  55787. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  55788. //add face axis
  55789. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  55790. PMREMGenerator._vectorTemp.x += faceAxis[0];
  55791. PMREMGenerator._vectorTemp.y += faceAxis[1];
  55792. PMREMGenerator._vectorTemp.z += faceAxis[2];
  55793. //normalize vector
  55794. PMREMGenerator._vectorTemp.normalize();
  55795. return PMREMGenerator._vectorTemp;
  55796. };
  55797. //--------------------------------------------------------------------------------------
  55798. // Convert 3D vector to cubemap face texel coordinates and face idx
  55799. // note the U and V coords are integer coords and range from 0 to size-1
  55800. // this routine can be used to generate a normalizer cube map
  55801. //
  55802. // returns face IDX and texel coords
  55803. //--------------------------------------------------------------------------------------
  55804. // SL BEGIN
  55805. /*
  55806. Mapping Texture Coordinates to Cube Map Faces
  55807. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  55808. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  55809. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  55810. map arrangement in Pixar's RenderMan package.
  55811. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  55812. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  55813. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  55814. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  55815. the major axis direction). The target column in the table below explains how the major axis direction
  55816. maps to the 2D image of a particular cube map target.
  55817. major axis
  55818. direction target sc tc ma
  55819. ---------- --------------------------------- --- --- ---
  55820. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  55821. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  55822. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  55823. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  55824. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  55825. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  55826. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  55827. an updated (s,t) is calculated as follows
  55828. s = ( sc/|ma| + 1 ) / 2
  55829. t = ( tc/|ma| + 1 ) / 2
  55830. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  55831. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  55832. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  55833. */
  55834. // Note this method return U and V in range from 0 to size-1
  55835. // SL END
  55836. // Store the information in vector3 for convenience (faceindex, u, v)
  55837. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  55838. var maxCoord;
  55839. var faceIdx;
  55840. //absolute value 3
  55841. var absX = Math.abs(x);
  55842. var absY = Math.abs(y);
  55843. var absZ = Math.abs(z);
  55844. if (absX >= absY && absX >= absZ) {
  55845. maxCoord = absX;
  55846. if (x >= 0) {
  55847. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  55848. }
  55849. else {
  55850. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  55851. }
  55852. }
  55853. else if (absY >= absX && absY >= absZ) {
  55854. maxCoord = absY;
  55855. if (y >= 0) {
  55856. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  55857. }
  55858. else {
  55859. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  55860. }
  55861. }
  55862. else {
  55863. maxCoord = absZ;
  55864. if (z >= 0) {
  55865. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  55866. }
  55867. else {
  55868. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  55869. }
  55870. }
  55871. //divide through by max coord so face vector lies on cube face
  55872. var scale = 1 / maxCoord;
  55873. x *= scale;
  55874. y *= scale;
  55875. z *= scale;
  55876. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  55877. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  55878. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  55879. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  55880. // Modify original AMD code to return value from 0 to Size - 1
  55881. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  55882. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  55883. PMREMGenerator._vectorTemp.x = faceIdx;
  55884. PMREMGenerator._vectorTemp.y = u;
  55885. PMREMGenerator._vectorTemp.z = v;
  55886. return PMREMGenerator._vectorTemp;
  55887. };
  55888. //--------------------------------------------------------------------------------------
  55889. //Original code from Ignacio CastaÒo
  55890. // This formula is from Manne ÷hrstrˆm's thesis.
  55891. // Take two coordiantes in the range [-1, 1] that define a portion of a
  55892. // cube face and return the area of the projection of that portion on the
  55893. // surface of the sphere.
  55894. //--------------------------------------------------------------------------------------
  55895. PMREMGenerator.prototype.areaElement = function (x, y) {
  55896. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  55897. };
  55898. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  55899. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  55900. // (+ 0.5f is for texel center addressing)
  55901. u = (2.0 * (u + 0.5) / size) - 1.0;
  55902. v = (2.0 * (v + 0.5) / size) - 1.0;
  55903. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  55904. var invResolution = 1.0 / size;
  55905. // U and V are the -1..1 texture coordinate on the current face.
  55906. // Get projected area for this texel
  55907. var x0 = u - invResolution;
  55908. var y0 = v - invResolution;
  55909. var x1 = u + invResolution;
  55910. var y1 = v + invResolution;
  55911. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  55912. return solidAngle;
  55913. };
  55914. //--------------------------------------------------------------------------------------
  55915. //The key to the speed of these filtering routines is to quickly define a per-face
  55916. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  55917. // Later these pixels are selectively processed based on their dot products to see if
  55918. // they reside within the filtering cone.
  55919. //
  55920. //This is done by computing the smallest per-texel angle to get a conservative estimate
  55921. // of the number of texels needed to be covered in width and height order to filter the
  55922. // region. the bounding box for the center taps face is defined first, and if the
  55923. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  55924. // defined next
  55925. //--------------------------------------------------------------------------------------
  55926. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  55927. // note that pixels within these regions may be rejected
  55928. // based on the anlge
  55929. var iCubeFace;
  55930. var u;
  55931. var v;
  55932. // bounding box per face to specify region to process
  55933. var filterExtents = [];
  55934. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55935. filterExtents.push(new CMGBoundinBox());
  55936. }
  55937. // min angle a src texel can cover (in degrees)
  55938. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  55939. // angle about center tap to define filter cone
  55940. // filter angle is 1/2 the cone angle
  55941. var filterAngle = filterConeAngle / 2.0;
  55942. //ensure filter angle is larger than a texel
  55943. if (filterAngle < srcTexelAngle) {
  55944. filterAngle = srcTexelAngle;
  55945. }
  55946. //ensure filter cone is always smaller than the hemisphere
  55947. if (filterAngle > 90.0) {
  55948. filterAngle = 90.0;
  55949. }
  55950. // the maximum number of texels in 1D the filter cone angle will cover
  55951. // used to determine bounding box size for filter extents
  55952. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  55953. // ensure conservative region always covers at least one texel
  55954. if (filterSize < 1) {
  55955. filterSize = 1;
  55956. }
  55957. // dotProdThresh threshold based on cone angle to determine whether or not taps
  55958. // reside within the cone angle
  55959. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  55960. // process required faces
  55961. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  55962. //iterate over dst cube map face texel
  55963. for (v = 0; v < dstSize; v++) {
  55964. for (u = 0; u < dstSize; u++) {
  55965. //get center tap direction
  55966. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  55967. //clear old per-face filter extents
  55968. this.clearFilterExtents(filterExtents);
  55969. //define per-face filter extents
  55970. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  55971. //perform filtering of src faces using filter extents
  55972. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  55973. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  55974. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  55975. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  55976. }
  55977. }
  55978. }
  55979. };
  55980. //--------------------------------------------------------------------------------------
  55981. //Clear filter extents for the 6 cube map faces
  55982. //--------------------------------------------------------------------------------------
  55983. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  55984. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  55985. filterExtents[iCubeFaces].clear();
  55986. }
  55987. };
  55988. //--------------------------------------------------------------------------------------
  55989. //Define per-face bounding box filter extents
  55990. //
  55991. // These define conservative texel regions in each of the faces the filter can possibly
  55992. // process. When the pixels in the regions are actually processed, the dot product
  55993. // between the tap vector and the center tap vector is used to determine the weight of
  55994. // the tap and whether or not the tap is within the cone.
  55995. //
  55996. //--------------------------------------------------------------------------------------
  55997. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  55998. //neighboring face and bleed over amount, and width of BBOX for
  55999. // left, right, top, and bottom edges of this face
  56000. var bleedOverAmount = [0, 0, 0, 0];
  56001. var bleedOverBBoxMin = [0, 0, 0, 0];
  56002. var bleedOverBBoxMax = [0, 0, 0, 0];
  56003. var neighborFace;
  56004. var neighborEdge;
  56005. var oppositeFaceIdx;
  56006. //get face idx, and u, v info from center tap dir
  56007. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  56008. var faceIdx = result.x;
  56009. var u = result.y;
  56010. var v = result.z;
  56011. //define bbox size within face
  56012. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  56013. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  56014. filterExtents[faceIdx].clampMin(0, 0, 0);
  56015. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  56016. //u and v extent in face corresponding to center tap
  56017. var minU = filterExtents[faceIdx].min.x;
  56018. var minV = filterExtents[faceIdx].min.y;
  56019. var maxU = filterExtents[faceIdx].max.x;
  56020. var maxV = filterExtents[faceIdx].max.y;
  56021. //bleed over amounts for face across u=0 edge (left)
  56022. bleedOverAmount[0] = (bboxSize - u);
  56023. bleedOverBBoxMin[0] = minV;
  56024. bleedOverBBoxMax[0] = maxV;
  56025. //bleed over amounts for face across u=1 edge (right)
  56026. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  56027. bleedOverBBoxMin[1] = minV;
  56028. bleedOverBBoxMax[1] = maxV;
  56029. //bleed over to face across v=0 edge (up)
  56030. bleedOverAmount[2] = (bboxSize - v);
  56031. bleedOverBBoxMin[2] = minU;
  56032. bleedOverBBoxMax[2] = maxU;
  56033. //bleed over to face across v=1 edge (down)
  56034. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  56035. bleedOverBBoxMin[3] = minU;
  56036. bleedOverBBoxMax[3] = maxU;
  56037. //compute bleed over regions in neighboring faces
  56038. for (var i = 0; i < 4; i++) {
  56039. if (bleedOverAmount[i] > 0) {
  56040. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  56041. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  56042. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  56043. // be flipped: the cases are
  56044. // if a left edge mates with a left or bottom edge on the neighbor
  56045. // if a top edge mates with a top or right edge on the neighbor
  56046. // if a right edge mates with a right or top edge on the neighbor
  56047. // if a bottom edge mates with a bottom or left edge on the neighbor
  56048. //Seeing as the edges are enumerated as follows
  56049. // left =0
  56050. // right =1
  56051. // top =2
  56052. // bottom =3
  56053. //
  56054. // so if the edge enums are the same, or the sum of the enums == 3,
  56055. // the bbox needs to be flipped
  56056. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  56057. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  56058. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  56059. }
  56060. //The way the bounding box is extended onto the neighboring face
  56061. // depends on which edge of neighboring face abuts with this one
  56062. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  56063. case PMREMGenerator.CP_EDGE_LEFT:
  56064. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  56065. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  56066. break;
  56067. case PMREMGenerator.CP_EDGE_RIGHT:
  56068. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  56069. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  56070. break;
  56071. case PMREMGenerator.CP_EDGE_TOP:
  56072. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  56073. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  56074. break;
  56075. case PMREMGenerator.CP_EDGE_BOTTOM:
  56076. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  56077. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  56078. break;
  56079. }
  56080. //clamp filter extents in non-center tap faces to remain within surface
  56081. filterExtents[neighborFace].clampMin(0, 0, 0);
  56082. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  56083. }
  56084. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  56085. // from the center tap face, then process the opposite face entirely for now.
  56086. //Note that the cases in which this happens, what usually happens is that
  56087. // more than one edge bleeds onto the opposite face, and the bounding box
  56088. // encompasses the entire cube map face.
  56089. if (bleedOverAmount[i] > srcSize) {
  56090. //determine opposite face
  56091. switch (faceIdx) {
  56092. case PMREMGenerator.CP_FACE_X_POS:
  56093. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  56094. break;
  56095. case PMREMGenerator.CP_FACE_X_NEG:
  56096. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  56097. break;
  56098. case PMREMGenerator.CP_FACE_Y_POS:
  56099. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  56100. break;
  56101. case PMREMGenerator.CP_FACE_Y_NEG:
  56102. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  56103. break;
  56104. case PMREMGenerator.CP_FACE_Z_POS:
  56105. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  56106. break;
  56107. case PMREMGenerator.CP_FACE_Z_NEG:
  56108. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  56109. break;
  56110. default:
  56111. break;
  56112. }
  56113. //just encompass entire face for now
  56114. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  56115. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  56116. }
  56117. }
  56118. };
  56119. //--------------------------------------------------------------------------------------
  56120. //ProcessFilterExtents
  56121. // Process bounding box in each cube face
  56122. //
  56123. //--------------------------------------------------------------------------------------
  56124. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  56125. //accumulators are 64-bit floats in order to have the precision needed
  56126. // over a summation of a large number of pixels
  56127. var dstAccum = [0, 0, 0, 0];
  56128. var weightAccum = 0;
  56129. var k = 0;
  56130. var nSrcChannels = this.numChannels;
  56131. // norm cube map and srcCubeMap have same face width
  56132. var faceWidth = srcSize;
  56133. //amount to add to pointer to move to next scanline in images
  56134. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  56135. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  56136. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  56137. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  56138. // iterate over cubefaces
  56139. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  56140. //if bbox is non empty
  56141. if (!filterExtents[iFaceIdx].empty()) {
  56142. var uStart = filterExtents[iFaceIdx].min.x;
  56143. var vStart = filterExtents[iFaceIdx].min.y;
  56144. var uEnd = filterExtents[iFaceIdx].max.x;
  56145. var vEnd = filterExtents[iFaceIdx].max.y;
  56146. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  56147. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  56148. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  56149. for (var v = vStart; v <= vEnd; v++) {
  56150. var normCubeRowWalk = 0;
  56151. var srcCubeRowWalk = 0;
  56152. for (var u = uStart; u <= uEnd; u++) {
  56153. //pointer to direction in cube map associated with texel
  56154. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  56155. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  56156. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  56157. //check dot product to see if texel is within cone
  56158. var tapDotProd = texelVectX * centerTapDir.x +
  56159. texelVectY * centerTapDir.y +
  56160. texelVectZ * centerTapDir.z;
  56161. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  56162. //solid angle stored in 4th channel of normalizer/solid angle cube map
  56163. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  56164. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  56165. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  56166. // so just adding one to specularpower do the trick.
  56167. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  56168. //iterate over channels
  56169. for (k = 0; k < nSrcChannels; k++) {
  56170. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  56171. srcCubeRowWalk++;
  56172. }
  56173. weightAccum += weight; //accumulate weight
  56174. }
  56175. else {
  56176. //step across source pixel
  56177. srcCubeRowWalk += nSrcChannels;
  56178. }
  56179. normCubeRowWalk += 4; // 4 channels per norm cube map.
  56180. }
  56181. startIndexNormCubeMap += normCubePitch;
  56182. startIndexSrcCubeMap += srcCubePitch;
  56183. }
  56184. }
  56185. }
  56186. //divide through by weights if weight is non zero
  56187. if (weightAccum != 0.0) {
  56188. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  56189. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  56190. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  56191. if (this.numChannels > 3) {
  56192. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  56193. }
  56194. }
  56195. else {
  56196. // otherwise sample nearest
  56197. // get face idx and u, v texel coordinate in face
  56198. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  56199. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  56200. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  56201. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  56202. if (this.numChannels > 3) {
  56203. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  56204. }
  56205. }
  56206. return PMREMGenerator._vectorTemp;
  56207. };
  56208. //--------------------------------------------------------------------------------------
  56209. // Fixup cube edges
  56210. //
  56211. // average texels on cube map faces across the edges
  56212. // WARP/BENT Method Only.
  56213. //--------------------------------------------------------------------------------------
  56214. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  56215. var k;
  56216. var j;
  56217. var i;
  56218. var iFace;
  56219. var iCorner = 0;
  56220. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  56221. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  56222. // note that if functionality to filter across the three texels for each corner, then
  56223. //indexed by corner and face idx. the array contains the face the start points belongs to.
  56224. var cornerPtr = [
  56225. [[], [], []],
  56226. [[], [], []],
  56227. [[], [], []],
  56228. [[], [], []],
  56229. [[], [], []],
  56230. [[], [], []],
  56231. [[], [], []],
  56232. [[], [], []]
  56233. ];
  56234. //if there is no fixup, or fixup width = 0, do nothing
  56235. if (cubeMapSize < 1) {
  56236. return;
  56237. }
  56238. //special case 1x1 cubemap, average face colors
  56239. if (cubeMapSize == 1) {
  56240. //iterate over channels
  56241. for (k = 0; k < this.numChannels; k++) {
  56242. var accum = 0.0;
  56243. //iterate over faces to accumulate face colors
  56244. for (iFace = 0; iFace < 6; iFace++) {
  56245. accum += cubeMap[iFace][k];
  56246. }
  56247. //compute average over 6 face colors
  56248. accum /= 6.0;
  56249. //iterate over faces to distribute face colors
  56250. for (iFace = 0; iFace < 6; iFace++) {
  56251. cubeMap[iFace][k] = accum;
  56252. }
  56253. }
  56254. return;
  56255. }
  56256. //iterate over faces to collect list of corner texel pointers
  56257. for (iFace = 0; iFace < 6; iFace++) {
  56258. //the 4 corner pointers for this face
  56259. faceCornerStartIndicies[0] = [iFace, 0];
  56260. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  56261. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  56262. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  56263. //iterate over face corners to collect cube corner pointers
  56264. for (iCorner = 0; iCorner < 4; iCorner++) {
  56265. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  56266. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  56267. cornerNumPtrs[corner]++;
  56268. }
  56269. }
  56270. //iterate over corners to average across corner tap values
  56271. for (iCorner = 0; iCorner < 8; iCorner++) {
  56272. for (k = 0; k < this.numChannels; k++) {
  56273. var cornerTapAccum = 0.0;
  56274. //iterate over corner texels and average results
  56275. for (i = 0; i < 3; i++) {
  56276. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  56277. }
  56278. //divide by 3 to compute average of corner tap values
  56279. cornerTapAccum *= (1.0 / 3.0);
  56280. //iterate over corner texels and average results
  56281. for (i = 0; i < 3; i++) {
  56282. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  56283. }
  56284. }
  56285. }
  56286. //iterate over the twelve edges of the cube to average across edges
  56287. for (i = 0; i < 12; i++) {
  56288. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  56289. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  56290. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  56291. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  56292. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  56293. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  56294. var edgeWalk = 0;
  56295. var neighborEdgeWalk = 0;
  56296. //Determine walking pointers based on edge type
  56297. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  56298. switch (edge) {
  56299. case PMREMGenerator.CP_EDGE_LEFT:
  56300. // no change to faceEdgeStartPtr
  56301. edgeWalk = this.numChannels * cubeMapSize;
  56302. break;
  56303. case PMREMGenerator.CP_EDGE_RIGHT:
  56304. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56305. edgeWalk = this.numChannels * cubeMapSize;
  56306. break;
  56307. case PMREMGenerator.CP_EDGE_TOP:
  56308. // no change to faceEdgeStartPtr
  56309. edgeWalk = this.numChannels;
  56310. break;
  56311. case PMREMGenerator.CP_EDGE_BOTTOM:
  56312. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56313. edgeWalk = this.numChannels;
  56314. break;
  56315. }
  56316. //For certain types of edge abutments, the neighbor edge walk needs to
  56317. // be flipped: the cases are
  56318. // if a left edge mates with a left or bottom edge on the neighbor
  56319. // if a top edge mates with a top or right edge on the neighbor
  56320. // if a right edge mates with a right or top edge on the neighbor
  56321. // if a bottom edge mates with a bottom or left edge on the neighbor
  56322. //Seeing as the edges are enumerated as follows
  56323. // left =0
  56324. // right =1
  56325. // top =2
  56326. // bottom =3
  56327. //
  56328. //If the edge enums are the same, or the sum of the enums == 3,
  56329. // the neighbor edge walk needs to be flipped
  56330. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  56331. switch (neighborEdge) {
  56332. case PMREMGenerator.CP_EDGE_LEFT:
  56333. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  56334. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56335. break;
  56336. case PMREMGenerator.CP_EDGE_RIGHT:
  56337. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56338. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  56339. break;
  56340. case PMREMGenerator.CP_EDGE_TOP:
  56341. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56342. neighborEdgeWalk = -this.numChannels;
  56343. break;
  56344. case PMREMGenerator.CP_EDGE_BOTTOM:
  56345. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  56346. neighborEdgeWalk = -this.numChannels;
  56347. break;
  56348. }
  56349. }
  56350. else {
  56351. //swapped direction neighbor edge walk
  56352. switch (neighborEdge) {
  56353. case PMREMGenerator.CP_EDGE_LEFT:
  56354. //no change to neighborEdgeStartPtr for this case since it points
  56355. // to the upper left corner already
  56356. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56357. break;
  56358. case PMREMGenerator.CP_EDGE_RIGHT:
  56359. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  56360. neighborEdgeWalk = this.numChannels * cubeMapSize;
  56361. break;
  56362. case PMREMGenerator.CP_EDGE_TOP:
  56363. //no change to neighborEdgeStartPtr for this case since it points
  56364. // to the upper left corner already
  56365. neighborEdgeWalk = this.numChannels;
  56366. break;
  56367. case PMREMGenerator.CP_EDGE_BOTTOM:
  56368. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  56369. neighborEdgeWalk = this.numChannels;
  56370. break;
  56371. }
  56372. }
  56373. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  56374. //nearby neighborhood
  56375. //step ahead one texel on edge
  56376. edgeStartIndex += edgeWalk;
  56377. neighborEdgeStartIndex += neighborEdgeWalk;
  56378. // note that this loop does not process the corner texels, since they have already been
  56379. // averaged across faces across earlier
  56380. for (j = 1; j < (cubeMapSize - 1); j++) {
  56381. //for each set of taps along edge, average them
  56382. // and rewrite the results into the edges
  56383. for (k = 0; k < this.numChannels; k++) {
  56384. var edgeTap = cubeMap[face][edgeStartIndex + k];
  56385. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  56386. //compute average of tap intensity values
  56387. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  56388. //propagate average of taps to edge taps
  56389. cubeMap[face][edgeStartIndex + k] = avgTap;
  56390. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  56391. }
  56392. edgeStartIndex += edgeWalk;
  56393. neighborEdgeStartIndex += neighborEdgeWalk;
  56394. }
  56395. }
  56396. };
  56397. return PMREMGenerator;
  56398. }());
  56399. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  56400. PMREMGenerator.CP_UDIR = 0;
  56401. PMREMGenerator.CP_VDIR = 1;
  56402. PMREMGenerator.CP_FACEAXIS = 2;
  56403. //used to index cube faces
  56404. PMREMGenerator.CP_FACE_X_POS = 0;
  56405. PMREMGenerator.CP_FACE_X_NEG = 1;
  56406. PMREMGenerator.CP_FACE_Y_POS = 2;
  56407. PMREMGenerator.CP_FACE_Y_NEG = 3;
  56408. PMREMGenerator.CP_FACE_Z_POS = 4;
  56409. PMREMGenerator.CP_FACE_Z_NEG = 5;
  56410. //used to index image edges
  56411. // NOTE.. the actual number corresponding to the edge is important
  56412. // do not change these, or the code will break
  56413. //
  56414. // CP_EDGE_LEFT is u = 0
  56415. // CP_EDGE_RIGHT is u = width-1
  56416. // CP_EDGE_TOP is v = 0
  56417. // CP_EDGE_BOTTOM is v = height-1
  56418. PMREMGenerator.CP_EDGE_LEFT = 0;
  56419. PMREMGenerator.CP_EDGE_RIGHT = 1;
  56420. PMREMGenerator.CP_EDGE_TOP = 2;
  56421. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  56422. //corners of CUBE map (P or N specifys if it corresponds to the
  56423. // positive or negative direction each of X, Y, and Z
  56424. PMREMGenerator.CP_CORNER_NNN = 0;
  56425. PMREMGenerator.CP_CORNER_NNP = 1;
  56426. PMREMGenerator.CP_CORNER_NPN = 2;
  56427. PMREMGenerator.CP_CORNER_NPP = 3;
  56428. PMREMGenerator.CP_CORNER_PNN = 4;
  56429. PMREMGenerator.CP_CORNER_PNP = 5;
  56430. PMREMGenerator.CP_CORNER_PPN = 6;
  56431. PMREMGenerator.CP_CORNER_PPP = 7;
  56432. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  56433. //3x2 matrices that map cube map indexing vectors in 3d
  56434. // (after face selection and divide through by the
  56435. // _ABSOLUTE VALUE_ of the max coord)
  56436. // into NVC space
  56437. //Note this currently assumes the D3D cube face ordering and orientation
  56438. PMREMGenerator._sgFace2DMapping = [
  56439. //XPOS face
  56440. [[0, 0, -1],
  56441. [0, -1, 0],
  56442. [1, 0, 0]],
  56443. //XNEG face
  56444. [[0, 0, 1],
  56445. [0, -1, 0],
  56446. [-1, 0, 0]],
  56447. //YPOS face
  56448. [[1, 0, 0],
  56449. [0, 0, 1],
  56450. [0, 1, 0]],
  56451. //YNEG face
  56452. [[1, 0, 0],
  56453. [0, 0, -1],
  56454. [0, -1, 0]],
  56455. //ZPOS face
  56456. [[1, 0, 0],
  56457. [0, -1, 0],
  56458. [0, 0, 1]],
  56459. //ZNEG face
  56460. [[-1, 0, 0],
  56461. [0, -1, 0],
  56462. [0, 0, -1]],
  56463. ];
  56464. //------------------------------------------------------------------------------
  56465. // D3D cube map face specification
  56466. // mapping from 3D x,y,z cube map lookup coordinates
  56467. // to 2D within face u,v coordinates
  56468. //
  56469. // --------------------> U direction
  56470. // | (within-face texture space)
  56471. // | _____
  56472. // | | |
  56473. // | | +Y |
  56474. // | _____|_____|_____ _____
  56475. // | | | | | |
  56476. // | | -X | +Z | +X | -Z |
  56477. // | |_____|_____|_____|_____|
  56478. // | | |
  56479. // | | -Y |
  56480. // | |_____|
  56481. // |
  56482. // v V direction
  56483. // (within-face texture space)
  56484. //------------------------------------------------------------------------------
  56485. //Information about neighbors and how texture coorrdinates change across faces
  56486. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  56487. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  56488. //Note this currently assumes the D3D cube face ordering and orientation
  56489. PMREMGenerator._sgCubeNgh = [
  56490. //XPOS face
  56491. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56492. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56493. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56494. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  56495. //XNEG face
  56496. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56497. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  56498. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  56499. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  56500. //YPOS face
  56501. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56502. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56503. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56504. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  56505. //YNEG face
  56506. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56507. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56508. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56509. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  56510. //ZPOS face
  56511. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56512. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56513. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56514. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  56515. //ZNEG face
  56516. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56517. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56518. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  56519. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  56520. ];
  56521. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  56522. // this table is used to average over the edges.
  56523. PMREMGenerator._sgCubeEdgeList = [
  56524. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  56525. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  56526. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  56527. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56528. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  56529. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  56530. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  56531. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  56532. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  56533. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  56534. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  56535. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  56536. ];
  56537. //Information about which of the 8 cube corners are correspond to the
  56538. // the 4 corners in each cube face
  56539. // the order is upper left, upper right, lower left, lower right
  56540. PMREMGenerator._sgCubeCornerList = [
  56541. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  56542. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  56543. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  56544. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  56545. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  56546. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  56547. ];
  56548. Internals.PMREMGenerator = PMREMGenerator;
  56549. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56550. })(BABYLON || (BABYLON = {}));
  56551. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  56552. var BABYLON;
  56553. (function (BABYLON) {
  56554. /**
  56555. * This represents a texture coming from an HDR input.
  56556. *
  56557. * The only supported format is currently panorama picture stored in RGBE format.
  56558. * Example of such files can be found on HDRLib: http://hdrlib.com/
  56559. */
  56560. var HDRCubeTexture = (function (_super) {
  56561. __extends(HDRCubeTexture, _super);
  56562. /**
  56563. * Instantiates an HDRTexture from the following parameters.
  56564. *
  56565. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  56566. * @param scene The scene the texture will be used in
  56567. * @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.
  56568. * @param noMipmap Forces to not generate the mipmap if true
  56569. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  56570. * @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)
  56571. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  56572. */
  56573. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  56574. if (noMipmap === void 0) { noMipmap = false; }
  56575. if (generateHarmonics === void 0) { generateHarmonics = true; }
  56576. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  56577. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  56578. if (onLoad === void 0) { onLoad = null; }
  56579. if (onError === void 0) { onError = null; }
  56580. var _this = _super.call(this, scene) || this;
  56581. _this._useInGammaSpace = false;
  56582. _this._generateHarmonics = true;
  56583. _this._isBABYLONPreprocessed = false;
  56584. _this._onLoad = null;
  56585. _this._onError = null;
  56586. /**
  56587. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  56588. */
  56589. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56590. /**
  56591. * The spherical polynomial data extracted from the texture.
  56592. */
  56593. _this.sphericalPolynomial = null;
  56594. /**
  56595. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  56596. * This is usefull at run time to apply the good shader.
  56597. */
  56598. _this.isPMREM = false;
  56599. if (!url) {
  56600. return _this;
  56601. }
  56602. _this.name = url;
  56603. _this.url = url;
  56604. _this.hasAlpha = false;
  56605. _this.isCube = true;
  56606. _this._textureMatrix = BABYLON.Matrix.Identity();
  56607. _this._onLoad = onLoad;
  56608. _this._onError = onError;
  56609. if (size) {
  56610. _this._isBABYLONPreprocessed = false;
  56611. _this._noMipmap = noMipmap;
  56612. _this._size = size;
  56613. _this._useInGammaSpace = useInGammaSpace;
  56614. _this._usePMREMGenerator = usePMREMGenerator &&
  56615. scene.getEngine().getCaps().textureLOD &&
  56616. _this.getScene().getEngine().getCaps().textureFloat &&
  56617. !_this._useInGammaSpace;
  56618. }
  56619. else {
  56620. _this._isBABYLONPreprocessed = true;
  56621. _this._noMipmap = false;
  56622. _this._useInGammaSpace = false;
  56623. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  56624. _this.getScene().getEngine().getCaps().textureFloat &&
  56625. !_this._useInGammaSpace;
  56626. }
  56627. _this.isPMREM = _this._usePMREMGenerator;
  56628. _this._texture = _this._getFromCache(url, _this._noMipmap);
  56629. if (!_this._texture) {
  56630. if (!scene.useDelayedTextureLoading) {
  56631. _this.loadTexture();
  56632. }
  56633. else {
  56634. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56635. }
  56636. }
  56637. return _this;
  56638. }
  56639. /**
  56640. * Occurs when the file is a preprocessed .babylon.hdr file.
  56641. */
  56642. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  56643. var _this = this;
  56644. var mipLevels = 0;
  56645. var floatArrayView = null;
  56646. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  56647. var mips = [];
  56648. var startIndex = 30;
  56649. for (var level = 0; level < mipLevels; level++) {
  56650. mips.push([]);
  56651. // Fill each pixel of the mip level.
  56652. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  56653. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56654. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  56655. mips[level].push(faceData);
  56656. startIndex += faceSize;
  56657. }
  56658. }
  56659. return mips;
  56660. } : null;
  56661. var callback = function (buffer) {
  56662. // Create Native Array Views
  56663. var intArrayView = new Int32Array(buffer);
  56664. floatArrayView = new Float32Array(buffer);
  56665. // Fill header.
  56666. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  56667. _this._size = intArrayView[1]; // CubeMap max mip face size.
  56668. // Update Texture Information.
  56669. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  56670. // Fill polynomial information.
  56671. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  56672. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  56673. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  56674. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  56675. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  56676. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  56677. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  56678. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  56679. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  56680. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  56681. // Fill pixel data.
  56682. mipLevels = intArrayView[29]; // Number of mip levels.
  56683. var startIndex = 30;
  56684. var data = [];
  56685. var faceSize = Math.pow(_this._size, 2) * 3;
  56686. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56687. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  56688. startIndex += faceSize;
  56689. }
  56690. var results = [];
  56691. var byteArray = null;
  56692. // Push each faces.
  56693. for (var k = 0; k < 6; k++) {
  56694. var dataFace = null;
  56695. // If special cases.
  56696. if (!mipmapGenerator) {
  56697. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  56698. dataFace = data[j];
  56699. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56700. // 3 channels of 1 bytes per pixel in bytes.
  56701. var byteBuffer = new ArrayBuffer(faceSize);
  56702. byteArray = new Uint8Array(byteBuffer);
  56703. }
  56704. for (var i = 0; i < _this._size * _this._size; i++) {
  56705. // Put in gamma space if requested.
  56706. if (_this._useInGammaSpace) {
  56707. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56708. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56709. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56710. }
  56711. // Convert to int texture for fallback.
  56712. if (byteArray) {
  56713. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56714. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56715. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56716. // May use luminance instead if the result is not accurate.
  56717. var max = Math.max(Math.max(r, g), b);
  56718. if (max > 255) {
  56719. var scale = 255 / max;
  56720. r *= scale;
  56721. g *= scale;
  56722. b *= scale;
  56723. }
  56724. byteArray[(i * 3) + 0] = r;
  56725. byteArray[(i * 3) + 1] = g;
  56726. byteArray[(i * 3) + 2] = b;
  56727. }
  56728. }
  56729. }
  56730. else {
  56731. dataFace = data[k];
  56732. }
  56733. // Fill the array accordingly.
  56734. if (byteArray) {
  56735. results.push(byteArray);
  56736. }
  56737. else {
  56738. results.push(dataFace);
  56739. }
  56740. }
  56741. return results;
  56742. };
  56743. 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);
  56744. };
  56745. /**
  56746. * Occurs when the file is raw .hdr file.
  56747. */
  56748. HDRCubeTexture.prototype.loadHDRTexture = function () {
  56749. var _this = this;
  56750. var callback = function (buffer) {
  56751. // Extract the raw linear data.
  56752. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  56753. // Generate harmonics if needed.
  56754. if (_this._generateHarmonics) {
  56755. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  56756. }
  56757. var results = [];
  56758. var byteArray = null;
  56759. // Push each faces.
  56760. for (var j = 0; j < 6; j++) {
  56761. // Create uintarray fallback.
  56762. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  56763. // 3 channels of 1 bytes per pixel in bytes.
  56764. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  56765. byteArray = new Uint8Array(byteBuffer);
  56766. }
  56767. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  56768. // If special cases.
  56769. if (_this._useInGammaSpace || byteArray) {
  56770. for (var i = 0; i < _this._size * _this._size; i++) {
  56771. // Put in gamma space if requested.
  56772. if (_this._useInGammaSpace) {
  56773. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  56774. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  56775. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  56776. }
  56777. // Convert to int texture for fallback.
  56778. if (byteArray) {
  56779. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  56780. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  56781. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  56782. // May use luminance instead if the result is not accurate.
  56783. var max = Math.max(Math.max(r, g), b);
  56784. if (max > 255) {
  56785. var scale = 255 / max;
  56786. r *= scale;
  56787. g *= scale;
  56788. b *= scale;
  56789. }
  56790. byteArray[(i * 3) + 0] = r;
  56791. byteArray[(i * 3) + 1] = g;
  56792. byteArray[(i * 3) + 2] = b;
  56793. }
  56794. }
  56795. }
  56796. if (byteArray) {
  56797. results.push(byteArray);
  56798. }
  56799. else {
  56800. results.push(dataFace);
  56801. }
  56802. }
  56803. return results;
  56804. };
  56805. var mipmapGenerator = null;
  56806. if (!this._noMipmap &&
  56807. this._usePMREMGenerator) {
  56808. mipmapGenerator = function (data) {
  56809. // Custom setup of the generator matching with the PBR shader values.
  56810. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  56811. return generator.filterCubeMap();
  56812. };
  56813. }
  56814. 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);
  56815. };
  56816. /**
  56817. * Starts the loading process of the texture.
  56818. */
  56819. HDRCubeTexture.prototype.loadTexture = function () {
  56820. if (this._isBABYLONPreprocessed) {
  56821. this.loadBabylonTexture();
  56822. }
  56823. else {
  56824. this.loadHDRTexture();
  56825. }
  56826. };
  56827. HDRCubeTexture.prototype.clone = function () {
  56828. var size = this._isBABYLONPreprocessed ? null : this._size;
  56829. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  56830. // Base texture
  56831. newTexture.level = this.level;
  56832. newTexture.wrapU = this.wrapU;
  56833. newTexture.wrapV = this.wrapV;
  56834. newTexture.coordinatesIndex = this.coordinatesIndex;
  56835. newTexture.coordinatesMode = this.coordinatesMode;
  56836. return newTexture;
  56837. };
  56838. // Methods
  56839. HDRCubeTexture.prototype.delayLoad = function () {
  56840. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56841. return;
  56842. }
  56843. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56844. this._texture = this._getFromCache(this.url, this._noMipmap);
  56845. if (!this._texture) {
  56846. this.loadTexture();
  56847. }
  56848. };
  56849. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  56850. return this._textureMatrix;
  56851. };
  56852. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56853. var texture = null;
  56854. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56855. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  56856. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  56857. texture.name = parsedTexture.name;
  56858. texture.hasAlpha = parsedTexture.hasAlpha;
  56859. texture.level = parsedTexture.level;
  56860. texture.coordinatesMode = parsedTexture.coordinatesMode;
  56861. }
  56862. return texture;
  56863. };
  56864. HDRCubeTexture.prototype.serialize = function () {
  56865. if (!this.name) {
  56866. return null;
  56867. }
  56868. var serializationObject = {};
  56869. serializationObject.name = this.name;
  56870. serializationObject.hasAlpha = this.hasAlpha;
  56871. serializationObject.isCube = true;
  56872. serializationObject.level = this.level;
  56873. serializationObject.size = this._size;
  56874. serializationObject.coordinatesMode = this.coordinatesMode;
  56875. serializationObject.useInGammaSpace = this._useInGammaSpace;
  56876. serializationObject.generateHarmonics = this._generateHarmonics;
  56877. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  56878. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  56879. serializationObject.customType = "BABYLON.HDRCubeTexture";
  56880. serializationObject.noMipmap = this._noMipmap;
  56881. return serializationObject;
  56882. };
  56883. /**
  56884. * Saves as a file the data contained in the texture in a binary format.
  56885. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56886. * as the spherical used in the lighting.
  56887. * @param url The HDR file url.
  56888. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56889. * @param onError Method called if any error happens during download.
  56890. * @return The packed binary data.
  56891. */
  56892. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  56893. if (onError === void 0) { onError = null; }
  56894. var callback = function (buffer) {
  56895. var data = new Blob([buffer], { type: 'application/octet-stream' });
  56896. // Returns a URL you can use as a href.
  56897. var objUrl = window.URL.createObjectURL(data);
  56898. // Simulates a link to it and click to dowload.
  56899. var a = document.createElement("a");
  56900. document.body.appendChild(a);
  56901. a.style.display = "none";
  56902. a.href = objUrl;
  56903. a.download = "envmap.babylon.hdr";
  56904. a.click();
  56905. };
  56906. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  56907. };
  56908. /**
  56909. * Serializes the data contained in the texture in a binary format.
  56910. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  56911. * as the spherical used in the lighting.
  56912. * @param url The HDR file url.
  56913. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  56914. * @param onError Method called if any error happens during download.
  56915. * @return The packed binary data.
  56916. */
  56917. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  56918. if (onError === void 0) { onError = null; }
  56919. // Needs the url tho create the texture.
  56920. if (!url) {
  56921. return null;
  56922. }
  56923. // Check Power of two size.
  56924. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  56925. return null;
  56926. }
  56927. var getDataCallback = function (dataBuffer) {
  56928. // Extract the raw linear data.
  56929. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  56930. // Generate harmonics if needed.
  56931. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  56932. // Generate seamless faces
  56933. var mipGeneratorArray = [];
  56934. // Data are known to be in +X +Y +Z -X -Y -Z
  56935. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  56936. mipGeneratorArray.push(cubeData.right); // +X
  56937. mipGeneratorArray.push(cubeData.left); // -X
  56938. mipGeneratorArray.push(cubeData.up); // +Y
  56939. mipGeneratorArray.push(cubeData.down); // -Y
  56940. mipGeneratorArray.push(cubeData.front); // +Z
  56941. mipGeneratorArray.push(cubeData.back); // -Z
  56942. // Custom setup of the generator matching with the PBR shader values.
  56943. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  56944. var mippedData = generator.filterCubeMap();
  56945. // Compute required byte length.
  56946. var byteLength = 1 * 4; // Raw Data Version int32.
  56947. byteLength += 4; // CubeMap max mip face size int32.
  56948. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  56949. // Add data size.
  56950. byteLength += 4; // Number of mip levels int32.
  56951. for (var level = 0; level < mippedData.length; level++) {
  56952. var mipSize = size >> level;
  56953. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  56954. }
  56955. // Prepare binary structure.
  56956. var buffer = new ArrayBuffer(byteLength);
  56957. var intArrayView = new Int32Array(buffer);
  56958. var floatArrayView = new Float32Array(buffer);
  56959. // Fill header.
  56960. intArrayView[0] = 1; // Version 1.
  56961. intArrayView[1] = size; // CubeMap max mip face size.
  56962. // Fill polynomial information.
  56963. sphericalPolynomial.x.toArray(floatArrayView, 2);
  56964. sphericalPolynomial.y.toArray(floatArrayView, 5);
  56965. sphericalPolynomial.z.toArray(floatArrayView, 8);
  56966. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  56967. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  56968. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  56969. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  56970. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  56971. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  56972. // Fill pixel data.
  56973. intArrayView[29] = mippedData.length; // Number of mip levels.
  56974. var startIndex = 30;
  56975. for (var level = 0; level < mippedData.length; level++) {
  56976. // Fill each pixel of the mip level.
  56977. var faceSize = Math.pow(size >> level, 2) * 3;
  56978. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  56979. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  56980. startIndex += faceSize;
  56981. }
  56982. }
  56983. // Callback.
  56984. callback(buffer);
  56985. };
  56986. // Download and process.
  56987. BABYLON.Tools.LoadFile(url, function (data) {
  56988. getDataCallback(data);
  56989. }, null, null, true, onError);
  56990. };
  56991. return HDRCubeTexture;
  56992. }(BABYLON.BaseTexture));
  56993. HDRCubeTexture._facesMapping = [
  56994. "right",
  56995. "up",
  56996. "front",
  56997. "left",
  56998. "down",
  56999. "back"
  57000. ];
  57001. BABYLON.HDRCubeTexture = HDRCubeTexture;
  57002. })(BABYLON || (BABYLON = {}));
  57003. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  57004. var BABYLON;
  57005. (function (BABYLON) {
  57006. var Debug;
  57007. (function (Debug) {
  57008. /**
  57009. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  57010. */
  57011. var SkeletonViewer = (function () {
  57012. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  57013. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  57014. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  57015. this.skeleton = skeleton;
  57016. this.mesh = mesh;
  57017. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  57018. this.renderingGroupId = renderingGroupId;
  57019. this.color = BABYLON.Color3.White();
  57020. this._debugLines = [];
  57021. this._isEnabled = false;
  57022. this._scene = scene;
  57023. this.update();
  57024. this._renderFunction = this.update.bind(this);
  57025. }
  57026. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  57027. get: function () {
  57028. return this._isEnabled;
  57029. },
  57030. set: function (value) {
  57031. if (this._isEnabled === value) {
  57032. return;
  57033. }
  57034. this._isEnabled = value;
  57035. if (value) {
  57036. this._scene.registerBeforeRender(this._renderFunction);
  57037. }
  57038. else {
  57039. this._scene.unregisterBeforeRender(this._renderFunction);
  57040. }
  57041. },
  57042. enumerable: true,
  57043. configurable: true
  57044. });
  57045. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  57046. if (x === void 0) { x = 0; }
  57047. if (y === void 0) { y = 0; }
  57048. if (z === void 0) { z = 0; }
  57049. var tmat = BABYLON.Tmp.Matrix[0];
  57050. var parentBone = bone.getParent();
  57051. tmat.copyFrom(bone.getLocalMatrix());
  57052. if (x !== 0 || y !== 0 || z !== 0) {
  57053. var tmat2 = BABYLON.Tmp.Matrix[1];
  57054. BABYLON.Matrix.IdentityToRef(tmat2);
  57055. tmat2.m[12] = x;
  57056. tmat2.m[13] = y;
  57057. tmat2.m[14] = z;
  57058. tmat2.multiplyToRef(tmat, tmat);
  57059. }
  57060. if (parentBone) {
  57061. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  57062. }
  57063. tmat.multiplyToRef(meshMat, tmat);
  57064. position.x = tmat.m[12];
  57065. position.y = tmat.m[13];
  57066. position.z = tmat.m[14];
  57067. };
  57068. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  57069. var len = bones.length;
  57070. for (var i = 0; i < len; i++) {
  57071. var bone = bones[i];
  57072. var points = this._debugLines[i];
  57073. if (!points) {
  57074. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57075. this._debugLines[i] = points;
  57076. }
  57077. this._getBonePosition(points[0], bone, meshMat);
  57078. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  57079. }
  57080. };
  57081. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  57082. var len = bones.length;
  57083. var boneNum = 0;
  57084. for (var i = len - 1; i >= 0; i--) {
  57085. var childBone = bones[i];
  57086. var parentBone = childBone.getParent();
  57087. if (!parentBone) {
  57088. continue;
  57089. }
  57090. var points = this._debugLines[boneNum];
  57091. if (!points) {
  57092. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57093. this._debugLines[boneNum] = points;
  57094. }
  57095. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  57096. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  57097. boneNum++;
  57098. }
  57099. };
  57100. SkeletonViewer.prototype.update = function () {
  57101. if (this.autoUpdateBonesMatrices) {
  57102. this.skeleton.computeAbsoluteTransforms();
  57103. }
  57104. if (this.skeleton.bones[0].length === undefined) {
  57105. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57106. }
  57107. else {
  57108. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  57109. }
  57110. if (!this._debugMesh) {
  57111. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  57112. this._debugMesh.renderingGroupId = this.renderingGroupId;
  57113. }
  57114. else {
  57115. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  57116. }
  57117. this._debugMesh.color = this.color;
  57118. };
  57119. SkeletonViewer.prototype.dispose = function () {
  57120. if (this._debugMesh) {
  57121. this.isEnabled = false;
  57122. this._debugMesh.dispose();
  57123. this._debugMesh = null;
  57124. }
  57125. };
  57126. return SkeletonViewer;
  57127. }());
  57128. Debug.SkeletonViewer = SkeletonViewer;
  57129. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57130. })(BABYLON || (BABYLON = {}));
  57131. //# sourceMappingURL=babylon.skeletonViewer.js.map
  57132. var BABYLON;
  57133. (function (BABYLON) {
  57134. var Debug;
  57135. (function (Debug) {
  57136. var AxesViewer = (function () {
  57137. function AxesViewer(scene, scaleLines) {
  57138. if (scaleLines === void 0) { scaleLines = 1; }
  57139. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57140. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57141. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  57142. this.scaleLines = 1;
  57143. this.scaleLines = scaleLines;
  57144. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  57145. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  57146. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  57147. this._xmesh.renderingGroupId = 2;
  57148. this._ymesh.renderingGroupId = 2;
  57149. this._zmesh.renderingGroupId = 2;
  57150. this._xmesh.material.checkReadyOnlyOnce = true;
  57151. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  57152. this._ymesh.material.checkReadyOnlyOnce = true;
  57153. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  57154. this._zmesh.material.checkReadyOnlyOnce = true;
  57155. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  57156. this.scene = scene;
  57157. }
  57158. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  57159. var scaleLines = this.scaleLines;
  57160. var point1 = this._xline[0];
  57161. var point2 = this._xline[1];
  57162. point1.x = position.x;
  57163. point1.y = position.y;
  57164. point1.z = position.z;
  57165. point2.x = point1.x + xaxis.x * scaleLines;
  57166. point2.y = point1.y + xaxis.y * scaleLines;
  57167. point2.z = point1.z + xaxis.z * scaleLines;
  57168. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  57169. point1 = this._yline[0];
  57170. point2 = this._yline[1];
  57171. point1.x = position.x;
  57172. point1.y = position.y;
  57173. point1.z = position.z;
  57174. point2.x = point1.x + yaxis.x * scaleLines;
  57175. point2.y = point1.y + yaxis.y * scaleLines;
  57176. point2.z = point1.z + yaxis.z * scaleLines;
  57177. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  57178. point1 = this._zline[0];
  57179. point2 = this._zline[1];
  57180. point1.x = position.x;
  57181. point1.y = position.y;
  57182. point1.z = position.z;
  57183. point2.x = point1.x + zaxis.x * scaleLines;
  57184. point2.y = point1.y + zaxis.y * scaleLines;
  57185. point2.z = point1.z + zaxis.z * scaleLines;
  57186. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  57187. };
  57188. AxesViewer.prototype.dispose = function () {
  57189. if (this._xmesh) {
  57190. this._xmesh.dispose();
  57191. this._ymesh.dispose();
  57192. this._zmesh.dispose();
  57193. this._xmesh = null;
  57194. this._ymesh = null;
  57195. this._zmesh = null;
  57196. this._xline = null;
  57197. this._yline = null;
  57198. this._zline = null;
  57199. this.scene = null;
  57200. }
  57201. };
  57202. return AxesViewer;
  57203. }());
  57204. Debug.AxesViewer = AxesViewer;
  57205. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57206. })(BABYLON || (BABYLON = {}));
  57207. //# sourceMappingURL=babylon.axesViewer.js.map
  57208. var BABYLON;
  57209. (function (BABYLON) {
  57210. var Debug;
  57211. (function (Debug) {
  57212. var BoneAxesViewer = (function (_super) {
  57213. __extends(BoneAxesViewer, _super);
  57214. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  57215. if (scaleLines === void 0) { scaleLines = 1; }
  57216. var _this = _super.call(this, scene, scaleLines) || this;
  57217. _this.pos = BABYLON.Vector3.Zero();
  57218. _this.xaxis = BABYLON.Vector3.Zero();
  57219. _this.yaxis = BABYLON.Vector3.Zero();
  57220. _this.zaxis = BABYLON.Vector3.Zero();
  57221. _this.mesh = mesh;
  57222. _this.bone = bone;
  57223. return _this;
  57224. }
  57225. BoneAxesViewer.prototype.update = function () {
  57226. var bone = this.bone;
  57227. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  57228. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  57229. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  57230. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  57231. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  57232. };
  57233. BoneAxesViewer.prototype.dispose = function () {
  57234. if (this.pos) {
  57235. this.pos = null;
  57236. this.xaxis = null;
  57237. this.yaxis = null;
  57238. this.zaxis = null;
  57239. this.mesh = null;
  57240. this.bone = null;
  57241. _super.prototype.dispose.call(this);
  57242. }
  57243. };
  57244. return BoneAxesViewer;
  57245. }(Debug.AxesViewer));
  57246. Debug.BoneAxesViewer = BoneAxesViewer;
  57247. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  57248. })(BABYLON || (BABYLON = {}));
  57249. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  57250. var BABYLON;
  57251. (function (BABYLON) {
  57252. /**
  57253. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  57254. * It can help converting any input color in a desired output one. This can then be used to create effects
  57255. * from sepia, black and white to sixties or futuristic rendering...
  57256. *
  57257. * The only supported format is currently 3dl.
  57258. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  57259. */
  57260. var ColorGradingTexture = (function (_super) {
  57261. __extends(ColorGradingTexture, _super);
  57262. /**
  57263. * Instantiates a ColorGradingTexture from the following parameters.
  57264. *
  57265. * @param url The location of the color gradind data (currently only supporting 3dl)
  57266. * @param scene The scene the texture will be used in
  57267. */
  57268. function ColorGradingTexture(url, scene) {
  57269. var _this = _super.call(this, scene) || this;
  57270. if (!url) {
  57271. return _this;
  57272. }
  57273. _this._textureMatrix = BABYLON.Matrix.Identity();
  57274. _this.name = url;
  57275. _this.url = url;
  57276. _this.hasAlpha = false;
  57277. _this.isCube = false;
  57278. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57279. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57280. _this.anisotropicFilteringLevel = 1;
  57281. _this._texture = _this._getFromCache(url, true);
  57282. if (!_this._texture) {
  57283. if (!scene.useDelayedTextureLoading) {
  57284. _this.loadTexture();
  57285. }
  57286. else {
  57287. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57288. }
  57289. }
  57290. return _this;
  57291. }
  57292. /**
  57293. * Returns the texture matrix used in most of the material.
  57294. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  57295. */
  57296. ColorGradingTexture.prototype.getTextureMatrix = function () {
  57297. return this._textureMatrix;
  57298. };
  57299. /**
  57300. * Occurs when the file being loaded is a .3dl LUT file.
  57301. */
  57302. ColorGradingTexture.prototype.load3dlTexture = function () {
  57303. var _this = this;
  57304. var mipLevels = 0;
  57305. var floatArrayView = null;
  57306. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57307. this._texture = texture;
  57308. var callback = function (text) {
  57309. var data;
  57310. var tempData;
  57311. var line;
  57312. var lines = text.split('\n');
  57313. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  57314. var maxColor = 0;
  57315. for (var i = 0; i < lines.length; i++) {
  57316. line = lines[i];
  57317. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  57318. continue;
  57319. if (line.indexOf('#') === 0)
  57320. continue;
  57321. var words = line.split(" ");
  57322. if (size === 0) {
  57323. // Number of space + one
  57324. size = words.length;
  57325. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  57326. tempData = new Float32Array(size * size * size * 4);
  57327. continue;
  57328. }
  57329. if (size != 0) {
  57330. var r = Math.max(parseInt(words[0]), 0);
  57331. var g = Math.max(parseInt(words[1]), 0);
  57332. var b = Math.max(parseInt(words[2]), 0);
  57333. maxColor = Math.max(r, maxColor);
  57334. maxColor = Math.max(g, maxColor);
  57335. maxColor = Math.max(b, maxColor);
  57336. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  57337. tempData[pixelStorageIndex + 0] = r;
  57338. tempData[pixelStorageIndex + 1] = g;
  57339. tempData[pixelStorageIndex + 2] = b;
  57340. tempData[pixelStorageIndex + 3] = 0;
  57341. pixelIndexSlice++;
  57342. if (pixelIndexSlice % size == 0) {
  57343. pixelIndexH++;
  57344. pixelIndexSlice = 0;
  57345. if (pixelIndexH % size == 0) {
  57346. pixelIndexW++;
  57347. pixelIndexH = 0;
  57348. }
  57349. }
  57350. }
  57351. }
  57352. for (var i = 0; i < tempData.length; i++) {
  57353. var value = tempData[i];
  57354. data[i] = (value / maxColor * 255);
  57355. }
  57356. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  57357. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  57358. };
  57359. BABYLON.Tools.LoadFile(this.url, callback);
  57360. return this._texture;
  57361. };
  57362. /**
  57363. * Starts the loading process of the texture.
  57364. */
  57365. ColorGradingTexture.prototype.loadTexture = function () {
  57366. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  57367. this.load3dlTexture();
  57368. }
  57369. };
  57370. /**
  57371. * Clones the color gradind texture.
  57372. */
  57373. ColorGradingTexture.prototype.clone = function () {
  57374. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  57375. // Base texture
  57376. newTexture.level = this.level;
  57377. return newTexture;
  57378. };
  57379. /**
  57380. * Called during delayed load for textures.
  57381. */
  57382. ColorGradingTexture.prototype.delayLoad = function () {
  57383. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57384. return;
  57385. }
  57386. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57387. this._texture = this._getFromCache(this.url, true);
  57388. if (!this._texture) {
  57389. this.loadTexture();
  57390. }
  57391. };
  57392. /**
  57393. * Binds the color grading to the shader.
  57394. * @param colorGrading The texture to bind
  57395. * @param effect The effect to bind to
  57396. */
  57397. ColorGradingTexture.Bind = function (colorGrading, effect) {
  57398. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  57399. var x = colorGrading.level; // Texture Level
  57400. var y = colorGrading.getSize().height; // Texture Size example with 8
  57401. var z = y - 1.0; // SizeMinusOne 8 - 1
  57402. var w = 1 / y; // Space of 1 slice 1 / 8
  57403. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  57404. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  57405. 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
  57406. 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
  57407. 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
  57408. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  57409. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  57410. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  57411. };
  57412. /**
  57413. * Prepare the list of uniforms associated with the ColorGrading effects.
  57414. * @param uniformsList The list of uniforms used in the effect
  57415. * @param samplersList The list of samplers used in the effect
  57416. */
  57417. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  57418. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  57419. samplersList.push("cameraColorGrading2DSampler");
  57420. };
  57421. /**
  57422. * Parses a color grading texture serialized by Babylon.
  57423. * @param parsedTexture The texture information being parsedTexture
  57424. * @param scene The scene to load the texture in
  57425. * @param rootUrl The root url of the data assets to load
  57426. * @return A color gradind texture
  57427. */
  57428. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57429. var texture = null;
  57430. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57431. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57432. texture.name = parsedTexture.name;
  57433. texture.level = parsedTexture.level;
  57434. }
  57435. return texture;
  57436. };
  57437. /**
  57438. * Serializes the LUT texture to json format.
  57439. */
  57440. ColorGradingTexture.prototype.serialize = function () {
  57441. if (!this.name) {
  57442. return null;
  57443. }
  57444. var serializationObject = {};
  57445. serializationObject.name = this.name;
  57446. serializationObject.level = this.level;
  57447. serializationObject.customType = "BABYLON.ColorGradingTexture";
  57448. return serializationObject;
  57449. };
  57450. return ColorGradingTexture;
  57451. }(BABYLON.BaseTexture));
  57452. /**
  57453. * Empty line regex stored for GC.
  57454. */
  57455. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57456. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57457. })(BABYLON || (BABYLON = {}));
  57458. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  57459. var BABYLON;
  57460. (function (BABYLON) {
  57461. /**
  57462. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57463. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57464. * 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;
  57465. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57466. */
  57467. var ColorCurves = (function () {
  57468. function ColorCurves() {
  57469. this._dirty = true;
  57470. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57471. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57472. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57473. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57474. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57475. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57476. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57477. this._globalHue = 30;
  57478. this._globalDensity = 0;
  57479. this._globalSaturation = 0;
  57480. this._globalExposure = 0;
  57481. this._highlightsHue = 30;
  57482. this._highlightsDensity = 0;
  57483. this._highlightsSaturation = 0;
  57484. this._highlightsExposure = 0;
  57485. this._midtonesHue = 30;
  57486. this._midtonesDensity = 0;
  57487. this._midtonesSaturation = 0;
  57488. this._midtonesExposure = 0;
  57489. this._shadowsHue = 30;
  57490. this._shadowsDensity = 0;
  57491. this._shadowsSaturation = 0;
  57492. this._shadowsExposure = 0;
  57493. }
  57494. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57495. /**
  57496. * Gets the global Hue value.
  57497. * 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).
  57498. */
  57499. get: function () {
  57500. return this._globalHue;
  57501. },
  57502. /**
  57503. * Sets the global Hue value.
  57504. * 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).
  57505. */
  57506. set: function (value) {
  57507. this._globalHue = value;
  57508. this._dirty = true;
  57509. },
  57510. enumerable: true,
  57511. configurable: true
  57512. });
  57513. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57514. /**
  57515. * Gets the global Density value.
  57516. * 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.
  57517. * Values less than zero provide a filter of opposite hue.
  57518. */
  57519. get: function () {
  57520. return this._globalDensity;
  57521. },
  57522. /**
  57523. * Sets the global Density value.
  57524. * 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.
  57525. * Values less than zero provide a filter of opposite hue.
  57526. */
  57527. set: function (value) {
  57528. this._globalDensity = value;
  57529. this._dirty = true;
  57530. },
  57531. enumerable: true,
  57532. configurable: true
  57533. });
  57534. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57535. /**
  57536. * Gets the global Saturation value.
  57537. * 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.
  57538. */
  57539. get: function () {
  57540. return this._globalSaturation;
  57541. },
  57542. /**
  57543. * Sets the global Saturation value.
  57544. * 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.
  57545. */
  57546. set: function (value) {
  57547. this._globalSaturation = value;
  57548. this._dirty = true;
  57549. },
  57550. enumerable: true,
  57551. configurable: true
  57552. });
  57553. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57554. /**
  57555. * Gets the highlights Hue value.
  57556. * 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).
  57557. */
  57558. get: function () {
  57559. return this._highlightsHue;
  57560. },
  57561. /**
  57562. * Sets the highlights Hue value.
  57563. * 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).
  57564. */
  57565. set: function (value) {
  57566. this._highlightsHue = value;
  57567. this._dirty = true;
  57568. },
  57569. enumerable: true,
  57570. configurable: true
  57571. });
  57572. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57573. /**
  57574. * Gets the highlights Density value.
  57575. * 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.
  57576. * Values less than zero provide a filter of opposite hue.
  57577. */
  57578. get: function () {
  57579. return this._highlightsDensity;
  57580. },
  57581. /**
  57582. * Sets the highlights Density value.
  57583. * 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.
  57584. * Values less than zero provide a filter of opposite hue.
  57585. */
  57586. set: function (value) {
  57587. this._highlightsDensity = value;
  57588. this._dirty = true;
  57589. },
  57590. enumerable: true,
  57591. configurable: true
  57592. });
  57593. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57594. /**
  57595. * Gets the highlights Saturation value.
  57596. * 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.
  57597. */
  57598. get: function () {
  57599. return this._highlightsSaturation;
  57600. },
  57601. /**
  57602. * Sets the highlights Saturation value.
  57603. * 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.
  57604. */
  57605. set: function (value) {
  57606. this._highlightsSaturation = value;
  57607. this._dirty = true;
  57608. },
  57609. enumerable: true,
  57610. configurable: true
  57611. });
  57612. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57613. /**
  57614. * Gets the highlights Exposure value.
  57615. * 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.
  57616. */
  57617. get: function () {
  57618. return this._highlightsExposure;
  57619. },
  57620. /**
  57621. * Sets the highlights Exposure value.
  57622. * 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.
  57623. */
  57624. set: function (value) {
  57625. this._highlightsExposure = value;
  57626. this._dirty = true;
  57627. },
  57628. enumerable: true,
  57629. configurable: true
  57630. });
  57631. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57632. /**
  57633. * Gets the midtones Hue value.
  57634. * 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).
  57635. */
  57636. get: function () {
  57637. return this._midtonesHue;
  57638. },
  57639. /**
  57640. * Sets the midtones Hue value.
  57641. * 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).
  57642. */
  57643. set: function (value) {
  57644. this._midtonesHue = value;
  57645. this._dirty = true;
  57646. },
  57647. enumerable: true,
  57648. configurable: true
  57649. });
  57650. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57651. /**
  57652. * Gets the midtones Density value.
  57653. * 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.
  57654. * Values less than zero provide a filter of opposite hue.
  57655. */
  57656. get: function () {
  57657. return this._midtonesDensity;
  57658. },
  57659. /**
  57660. * Sets the midtones Density value.
  57661. * 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.
  57662. * Values less than zero provide a filter of opposite hue.
  57663. */
  57664. set: function (value) {
  57665. this._midtonesDensity = value;
  57666. this._dirty = true;
  57667. },
  57668. enumerable: true,
  57669. configurable: true
  57670. });
  57671. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57672. /**
  57673. * Gets the midtones Saturation value.
  57674. * 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.
  57675. */
  57676. get: function () {
  57677. return this._midtonesSaturation;
  57678. },
  57679. /**
  57680. * Sets the midtones Saturation value.
  57681. * 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.
  57682. */
  57683. set: function (value) {
  57684. this._midtonesSaturation = value;
  57685. this._dirty = true;
  57686. },
  57687. enumerable: true,
  57688. configurable: true
  57689. });
  57690. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57691. /**
  57692. * Gets the midtones Exposure value.
  57693. * 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.
  57694. */
  57695. get: function () {
  57696. return this._midtonesExposure;
  57697. },
  57698. /**
  57699. * Sets the midtones Exposure value.
  57700. * 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.
  57701. */
  57702. set: function (value) {
  57703. this._midtonesExposure = value;
  57704. this._dirty = true;
  57705. },
  57706. enumerable: true,
  57707. configurable: true
  57708. });
  57709. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57710. /**
  57711. * Gets the shadows Hue value.
  57712. * 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).
  57713. */
  57714. get: function () {
  57715. return this._shadowsHue;
  57716. },
  57717. /**
  57718. * Sets the shadows Hue value.
  57719. * 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).
  57720. */
  57721. set: function (value) {
  57722. this._shadowsHue = value;
  57723. this._dirty = true;
  57724. },
  57725. enumerable: true,
  57726. configurable: true
  57727. });
  57728. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57729. /**
  57730. * Gets the shadows Density value.
  57731. * 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.
  57732. * Values less than zero provide a filter of opposite hue.
  57733. */
  57734. get: function () {
  57735. return this._shadowsDensity;
  57736. },
  57737. /**
  57738. * Sets the shadows Density value.
  57739. * 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.
  57740. * Values less than zero provide a filter of opposite hue.
  57741. */
  57742. set: function (value) {
  57743. this._shadowsDensity = value;
  57744. this._dirty = true;
  57745. },
  57746. enumerable: true,
  57747. configurable: true
  57748. });
  57749. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57750. /**
  57751. * Gets the shadows Saturation value.
  57752. * 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.
  57753. */
  57754. get: function () {
  57755. return this._shadowsSaturation;
  57756. },
  57757. /**
  57758. * Sets the shadows Saturation value.
  57759. * 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.
  57760. */
  57761. set: function (value) {
  57762. this._shadowsSaturation = value;
  57763. this._dirty = true;
  57764. },
  57765. enumerable: true,
  57766. configurable: true
  57767. });
  57768. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57769. /**
  57770. * Gets the shadows Exposure value.
  57771. * 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.
  57772. */
  57773. get: function () {
  57774. return this._shadowsExposure;
  57775. },
  57776. /**
  57777. * Sets the shadows Exposure value.
  57778. * 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.
  57779. */
  57780. set: function (value) {
  57781. this._shadowsExposure = value;
  57782. this._dirty = true;
  57783. },
  57784. enumerable: true,
  57785. configurable: true
  57786. });
  57787. /**
  57788. * Binds the color curves to the shader.
  57789. * @param colorCurves The color curve to bind
  57790. * @param effect The effect to bind to
  57791. */
  57792. ColorCurves.Bind = function (colorCurves, effect) {
  57793. if (colorCurves._dirty) {
  57794. colorCurves._dirty = false;
  57795. // Fill in global info.
  57796. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57797. // Compute highlights info.
  57798. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57799. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57800. // Compute midtones info.
  57801. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57802. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57803. // Compute shadows info.
  57804. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57805. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57806. // Compute deltas (neutral is midtones).
  57807. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57808. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57809. }
  57810. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57811. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57812. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57813. };
  57814. /**
  57815. * Prepare the list of uniforms associated with the ColorCurves effects.
  57816. * @param uniformsList The list of uniforms used in the effect
  57817. */
  57818. ColorCurves.PrepareUniforms = function (uniformsList) {
  57819. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57820. };
  57821. /**
  57822. * Returns color grading data based on a hue, density, saturation and exposure value.
  57823. * @param filterHue The hue of the color filter.
  57824. * @param filterDensity The density of the color filter.
  57825. * @param saturation The saturation.
  57826. * @param exposure The exposure.
  57827. * @param result The result data container.
  57828. */
  57829. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57830. if (hue == null) {
  57831. return;
  57832. }
  57833. hue = ColorCurves.clamp(hue, 0, 360);
  57834. density = ColorCurves.clamp(density, -100, 100);
  57835. saturation = ColorCurves.clamp(saturation, -100, 100);
  57836. exposure = ColorCurves.clamp(exposure, -100, 100);
  57837. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57838. // so that the maximum filter density is only 50% control. This provides fine control
  57839. // for small values and reasonable range.
  57840. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57841. density *= 0.5;
  57842. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57843. if (density < 0) {
  57844. density *= -1;
  57845. hue = (hue + 180) % 360;
  57846. }
  57847. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57848. result.scaleToRef(2, result);
  57849. result.a = 1 + 0.01 * saturation;
  57850. };
  57851. /**
  57852. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57853. * @param value The input slider value in range [-100,100].
  57854. * @returns Adjusted value.
  57855. */
  57856. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57857. value /= 100;
  57858. var x = Math.abs(value);
  57859. x = Math.pow(x, 2);
  57860. if (value < 0) {
  57861. x *= -1;
  57862. }
  57863. x *= 100;
  57864. return x;
  57865. };
  57866. /**
  57867. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57868. * @param hue The hue (H) input.
  57869. * @param saturation The saturation (S) input.
  57870. * @param brightness The brightness (B) input.
  57871. * @result An RGBA color represented as Vector4.
  57872. */
  57873. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57874. var h = ColorCurves.clamp(hue, 0, 360);
  57875. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57876. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57877. if (s === 0) {
  57878. result.r = v;
  57879. result.g = v;
  57880. result.b = v;
  57881. }
  57882. else {
  57883. // sector 0 to 5
  57884. h /= 60;
  57885. var i = Math.floor(h);
  57886. // fractional part of h
  57887. var f = h - i;
  57888. var p = v * (1 - s);
  57889. var q = v * (1 - s * f);
  57890. var t = v * (1 - s * (1 - f));
  57891. switch (i) {
  57892. case 0:
  57893. result.r = v;
  57894. result.g = t;
  57895. result.b = p;
  57896. break;
  57897. case 1:
  57898. result.r = q;
  57899. result.g = v;
  57900. result.b = p;
  57901. break;
  57902. case 2:
  57903. result.r = p;
  57904. result.g = v;
  57905. result.b = t;
  57906. break;
  57907. case 3:
  57908. result.r = p;
  57909. result.g = q;
  57910. result.b = v;
  57911. break;
  57912. case 4:
  57913. result.r = t;
  57914. result.g = p;
  57915. result.b = v;
  57916. break;
  57917. default:
  57918. result.r = v;
  57919. result.g = p;
  57920. result.b = q;
  57921. break;
  57922. }
  57923. }
  57924. result.a = 1;
  57925. };
  57926. /**
  57927. * Returns a value clamped between min and max
  57928. * @param value The value to clamp
  57929. * @param min The minimum of value
  57930. * @param max The maximum of value
  57931. * @returns The clamped value.
  57932. */
  57933. ColorCurves.clamp = function (value, min, max) {
  57934. return Math.min(Math.max(value, min), max);
  57935. };
  57936. /**
  57937. * Clones the current color curve instance.
  57938. * @return The cloned curves
  57939. */
  57940. ColorCurves.prototype.clone = function () {
  57941. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57942. };
  57943. /**
  57944. * Serializes the current color curve instance to a json representation.
  57945. * @return a JSON representation
  57946. */
  57947. ColorCurves.prototype.serialize = function () {
  57948. return BABYLON.SerializationHelper.Serialize(this);
  57949. };
  57950. /**
  57951. * Parses the color curve from a json representation.
  57952. * @param source the JSON source to parse
  57953. * @return The parsed curves
  57954. */
  57955. ColorCurves.Parse = function (source) {
  57956. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57957. };
  57958. return ColorCurves;
  57959. }());
  57960. __decorate([
  57961. BABYLON.serialize()
  57962. ], ColorCurves.prototype, "_globalHue", void 0);
  57963. __decorate([
  57964. BABYLON.serialize()
  57965. ], ColorCurves.prototype, "_globalDensity", void 0);
  57966. __decorate([
  57967. BABYLON.serialize()
  57968. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57969. __decorate([
  57970. BABYLON.serialize()
  57971. ], ColorCurves.prototype, "_globalExposure", void 0);
  57972. __decorate([
  57973. BABYLON.serialize()
  57974. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57975. __decorate([
  57976. BABYLON.serialize()
  57977. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57978. __decorate([
  57979. BABYLON.serialize()
  57980. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57981. __decorate([
  57982. BABYLON.serialize()
  57983. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57984. __decorate([
  57985. BABYLON.serialize()
  57986. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57987. __decorate([
  57988. BABYLON.serialize()
  57989. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57990. __decorate([
  57991. BABYLON.serialize()
  57992. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57993. __decorate([
  57994. BABYLON.serialize()
  57995. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57996. BABYLON.ColorCurves = ColorCurves;
  57997. })(BABYLON || (BABYLON = {}));
  57998. //# sourceMappingURL=babylon.colorCurves.js.map
  57999. var BABYLON;
  58000. (function (BABYLON) {
  58001. var PBRMaterialDefines = (function (_super) {
  58002. __extends(PBRMaterialDefines, _super);
  58003. function PBRMaterialDefines() {
  58004. var _this = _super.call(this) || this;
  58005. _this.ALBEDO = false;
  58006. _this.AMBIENT = false;
  58007. _this.OPACITY = false;
  58008. _this.OPACITYRGB = false;
  58009. _this.REFLECTION = false;
  58010. _this.EMISSIVE = false;
  58011. _this.REFLECTIVITY = false;
  58012. _this.BUMP = false;
  58013. _this.PARALLAX = false;
  58014. _this.PARALLAXOCCLUSION = false;
  58015. _this.SPECULAROVERALPHA = false;
  58016. _this.CLIPPLANE = false;
  58017. _this.ALPHATEST = false;
  58018. _this.ALPHAFROMALBEDO = false;
  58019. _this.POINTSIZE = false;
  58020. _this.FOG = false;
  58021. _this.SPECULARTERM = false;
  58022. _this.OPACITYFRESNEL = false;
  58023. _this.EMISSIVEFRESNEL = false;
  58024. _this.FRESNEL = false;
  58025. _this.NORMAL = false;
  58026. _this.TANGENT = false;
  58027. _this.UV1 = false;
  58028. _this.UV2 = false;
  58029. _this.VERTEXCOLOR = false;
  58030. _this.VERTEXALPHA = false;
  58031. _this.NUM_BONE_INFLUENCERS = 0;
  58032. _this.BonesPerMesh = 0;
  58033. _this.INSTANCES = false;
  58034. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  58035. _this.MICROSURFACEAUTOMATIC = false;
  58036. _this.EMISSIVEASILLUMINATION = false;
  58037. _this.LINKEMISSIVEWITHALBEDO = false;
  58038. _this.LIGHTMAP = false;
  58039. _this.USELIGHTMAPASSHADOWMAP = false;
  58040. _this.REFLECTIONMAP_3D = false;
  58041. _this.REFLECTIONMAP_SPHERICAL = false;
  58042. _this.REFLECTIONMAP_PLANAR = false;
  58043. _this.REFLECTIONMAP_CUBIC = false;
  58044. _this.REFLECTIONMAP_PROJECTION = false;
  58045. _this.REFLECTIONMAP_SKYBOX = false;
  58046. _this.REFLECTIONMAP_EXPLICIT = false;
  58047. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  58048. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  58049. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  58050. _this.INVERTCUBICMAP = false;
  58051. _this.LOGARITHMICDEPTH = false;
  58052. _this.CAMERATONEMAP = false;
  58053. _this.CAMERACONTRAST = false;
  58054. _this.CAMERACOLORGRADING = false;
  58055. _this.CAMERACOLORCURVES = false;
  58056. _this.OVERLOADEDVALUES = false;
  58057. _this.OVERLOADEDSHADOWVALUES = false;
  58058. _this.USESPHERICALFROMREFLECTIONMAP = false;
  58059. _this.REFRACTION = false;
  58060. _this.REFRACTIONMAP_3D = false;
  58061. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  58062. _this.REFRACTIONMAPINLINEARSPACE = false;
  58063. _this.LODBASEDMICROSFURACE = false;
  58064. _this.USEPHYSICALLIGHTFALLOFF = false;
  58065. _this.RADIANCEOVERALPHA = false;
  58066. _this.USEPMREMREFLECTION = false;
  58067. _this.USEPMREMREFRACTION = false;
  58068. _this.INVERTNORMALMAPX = false;
  58069. _this.INVERTNORMALMAPY = false;
  58070. _this.TWOSIDEDLIGHTING = false;
  58071. _this.SHADOWFULLFLOAT = false;
  58072. _this.METALLICWORKFLOW = false;
  58073. _this.METALLICROUGHNESSMAP = false;
  58074. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  58075. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  58076. _this.rebuild();
  58077. return _this;
  58078. }
  58079. return PBRMaterialDefines;
  58080. }(BABYLON.MaterialDefines));
  58081. /**
  58082. * The Physically based material of BJS.
  58083. *
  58084. * This offers the main features of a standard PBR material.
  58085. * For more information, please refer to the documentation :
  58086. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  58087. */
  58088. var PBRMaterial = (function (_super) {
  58089. __extends(PBRMaterial, _super);
  58090. /**
  58091. * Instantiates a new PBRMaterial instance.
  58092. *
  58093. * @param name The material name
  58094. * @param scene The scene the material will be use in.
  58095. */
  58096. function PBRMaterial(name, scene) {
  58097. var _this = _super.call(this, name, scene) || this;
  58098. /**
  58099. * Intensity of the direct lights e.g. the four lights available in your scene.
  58100. * This impacts both the direct diffuse and specular highlights.
  58101. */
  58102. _this.directIntensity = 1.0;
  58103. /**
  58104. * Intensity of the emissive part of the material.
  58105. * This helps controlling the emissive effect without modifying the emissive color.
  58106. */
  58107. _this.emissiveIntensity = 1.0;
  58108. /**
  58109. * Intensity of the environment e.g. how much the environment will light the object
  58110. * either through harmonics for rough material or through the refelction for shiny ones.
  58111. */
  58112. _this.environmentIntensity = 1.0;
  58113. /**
  58114. * This is a special control allowing the reduction of the specular highlights coming from the
  58115. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  58116. */
  58117. _this.specularIntensity = 1.0;
  58118. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  58119. /**
  58120. * Debug Control allowing disabling the bump map on this material.
  58121. */
  58122. _this.disableBumpMap = false;
  58123. /**
  58124. * Debug Control helping enforcing or dropping the darkness of shadows.
  58125. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  58126. */
  58127. _this.overloadedShadowIntensity = 1.0;
  58128. /**
  58129. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  58130. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  58131. */
  58132. _this.overloadedShadeIntensity = 1.0;
  58133. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  58134. /**
  58135. * The camera exposure used on this material.
  58136. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  58137. * This corresponds to a photographic exposure.
  58138. */
  58139. _this.cameraExposure = 1.0;
  58140. /**
  58141. * The camera contrast used on this material.
  58142. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  58143. */
  58144. _this.cameraContrast = 1.0;
  58145. /**
  58146. * Color Grading 2D Lookup Texture.
  58147. * This allows special effects like sepia, black and white to sixties rendering style.
  58148. */
  58149. _this.cameraColorGradingTexture = null;
  58150. /**
  58151. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  58152. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  58153. * 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;
  58154. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  58155. */
  58156. _this.cameraColorCurves = null;
  58157. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  58158. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  58159. /**
  58160. * Debug Control allowing to overload the ambient color.
  58161. * This as to be use with the overloadedAmbientIntensity parameter.
  58162. */
  58163. _this.overloadedAmbient = BABYLON.Color3.White();
  58164. /**
  58165. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  58166. */
  58167. _this.overloadedAmbientIntensity = 0.0;
  58168. /**
  58169. * Debug Control allowing to overload the albedo color.
  58170. * This as to be use with the overloadedAlbedoIntensity parameter.
  58171. */
  58172. _this.overloadedAlbedo = BABYLON.Color3.White();
  58173. /**
  58174. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  58175. */
  58176. _this.overloadedAlbedoIntensity = 0.0;
  58177. /**
  58178. * Debug Control allowing to overload the reflectivity color.
  58179. * This as to be use with the overloadedReflectivityIntensity parameter.
  58180. */
  58181. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  58182. /**
  58183. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  58184. */
  58185. _this.overloadedReflectivityIntensity = 0.0;
  58186. /**
  58187. * Debug Control allowing to overload the emissive color.
  58188. * This as to be use with the overloadedEmissiveIntensity parameter.
  58189. */
  58190. _this.overloadedEmissive = BABYLON.Color3.White();
  58191. /**
  58192. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  58193. */
  58194. _this.overloadedEmissiveIntensity = 0.0;
  58195. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  58196. /**
  58197. * Debug Control allowing to overload the reflection color.
  58198. * This as to be use with the overloadedReflectionIntensity parameter.
  58199. */
  58200. _this.overloadedReflection = BABYLON.Color3.White();
  58201. /**
  58202. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  58203. */
  58204. _this.overloadedReflectionIntensity = 0.0;
  58205. /**
  58206. * Debug Control allowing to overload the microsurface.
  58207. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  58208. */
  58209. _this.overloadedMicroSurface = 0.0;
  58210. /**
  58211. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  58212. */
  58213. _this.overloadedMicroSurfaceIntensity = 0.0;
  58214. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  58215. /**
  58216. * AKA Occlusion Texture Intensity in other nomenclature.
  58217. */
  58218. _this.ambientTextureStrength = 1.0;
  58219. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  58220. /**
  58221. * AKA Diffuse Color in other nomenclature.
  58222. */
  58223. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  58224. /**
  58225. * AKA Specular Color in other nomenclature.
  58226. */
  58227. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  58228. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  58229. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  58230. /**
  58231. * AKA Glossiness in other nomenclature.
  58232. */
  58233. _this.microSurface = 0.9;
  58234. /**
  58235. * source material index of refraction (IOR)' / 'destination material IOR.
  58236. */
  58237. _this.indexOfRefraction = 0.66;
  58238. /**
  58239. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  58240. */
  58241. _this.invertRefractionY = false;
  58242. /**
  58243. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  58244. * Materials half opaque for instance using refraction could benefit from this control.
  58245. */
  58246. _this.linkRefractionWithTransparency = false;
  58247. /**
  58248. * The emissive and albedo are linked to never be more than one (Energy conservation).
  58249. */
  58250. _this.linkEmissiveWithAlbedo = false;
  58251. _this.useLightmapAsShadowmap = false;
  58252. /**
  58253. * In this mode, the emissive informtaion will always be added to the lighting once.
  58254. * A light for instance can be thought as emissive.
  58255. */
  58256. _this.useEmissiveAsIllumination = false;
  58257. /**
  58258. * Secifies that the alpha is coming form the albedo channel alpha channel.
  58259. */
  58260. _this.useAlphaFromAlbedoTexture = false;
  58261. /**
  58262. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  58263. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  58264. */
  58265. _this.useSpecularOverAlpha = true;
  58266. /**
  58267. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  58268. */
  58269. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  58270. /**
  58271. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  58272. */
  58273. _this.useRoughnessFromMetallicTextureAlpha = true;
  58274. /**
  58275. * Specifies if the metallic texture contains the roughness information in its green channel.
  58276. */
  58277. _this.useRoughnessFromMetallicTextureGreen = false;
  58278. /**
  58279. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  58280. * The material will try to infer what glossiness each pixel should be.
  58281. */
  58282. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  58283. /**
  58284. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  58285. * the creation of the material.
  58286. */
  58287. _this.useScalarInLinearSpace = false;
  58288. /**
  58289. * BJS is using an harcoded light falloff based on a manually sets up range.
  58290. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  58291. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  58292. */
  58293. _this.usePhysicalLightFalloff = true;
  58294. /**
  58295. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  58296. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  58297. */
  58298. _this.useRadianceOverAlpha = true;
  58299. /**
  58300. * Allows using the bump map in parallax mode.
  58301. */
  58302. _this.useParallax = false;
  58303. /**
  58304. * Allows using the bump map in parallax occlusion mode.
  58305. */
  58306. _this.useParallaxOcclusion = false;
  58307. /**
  58308. * Controls the scale bias of the parallax mode.
  58309. */
  58310. _this.parallaxScaleBias = 0.05;
  58311. /**
  58312. * If sets to true, disables all the lights affecting the material.
  58313. */
  58314. _this.disableLighting = false;
  58315. /**
  58316. * Number of Simultaneous lights allowed on the material.
  58317. */
  58318. _this.maxSimultaneousLights = 4;
  58319. /**
  58320. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  58321. */
  58322. _this.invertNormalMapX = false;
  58323. /**
  58324. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  58325. */
  58326. _this.invertNormalMapY = false;
  58327. /**
  58328. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  58329. */
  58330. _this.twoSidedLighting = false;
  58331. _this._renderTargets = new BABYLON.SmartArray(16);
  58332. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  58333. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  58334. _this._tempColor = new BABYLON.Color3();
  58335. _this._defines = new PBRMaterialDefines();
  58336. _this._cachedDefines = new PBRMaterialDefines();
  58337. _this._myScene = null;
  58338. _this._myShadowGenerator = null;
  58339. _this._cachedDefines.BonesPerMesh = -1;
  58340. _this.getRenderTargetTextures = function () {
  58341. _this._renderTargets.reset();
  58342. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  58343. _this._renderTargets.push(_this.reflectionTexture);
  58344. }
  58345. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  58346. _this._renderTargets.push(_this.refractionTexture);
  58347. }
  58348. return _this._renderTargets;
  58349. };
  58350. return _this;
  58351. }
  58352. PBRMaterial.prototype.getClassName = function () {
  58353. return "PBRMaterial";
  58354. };
  58355. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  58356. get: function () {
  58357. return this._useLogarithmicDepth;
  58358. },
  58359. set: function (value) {
  58360. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  58361. },
  58362. enumerable: true,
  58363. configurable: true
  58364. });
  58365. PBRMaterial.prototype.needAlphaBlending = function () {
  58366. if (this.linkRefractionWithTransparency) {
  58367. return false;
  58368. }
  58369. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  58370. };
  58371. PBRMaterial.prototype.needAlphaTesting = function () {
  58372. if (this.linkRefractionWithTransparency) {
  58373. return false;
  58374. }
  58375. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  58376. };
  58377. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  58378. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  58379. };
  58380. PBRMaterial.prototype.getAlphaTestTexture = function () {
  58381. return this.albedoTexture;
  58382. };
  58383. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58384. if (!mesh) {
  58385. return true;
  58386. }
  58387. if (this._defines.INSTANCES !== useInstances) {
  58388. return false;
  58389. }
  58390. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  58391. return true;
  58392. }
  58393. return false;
  58394. };
  58395. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  58396. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  58397. };
  58398. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  58399. if (!useScalarInLinear) {
  58400. color.toLinearSpaceToRef(ref);
  58401. }
  58402. else {
  58403. ref.r = color.r;
  58404. ref.g = color.g;
  58405. ref.b = color.b;
  58406. }
  58407. };
  58408. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  58409. var lightIndex = 0;
  58410. var depthValuesAlreadySet = false;
  58411. for (var index = 0; index < scene.lights.length; index++) {
  58412. var light = scene.lights[index];
  58413. if (!light.isEnabled()) {
  58414. continue;
  58415. }
  58416. if (!light.canAffectMesh(mesh)) {
  58417. continue;
  58418. }
  58419. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  58420. // GAMMA CORRECTION.
  58421. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  58422. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  58423. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  58424. if (defines["SPECULARTERM"]) {
  58425. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  58426. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  58427. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  58428. }
  58429. // Shadows
  58430. if (scene.shadowsEnabled) {
  58431. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  58432. }
  58433. lightIndex++;
  58434. if (lightIndex === maxSimultaneousLights)
  58435. break;
  58436. }
  58437. };
  58438. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  58439. if (this.isFrozen) {
  58440. if (this._wasPreviouslyReady) {
  58441. return true;
  58442. }
  58443. }
  58444. var scene = this.getScene();
  58445. var engine = scene.getEngine();
  58446. var needNormals = false;
  58447. var needUVs = false;
  58448. this._defines.reset();
  58449. if (scene.lightsEnabled && !this.disableLighting) {
  58450. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  58451. }
  58452. if (!this.checkReadyOnEveryCall) {
  58453. if (this._renderId === scene.getRenderId()) {
  58454. if (this._checkCache(scene, mesh, useInstances)) {
  58455. return true;
  58456. }
  58457. }
  58458. }
  58459. if (scene.texturesEnabled) {
  58460. if (scene.getEngine().getCaps().textureLOD) {
  58461. this._defines.LODBASEDMICROSFURACE = true;
  58462. }
  58463. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58464. if (!this.albedoTexture.isReady()) {
  58465. return false;
  58466. }
  58467. else {
  58468. needUVs = true;
  58469. this._defines.ALBEDO = true;
  58470. }
  58471. }
  58472. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58473. if (!this.ambientTexture.isReady()) {
  58474. return false;
  58475. }
  58476. else {
  58477. needUVs = true;
  58478. this._defines.AMBIENT = true;
  58479. }
  58480. }
  58481. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58482. if (!this.opacityTexture.isReady()) {
  58483. return false;
  58484. }
  58485. else {
  58486. needUVs = true;
  58487. this._defines.OPACITY = true;
  58488. if (this.opacityTexture.getAlphaFromRGB) {
  58489. this._defines.OPACITYRGB = true;
  58490. }
  58491. }
  58492. }
  58493. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58494. if (!this.reflectionTexture.isReady()) {
  58495. return false;
  58496. }
  58497. else {
  58498. needNormals = true;
  58499. this._defines.REFLECTION = true;
  58500. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  58501. this._defines.INVERTCUBICMAP = true;
  58502. }
  58503. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  58504. switch (this.reflectionTexture.coordinatesMode) {
  58505. case BABYLON.Texture.CUBIC_MODE:
  58506. case BABYLON.Texture.INVCUBIC_MODE:
  58507. this._defines.REFLECTIONMAP_CUBIC = true;
  58508. break;
  58509. case BABYLON.Texture.EXPLICIT_MODE:
  58510. this._defines.REFLECTIONMAP_EXPLICIT = true;
  58511. break;
  58512. case BABYLON.Texture.PLANAR_MODE:
  58513. this._defines.REFLECTIONMAP_PLANAR = true;
  58514. break;
  58515. case BABYLON.Texture.PROJECTION_MODE:
  58516. this._defines.REFLECTIONMAP_PROJECTION = true;
  58517. break;
  58518. case BABYLON.Texture.SKYBOX_MODE:
  58519. this._defines.REFLECTIONMAP_SKYBOX = true;
  58520. break;
  58521. case BABYLON.Texture.SPHERICAL_MODE:
  58522. this._defines.REFLECTIONMAP_SPHERICAL = true;
  58523. break;
  58524. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  58525. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  58526. break;
  58527. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  58528. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  58529. break;
  58530. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  58531. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  58532. break;
  58533. }
  58534. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  58535. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  58536. needNormals = true;
  58537. if (this.reflectionTexture.isPMREM) {
  58538. this._defines.USEPMREMREFLECTION = true;
  58539. }
  58540. }
  58541. }
  58542. }
  58543. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58544. if (!this.lightmapTexture.isReady()) {
  58545. return false;
  58546. }
  58547. else {
  58548. needUVs = true;
  58549. this._defines.LIGHTMAP = true;
  58550. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  58551. }
  58552. }
  58553. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58554. if (!this.emissiveTexture.isReady()) {
  58555. return false;
  58556. }
  58557. else {
  58558. needUVs = true;
  58559. this._defines.EMISSIVE = true;
  58560. }
  58561. }
  58562. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58563. if (this.metallicTexture) {
  58564. if (!this.metallicTexture.isReady()) {
  58565. return false;
  58566. }
  58567. else {
  58568. needUVs = true;
  58569. this._defines.METALLICWORKFLOW = true;
  58570. this._defines.METALLICROUGHNESSMAP = true;
  58571. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  58572. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  58573. }
  58574. }
  58575. else if (this.reflectivityTexture) {
  58576. if (!this.reflectivityTexture.isReady()) {
  58577. return false;
  58578. }
  58579. else {
  58580. needUVs = true;
  58581. this._defines.REFLECTIVITY = true;
  58582. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  58583. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  58584. }
  58585. }
  58586. }
  58587. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58588. if (!this.bumpTexture.isReady()) {
  58589. return false;
  58590. }
  58591. else {
  58592. needUVs = true;
  58593. this._defines.BUMP = true;
  58594. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58595. this._defines.PARALLAX = true;
  58596. if (this.useParallaxOcclusion) {
  58597. this._defines.PARALLAXOCCLUSION = true;
  58598. }
  58599. }
  58600. if (this.invertNormalMapX) {
  58601. this._defines.INVERTNORMALMAPX = true;
  58602. }
  58603. if (this.invertNormalMapY) {
  58604. this._defines.INVERTNORMALMAPY = true;
  58605. }
  58606. if (scene._mirroredCameraPosition) {
  58607. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  58608. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  58609. }
  58610. }
  58611. }
  58612. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58613. if (!this.refractionTexture.isReady()) {
  58614. return false;
  58615. }
  58616. else {
  58617. needUVs = true;
  58618. this._defines.REFRACTION = true;
  58619. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  58620. if (this.linkRefractionWithTransparency) {
  58621. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  58622. }
  58623. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  58624. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  58625. if (this.refractionTexture.isPMREM) {
  58626. this._defines.USEPMREMREFRACTION = true;
  58627. }
  58628. }
  58629. }
  58630. }
  58631. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58632. if (!this.cameraColorGradingTexture.isReady()) {
  58633. return false;
  58634. }
  58635. else {
  58636. this._defines.CAMERACOLORGRADING = true;
  58637. }
  58638. }
  58639. if (!this.backFaceCulling && this.twoSidedLighting) {
  58640. this._defines.TWOSIDEDLIGHTING = true;
  58641. }
  58642. }
  58643. // Effect
  58644. if (scene.clipPlane) {
  58645. this._defines.CLIPPLANE = true;
  58646. }
  58647. if (engine.getAlphaTesting()) {
  58648. this._defines.ALPHATEST = true;
  58649. }
  58650. if (this._shouldUseAlphaFromAlbedoTexture()) {
  58651. this._defines.ALPHAFROMALBEDO = true;
  58652. }
  58653. if (this.useEmissiveAsIllumination) {
  58654. this._defines.EMISSIVEASILLUMINATION = true;
  58655. }
  58656. if (this.linkEmissiveWithAlbedo) {
  58657. this._defines.LINKEMISSIVEWITHALBEDO = true;
  58658. }
  58659. if (this.useLogarithmicDepth) {
  58660. this._defines.LOGARITHMICDEPTH = true;
  58661. }
  58662. if (this.cameraContrast != 1) {
  58663. this._defines.CAMERACONTRAST = true;
  58664. }
  58665. if (this.cameraExposure != 1) {
  58666. this._defines.CAMERATONEMAP = true;
  58667. }
  58668. if (this.cameraColorCurves) {
  58669. this._defines.CAMERACOLORCURVES = true;
  58670. }
  58671. if (this.overloadedShadeIntensity != 1 ||
  58672. this.overloadedShadowIntensity != 1) {
  58673. this._defines.OVERLOADEDSHADOWVALUES = true;
  58674. }
  58675. if (this.overloadedMicroSurfaceIntensity > 0 ||
  58676. this.overloadedEmissiveIntensity > 0 ||
  58677. this.overloadedReflectivityIntensity > 0 ||
  58678. this.overloadedAlbedoIntensity > 0 ||
  58679. this.overloadedAmbientIntensity > 0 ||
  58680. this.overloadedReflectionIntensity > 0) {
  58681. this._defines.OVERLOADEDVALUES = true;
  58682. }
  58683. // Point size
  58684. if (this.pointsCloud || scene.forcePointsCloud) {
  58685. this._defines.POINTSIZE = true;
  58686. }
  58687. // Fog
  58688. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  58689. this._defines.FOG = true;
  58690. }
  58691. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58692. // Fresnel
  58693. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  58694. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58695. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58696. this._defines.OPACITYFRESNEL = true;
  58697. }
  58698. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58699. this._defines.EMISSIVEFRESNEL = true;
  58700. }
  58701. needNormals = true;
  58702. this._defines.FRESNEL = true;
  58703. }
  58704. }
  58705. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  58706. this._defines.SPECULAROVERALPHA = true;
  58707. }
  58708. if (this.usePhysicalLightFalloff) {
  58709. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  58710. }
  58711. if (this.useRadianceOverAlpha) {
  58712. this._defines.RADIANCEOVERALPHA = true;
  58713. }
  58714. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  58715. this._defines.METALLICWORKFLOW = true;
  58716. }
  58717. // Attribs
  58718. if (mesh) {
  58719. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  58720. this._defines.NORMAL = true;
  58721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  58722. this._defines.TANGENT = true;
  58723. }
  58724. }
  58725. if (needUVs) {
  58726. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  58727. this._defines.UV1 = true;
  58728. }
  58729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  58730. this._defines.UV2 = true;
  58731. }
  58732. }
  58733. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58734. this._defines.VERTEXCOLOR = true;
  58735. if (mesh.hasVertexAlpha) {
  58736. this._defines.VERTEXALPHA = true;
  58737. }
  58738. }
  58739. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58740. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  58741. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  58742. }
  58743. // Instances
  58744. if (useInstances) {
  58745. this._defines.INSTANCES = true;
  58746. }
  58747. }
  58748. // Get correct effect
  58749. if (!this._defines.isEqual(this._cachedDefines)) {
  58750. this._defines.cloneTo(this._cachedDefines);
  58751. scene.resetCachedMaterial();
  58752. // Fallbacks
  58753. var fallbacks = new BABYLON.EffectFallbacks();
  58754. if (this._defines.REFLECTION) {
  58755. fallbacks.addFallback(0, "REFLECTION");
  58756. }
  58757. if (this._defines.REFRACTION) {
  58758. fallbacks.addFallback(0, "REFRACTION");
  58759. }
  58760. if (this._defines.REFLECTIVITY) {
  58761. fallbacks.addFallback(0, "REFLECTIVITY");
  58762. }
  58763. if (this._defines.BUMP) {
  58764. fallbacks.addFallback(0, "BUMP");
  58765. }
  58766. if (this._defines.PARALLAX) {
  58767. fallbacks.addFallback(1, "PARALLAX");
  58768. }
  58769. if (this._defines.PARALLAXOCCLUSION) {
  58770. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  58771. }
  58772. if (this._defines.SPECULAROVERALPHA) {
  58773. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  58774. }
  58775. if (this._defines.FOG) {
  58776. fallbacks.addFallback(1, "FOG");
  58777. }
  58778. if (this._defines.POINTSIZE) {
  58779. fallbacks.addFallback(0, "POINTSIZE");
  58780. }
  58781. if (this._defines.LOGARITHMICDEPTH) {
  58782. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  58783. }
  58784. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  58785. if (this._defines.SPECULARTERM) {
  58786. fallbacks.addFallback(0, "SPECULARTERM");
  58787. }
  58788. if (this._defines.OPACITYFRESNEL) {
  58789. fallbacks.addFallback(1, "OPACITYFRESNEL");
  58790. }
  58791. if (this._defines.EMISSIVEFRESNEL) {
  58792. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  58793. }
  58794. if (this._defines.FRESNEL) {
  58795. fallbacks.addFallback(3, "FRESNEL");
  58796. }
  58797. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  58798. fallbacks.addCPUSkinningFallback(0, mesh);
  58799. }
  58800. //Attributes
  58801. var attribs = [BABYLON.VertexBuffer.PositionKind];
  58802. if (this._defines.NORMAL) {
  58803. attribs.push(BABYLON.VertexBuffer.NormalKind);
  58804. }
  58805. if (this._defines.TANGENT) {
  58806. attribs.push(BABYLON.VertexBuffer.TangentKind);
  58807. }
  58808. if (this._defines.UV1) {
  58809. attribs.push(BABYLON.VertexBuffer.UVKind);
  58810. }
  58811. if (this._defines.UV2) {
  58812. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  58813. }
  58814. if (this._defines.VERTEXCOLOR) {
  58815. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58816. }
  58817. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  58818. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  58819. // Legacy browser patch
  58820. var join = this._defines.toString();
  58821. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  58822. "vFogInfos", "vFogColor", "pointSize",
  58823. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  58824. "mBones",
  58825. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  58826. "depthValues",
  58827. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  58828. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  58829. "logarithmicDepthConstant",
  58830. "vSphericalX", "vSphericalY", "vSphericalZ",
  58831. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  58832. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  58833. "vMicrosurfaceTextureLods",
  58834. "vCameraInfos"
  58835. ];
  58836. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  58837. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  58838. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  58839. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  58840. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  58841. }
  58842. if (!this._effect.isReady()) {
  58843. return false;
  58844. }
  58845. this._renderId = scene.getRenderId();
  58846. this._wasPreviouslyReady = true;
  58847. if (mesh) {
  58848. if (!mesh._materialDefines) {
  58849. mesh._materialDefines = new PBRMaterialDefines();
  58850. }
  58851. this._defines.cloneTo(mesh._materialDefines);
  58852. }
  58853. return true;
  58854. };
  58855. PBRMaterial.prototype.unbind = function () {
  58856. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  58857. this._effect.setTexture("reflection2DSampler", null);
  58858. }
  58859. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  58860. this._effect.setTexture("refraction2DSampler", null);
  58861. }
  58862. _super.prototype.unbind.call(this);
  58863. };
  58864. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58865. this._effect.setMatrix("world", world);
  58866. };
  58867. PBRMaterial.prototype.bind = function (world, mesh) {
  58868. this._myScene = this.getScene();
  58869. // Matrices
  58870. this.bindOnlyWorldMatrix(world);
  58871. // Bones
  58872. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58873. if (this._myScene.getCachedMaterial() !== this) {
  58874. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  58875. if (BABYLON.StandardMaterial.FresnelEnabled) {
  58876. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  58877. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  58878. }
  58879. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  58880. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  58881. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  58882. }
  58883. }
  58884. // Textures
  58885. if (this._myScene.texturesEnabled) {
  58886. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  58887. this._effect.setTexture("albedoSampler", this.albedoTexture);
  58888. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  58889. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  58890. }
  58891. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  58892. this._effect.setTexture("ambientSampler", this.ambientTexture);
  58893. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  58894. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  58895. }
  58896. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  58897. this._effect.setTexture("opacitySampler", this.opacityTexture);
  58898. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  58899. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  58900. }
  58901. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  58902. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  58903. if (this.reflectionTexture.isCube) {
  58904. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  58905. }
  58906. else {
  58907. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  58908. }
  58909. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  58910. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  58911. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  58912. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  58913. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  58914. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  58915. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  58916. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  58917. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  58918. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  58919. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  58920. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  58921. }
  58922. }
  58923. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  58924. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  58925. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  58926. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  58927. }
  58928. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  58929. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  58930. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  58931. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  58932. }
  58933. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  58934. if (this.metallicTexture) {
  58935. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  58936. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  58937. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  58938. }
  58939. else if (this.reflectivityTexture) {
  58940. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  58941. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  58942. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  58943. }
  58944. }
  58945. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  58946. this._effect.setTexture("bumpSampler", this.bumpTexture);
  58947. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  58948. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  58949. }
  58950. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  58951. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  58952. var depth = 1.0;
  58953. if (this.refractionTexture.isCube) {
  58954. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  58955. }
  58956. else {
  58957. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  58958. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  58959. if (this.refractionTexture.depth) {
  58960. depth = this.refractionTexture.depth;
  58961. }
  58962. }
  58963. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  58964. }
  58965. if ((this.reflectionTexture || this.refractionTexture)) {
  58966. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  58967. }
  58968. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  58969. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  58970. }
  58971. }
  58972. // Clip plane
  58973. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  58974. // Point size
  58975. if (this.pointsCloud) {
  58976. this._effect.setFloat("pointSize", this.pointSize);
  58977. }
  58978. // Colors
  58979. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  58980. if (this._defines.METALLICWORKFLOW) {
  58981. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  58982. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  58983. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  58984. }
  58985. else {
  58986. // GAMMA CORRECTION.
  58987. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  58988. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  58989. }
  58990. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  58991. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  58992. // GAMMA CORRECTION.
  58993. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  58994. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  58995. // GAMMA CORRECTION.
  58996. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  58997. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  58998. }
  58999. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  59000. // GAMMA CORRECTION.
  59001. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  59002. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  59003. // Lights
  59004. if (this._myScene.lightsEnabled && !this.disableLighting) {
  59005. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  59006. }
  59007. // View
  59008. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  59009. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  59010. }
  59011. // Fog
  59012. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  59013. this._lightingInfos.x = this.directIntensity;
  59014. this._lightingInfos.y = this.emissiveIntensity;
  59015. this._lightingInfos.z = this.environmentIntensity;
  59016. this._lightingInfos.w = this.specularIntensity;
  59017. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  59018. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  59019. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  59020. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  59021. this._cameraInfos.x = this.cameraExposure;
  59022. this._cameraInfos.y = this.cameraContrast;
  59023. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  59024. if (this.cameraColorCurves) {
  59025. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  59026. }
  59027. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  59028. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  59029. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  59030. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  59031. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  59032. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  59033. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  59034. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  59035. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  59036. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  59037. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  59038. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  59039. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  59040. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  59041. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  59042. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  59043. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  59044. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  59045. // Log. depth
  59046. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  59047. }
  59048. _super.prototype.bind.call(this, world, mesh);
  59049. this._myScene = null;
  59050. };
  59051. PBRMaterial.prototype.getAnimatables = function () {
  59052. var results = [];
  59053. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  59054. results.push(this.albedoTexture);
  59055. }
  59056. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  59057. results.push(this.ambientTexture);
  59058. }
  59059. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  59060. results.push(this.opacityTexture);
  59061. }
  59062. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  59063. results.push(this.reflectionTexture);
  59064. }
  59065. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  59066. results.push(this.emissiveTexture);
  59067. }
  59068. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  59069. results.push(this.metallicTexture);
  59070. }
  59071. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  59072. results.push(this.reflectivityTexture);
  59073. }
  59074. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  59075. results.push(this.bumpTexture);
  59076. }
  59077. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  59078. results.push(this.lightmapTexture);
  59079. }
  59080. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  59081. results.push(this.refractionTexture);
  59082. }
  59083. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  59084. results.push(this.cameraColorGradingTexture);
  59085. }
  59086. return results;
  59087. };
  59088. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59089. if (forceDisposeTextures) {
  59090. if (this.albedoTexture) {
  59091. this.albedoTexture.dispose();
  59092. }
  59093. if (this.ambientTexture) {
  59094. this.ambientTexture.dispose();
  59095. }
  59096. if (this.opacityTexture) {
  59097. this.opacityTexture.dispose();
  59098. }
  59099. if (this.reflectionTexture) {
  59100. this.reflectionTexture.dispose();
  59101. }
  59102. if (this.emissiveTexture) {
  59103. this.emissiveTexture.dispose();
  59104. }
  59105. if (this.metallicTexture) {
  59106. this.metallicTexture.dispose();
  59107. }
  59108. if (this.reflectivityTexture) {
  59109. this.reflectivityTexture.dispose();
  59110. }
  59111. if (this.bumpTexture) {
  59112. this.bumpTexture.dispose();
  59113. }
  59114. if (this.lightmapTexture) {
  59115. this.lightmapTexture.dispose();
  59116. }
  59117. if (this.refractionTexture) {
  59118. this.refractionTexture.dispose();
  59119. }
  59120. if (this.cameraColorGradingTexture) {
  59121. this.cameraColorGradingTexture.dispose();
  59122. }
  59123. }
  59124. this._renderTargets.dispose();
  59125. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59126. };
  59127. PBRMaterial.prototype.clone = function (name) {
  59128. var _this = this;
  59129. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  59130. };
  59131. PBRMaterial.prototype.serialize = function () {
  59132. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59133. serializationObject.customType = "BABYLON.PBRMaterial";
  59134. return serializationObject;
  59135. };
  59136. // Statics
  59137. PBRMaterial.Parse = function (source, scene, rootUrl) {
  59138. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  59139. };
  59140. return PBRMaterial;
  59141. }(BABYLON.Material));
  59142. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  59143. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  59144. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  59145. PBRMaterial._scaledReflection = new BABYLON.Color3();
  59146. __decorate([
  59147. BABYLON.serialize()
  59148. ], PBRMaterial.prototype, "directIntensity", void 0);
  59149. __decorate([
  59150. BABYLON.serialize()
  59151. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  59152. __decorate([
  59153. BABYLON.serialize()
  59154. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  59155. __decorate([
  59156. BABYLON.serialize()
  59157. ], PBRMaterial.prototype, "specularIntensity", void 0);
  59158. __decorate([
  59159. BABYLON.serialize()
  59160. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  59161. __decorate([
  59162. BABYLON.serialize()
  59163. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  59164. __decorate([
  59165. BABYLON.serialize()
  59166. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  59167. __decorate([
  59168. BABYLON.serialize()
  59169. ], PBRMaterial.prototype, "cameraExposure", void 0);
  59170. __decorate([
  59171. BABYLON.serialize()
  59172. ], PBRMaterial.prototype, "cameraContrast", void 0);
  59173. __decorate([
  59174. BABYLON.serializeAsTexture()
  59175. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  59176. __decorate([
  59177. BABYLON.serializeAsColorCurves()
  59178. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  59179. __decorate([
  59180. BABYLON.serializeAsColor3()
  59181. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  59182. __decorate([
  59183. BABYLON.serialize()
  59184. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  59185. __decorate([
  59186. BABYLON.serializeAsColor3()
  59187. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  59188. __decorate([
  59189. BABYLON.serialize()
  59190. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  59191. __decorate([
  59192. BABYLON.serializeAsColor3()
  59193. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  59194. __decorate([
  59195. BABYLON.serialize()
  59196. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  59197. __decorate([
  59198. BABYLON.serializeAsColor3()
  59199. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  59200. __decorate([
  59201. BABYLON.serialize()
  59202. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  59203. __decorate([
  59204. BABYLON.serializeAsColor3()
  59205. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  59206. __decorate([
  59207. BABYLON.serialize()
  59208. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  59209. __decorate([
  59210. BABYLON.serialize()
  59211. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  59212. __decorate([
  59213. BABYLON.serialize()
  59214. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  59215. __decorate([
  59216. BABYLON.serializeAsTexture()
  59217. ], PBRMaterial.prototype, "albedoTexture", void 0);
  59218. __decorate([
  59219. BABYLON.serializeAsTexture()
  59220. ], PBRMaterial.prototype, "ambientTexture", void 0);
  59221. __decorate([
  59222. BABYLON.serialize()
  59223. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  59224. __decorate([
  59225. BABYLON.serializeAsTexture()
  59226. ], PBRMaterial.prototype, "opacityTexture", void 0);
  59227. __decorate([
  59228. BABYLON.serializeAsTexture()
  59229. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  59230. __decorate([
  59231. BABYLON.serializeAsTexture()
  59232. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  59233. __decorate([
  59234. BABYLON.serializeAsTexture()
  59235. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  59236. __decorate([
  59237. BABYLON.serializeAsTexture()
  59238. ], PBRMaterial.prototype, "metallicTexture", void 0);
  59239. __decorate([
  59240. BABYLON.serialize()
  59241. ], PBRMaterial.prototype, "metallic", void 0);
  59242. __decorate([
  59243. BABYLON.serialize()
  59244. ], PBRMaterial.prototype, "roughness", void 0);
  59245. __decorate([
  59246. BABYLON.serializeAsTexture()
  59247. ], PBRMaterial.prototype, "bumpTexture", void 0);
  59248. __decorate([
  59249. BABYLON.serializeAsTexture()
  59250. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  59251. __decorate([
  59252. BABYLON.serializeAsTexture()
  59253. ], PBRMaterial.prototype, "refractionTexture", void 0);
  59254. __decorate([
  59255. BABYLON.serializeAsColor3("ambient")
  59256. ], PBRMaterial.prototype, "ambientColor", void 0);
  59257. __decorate([
  59258. BABYLON.serializeAsColor3("albedo")
  59259. ], PBRMaterial.prototype, "albedoColor", void 0);
  59260. __decorate([
  59261. BABYLON.serializeAsColor3("reflectivity")
  59262. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  59263. __decorate([
  59264. BABYLON.serializeAsColor3("reflection")
  59265. ], PBRMaterial.prototype, "reflectionColor", void 0);
  59266. __decorate([
  59267. BABYLON.serializeAsColor3("emissive")
  59268. ], PBRMaterial.prototype, "emissiveColor", void 0);
  59269. __decorate([
  59270. BABYLON.serialize()
  59271. ], PBRMaterial.prototype, "microSurface", void 0);
  59272. __decorate([
  59273. BABYLON.serialize()
  59274. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  59275. __decorate([
  59276. BABYLON.serialize()
  59277. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  59278. __decorate([
  59279. BABYLON.serializeAsFresnelParameters()
  59280. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  59281. __decorate([
  59282. BABYLON.serializeAsFresnelParameters()
  59283. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  59284. __decorate([
  59285. BABYLON.serialize()
  59286. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  59287. __decorate([
  59288. BABYLON.serialize()
  59289. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  59290. __decorate([
  59291. BABYLON.serialize()
  59292. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  59293. __decorate([
  59294. BABYLON.serialize()
  59295. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  59296. __decorate([
  59297. BABYLON.serialize()
  59298. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  59299. __decorate([
  59300. BABYLON.serialize()
  59301. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  59302. __decorate([
  59303. BABYLON.serialize()
  59304. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  59305. __decorate([
  59306. BABYLON.serialize()
  59307. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  59308. __decorate([
  59309. BABYLON.serialize()
  59310. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  59311. __decorate([
  59312. BABYLON.serialize()
  59313. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  59314. __decorate([
  59315. BABYLON.serialize()
  59316. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  59317. __decorate([
  59318. BABYLON.serialize()
  59319. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  59320. __decorate([
  59321. BABYLON.serialize()
  59322. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  59323. __decorate([
  59324. BABYLON.serialize()
  59325. ], PBRMaterial.prototype, "useParallax", void 0);
  59326. __decorate([
  59327. BABYLON.serialize()
  59328. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  59329. __decorate([
  59330. BABYLON.serialize()
  59331. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  59332. __decorate([
  59333. BABYLON.serialize()
  59334. ], PBRMaterial.prototype, "disableLighting", void 0);
  59335. __decorate([
  59336. BABYLON.serialize()
  59337. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  59338. __decorate([
  59339. BABYLON.serialize()
  59340. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  59341. __decorate([
  59342. BABYLON.serialize()
  59343. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  59344. __decorate([
  59345. BABYLON.serialize()
  59346. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  59347. __decorate([
  59348. BABYLON.serialize()
  59349. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  59350. BABYLON.PBRMaterial = PBRMaterial;
  59351. })(BABYLON || (BABYLON = {}));
  59352. //# sourceMappingURL=babylon.pbrMaterial.js.map
  59353. var BABYLON;
  59354. (function (BABYLON) {
  59355. var DebugLayer = (function () {
  59356. function DebugLayer(scene) {
  59357. this._scene = scene;
  59358. }
  59359. /** Creates the inspector window. */
  59360. DebugLayer.prototype._createInspector = function (config) {
  59361. if (config === void 0) { config = {}; }
  59362. var popup = config.popup || false;
  59363. var initialTab = config.initialTab || 0;
  59364. var parentElement = config.parentElement || null;
  59365. if (!this._inspector) {
  59366. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  59367. } // else nothing to do,; instance is already existing
  59368. };
  59369. DebugLayer.prototype.isVisible = function () {
  59370. if (!this._inspector) {
  59371. return false;
  59372. }
  59373. return true;
  59374. };
  59375. DebugLayer.prototype.hide = function () {
  59376. if (this._inspector) {
  59377. this._inspector.dispose();
  59378. this._inspector = null;
  59379. }
  59380. };
  59381. DebugLayer.prototype.show = function (config) {
  59382. if (config === void 0) { config = {}; }
  59383. if (typeof INSPECTOR == 'undefined') {
  59384. // Load inspector and add it to the DOM
  59385. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  59386. }
  59387. else {
  59388. // Otherwise creates the inspector
  59389. this._createInspector(config);
  59390. }
  59391. };
  59392. return DebugLayer;
  59393. }());
  59394. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  59395. BABYLON.DebugLayer = DebugLayer;
  59396. })(BABYLON || (BABYLON = {}));
  59397. //# sourceMappingURL=babylon.debugLayer.js.map
  59398. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  59399. var BABYLON;
  59400. (function (BABYLON) {
  59401. var StandardRenderingPipeline = (function (_super) {
  59402. __extends(StandardRenderingPipeline, _super);
  59403. /**
  59404. * @constructor
  59405. * @param {string} name - The rendering pipeline name
  59406. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59407. * @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)
  59408. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  59409. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59410. */
  59411. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  59412. if (originalPostProcess === void 0) { originalPostProcess = null; }
  59413. var _this = _super.call(this, scene.getEngine(), name) || this;
  59414. _this.downSampleX4PostProcess = null;
  59415. _this.brightPassPostProcess = null;
  59416. _this.gaussianBlurHPostProcesses = [];
  59417. _this.gaussianBlurVPostProcesses = [];
  59418. _this.textureAdderPostProcess = null;
  59419. _this.textureAdderFinalPostProcess = null;
  59420. _this.lensFlareFinalPostProcess = null;
  59421. _this.lensFlarePostProcess = null;
  59422. _this.lensFlareComposePostProcess = null;
  59423. _this.depthOfFieldPostProcess = null;
  59424. // Values
  59425. _this.brightThreshold = 1.0;
  59426. _this.blurWidth = 2.0;
  59427. _this.horizontalBlur = false;
  59428. _this.gaussianCoefficient = 0.25;
  59429. _this.gaussianMean = 1.0;
  59430. _this.gaussianStandardDeviation = 1.0;
  59431. _this.exposure = 1.0;
  59432. _this.lensTexture = null;
  59433. _this.lensColorTexture = null;
  59434. _this.lensFlareStrength = 20.0;
  59435. _this.lensFlareGhostDispersal = 1.4;
  59436. _this.lensFlareHaloWidth = 0.7;
  59437. _this.lensFlareDistortionStrength = 16.0;
  59438. _this.lensStarTexture = null;
  59439. _this.lensFlareDirtTexture = null;
  59440. _this.depthOfFieldDistance = 10.0;
  59441. _this.depthOfFieldBlurWidth = 2.0;
  59442. // IAnimatable
  59443. _this.animations = [];
  59444. _this._depthRenderer = null;
  59445. _this._currentDepthOfFieldSource = null;
  59446. // Getters and setters
  59447. _this._depthOfFieldEnabled = true;
  59448. _this._lensFlareEnabled = true;
  59449. // Initialize
  59450. _this._scene = scene;
  59451. // Create pass post-processe
  59452. if (!originalPostProcess) {
  59453. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  59454. }
  59455. else {
  59456. _this.originalPostProcess = originalPostProcess;
  59457. }
  59458. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  59459. // Create down sample X4 post-process
  59460. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  59461. // Create bright pass post-process
  59462. _this._createBrightPassPostProcess(scene, ratio / 2);
  59463. // Create gaussian blur post-processes (down sampling blurs)
  59464. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  59465. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  59466. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  59467. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  59468. // Create texture adder post-process
  59469. _this._createTextureAdderPostProcess(scene, ratio);
  59470. // Create depth-of-field source post-process
  59471. _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);
  59472. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  59473. // Create lens flare post-process
  59474. _this._createLensFlarePostProcess(scene, ratio);
  59475. // Create depth-of-field source post-process post lens-flare and disable it now
  59476. _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);
  59477. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  59478. // Create gaussian blur used by depth-of-field
  59479. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  59480. // Create depth-of-field post-process
  59481. _this._createDepthOfFieldPostProcess(scene, ratio);
  59482. // Finish
  59483. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59484. if (cameras !== null) {
  59485. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59486. }
  59487. // Deactivate
  59488. _this.LensFlareEnabled = false;
  59489. _this.DepthOfFieldEnabled = false;
  59490. return _this;
  59491. }
  59492. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  59493. get: function () {
  59494. return this._depthOfFieldEnabled;
  59495. },
  59496. set: function (enabled) {
  59497. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  59498. if (enabled && !this._depthOfFieldEnabled) {
  59499. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59500. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59501. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59502. this._depthRenderer = this._scene.enableDepthRenderer();
  59503. }
  59504. else if (!enabled && this._depthOfFieldEnabled) {
  59505. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59506. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59507. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  59508. }
  59509. this._depthOfFieldEnabled = enabled;
  59510. },
  59511. enumerable: true,
  59512. configurable: true
  59513. });
  59514. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  59515. get: function () {
  59516. return this._lensFlareEnabled;
  59517. },
  59518. set: function (enabled) {
  59519. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  59520. if (enabled && !this._lensFlareEnabled) {
  59521. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59522. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59523. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59524. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59525. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59526. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  59527. }
  59528. else if (!enabled && this._lensFlareEnabled) {
  59529. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  59530. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  59531. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  59532. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  59533. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  59534. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  59535. }
  59536. this._lensFlareEnabled = enabled;
  59537. },
  59538. enumerable: true,
  59539. configurable: true
  59540. });
  59541. // Sets depth-of-field save post-process
  59542. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  59543. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  59544. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._scene.cameras);
  59545. switch (name) {
  59546. case "HDRBaseDepthOfFieldSource":
  59547. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  59548. break;
  59549. case "HDRPostLensFlareDepthOfFieldSource":
  59550. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  59551. break;
  59552. default: break;
  59553. }
  59554. };
  59555. // Down Sample X4 Post-Processs
  59556. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  59557. var _this = this;
  59558. var downSampleX4Offsets = new Array(32);
  59559. 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);
  59560. this.downSampleX4PostProcess.onApply = function (effect) {
  59561. var id = 0;
  59562. for (var i = -2; i < 2; i++) {
  59563. for (var j = -2; j < 2; j++) {
  59564. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  59565. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  59566. id += 2;
  59567. }
  59568. }
  59569. effect.setArray2("dsOffsets", downSampleX4Offsets);
  59570. };
  59571. // Add to pipeline
  59572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  59573. };
  59574. // Brightpass Post-Process
  59575. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  59576. var _this = this;
  59577. var brightOffsets = new Array(8);
  59578. 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);
  59579. this.brightPassPostProcess.onApply = function (effect) {
  59580. var sU = (1.0 / _this.brightPassPostProcess.width);
  59581. var sV = (1.0 / _this.brightPassPostProcess.height);
  59582. brightOffsets[0] = -0.5 * sU;
  59583. brightOffsets[1] = 0.5 * sV;
  59584. brightOffsets[2] = 0.5 * sU;
  59585. brightOffsets[3] = 0.5 * sV;
  59586. brightOffsets[4] = -0.5 * sU;
  59587. brightOffsets[5] = -0.5 * sV;
  59588. brightOffsets[6] = 0.5 * sU;
  59589. brightOffsets[7] = -0.5 * sV;
  59590. effect.setArray2("dsOffsets", brightOffsets);
  59591. effect.setFloat("brightThreshold", _this.brightThreshold);
  59592. };
  59593. // Add to pipeline
  59594. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  59595. };
  59596. // Create gaussian blur H&V post-processes
  59597. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  59598. var _this = this;
  59599. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  59600. var blurOffsets = new Array(9);
  59601. var blurWeights = new Array(9);
  59602. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  59603. var callback = function (height) {
  59604. return function (effect) {
  59605. // Weights
  59606. var x = 0.0;
  59607. for (var i = 0; i < 9; i++) {
  59608. x = (i - 4.0) / 4.0;
  59609. blurWeights[i] =
  59610. _this.gaussianCoefficient
  59611. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  59612. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  59613. }
  59614. var lastOutputDimensions = {
  59615. width: scene.getEngine().getRenderWidth(),
  59616. height: scene.getEngine().getRenderHeight()
  59617. };
  59618. for (var i = 0; i < 9; i++) {
  59619. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  59620. blurOffsets[i] = value;
  59621. }
  59622. effect.setArray("blurOffsets", blurOffsets);
  59623. effect.setArray("blurWeights", blurWeights);
  59624. if (height) {
  59625. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  59626. }
  59627. else {
  59628. effect.setFloat("blurWidth", _this[blurWidthKey]);
  59629. }
  59630. };
  59631. };
  59632. // Create horizontal gaussian blur post-processes
  59633. 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);
  59634. gaussianBlurHPostProcess.onApply = callback(false);
  59635. // Create vertical gaussian blur post-process
  59636. 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);
  59637. gaussianBlurVPostProcess.onApply = callback(true);
  59638. // Add to pipeline
  59639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  59640. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  59641. // Finish
  59642. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  59643. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  59644. };
  59645. // Create texture adder post-process
  59646. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  59647. var _this = this;
  59648. 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);
  59649. this.textureAdderPostProcess.onApply = function (effect) {
  59650. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  59651. effect.setTexture("lensSampler", _this.lensTexture);
  59652. effect.setFloat("exposure", _this.exposure);
  59653. };
  59654. // Add to pipeline
  59655. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  59656. };
  59657. // Create lens flare post-process
  59658. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59659. var _this = this;
  59660. 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);
  59661. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59662. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  59663. 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);
  59664. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59665. var resolution = new BABYLON.Vector2(0, 0);
  59666. // Lens flare
  59667. this.lensFlarePostProcess.onApply = function (effect) {
  59668. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  59669. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59670. effect.setFloat("strength", _this.lensFlareStrength);
  59671. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59672. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59673. // Shift
  59674. resolution.x = _this.lensFlarePostProcess.width;
  59675. resolution.y = _this.lensFlarePostProcess.height;
  59676. effect.setVector2("resolution", resolution);
  59677. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59678. };
  59679. // Compose
  59680. 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);
  59681. 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);
  59682. this.lensFlareComposePostProcess.onApply = function (effect) {
  59683. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  59684. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59685. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59686. // Lens start rotation matrix
  59687. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59688. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59689. 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));
  59690. camRot *= 4.0;
  59691. 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);
  59692. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59693. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59694. };
  59695. };
  59696. // Create depth-of-field post-process
  59697. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59698. var _this = this;
  59699. 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);
  59700. this.depthOfFieldPostProcess.onApply = function (effect) {
  59701. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59702. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  59703. effect.setFloat("distance", _this.depthOfFieldDistance);
  59704. };
  59705. // Add to pipeline
  59706. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59707. };
  59708. // Dispose
  59709. StandardRenderingPipeline.prototype.dispose = function () {
  59710. for (var i = 0; i < this._scene.cameras.length; i++) {
  59711. var camera = this._scene.cameras[i];
  59712. this.originalPostProcess.dispose(camera);
  59713. this.downSampleX4PostProcess.dispose(camera);
  59714. this.brightPassPostProcess.dispose(camera);
  59715. this.textureAdderPostProcess.dispose(camera);
  59716. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  59717. this.gaussianBlurHPostProcesses[j].dispose(camera);
  59718. }
  59719. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  59720. this.gaussianBlurVPostProcesses[j].dispose(camera);
  59721. }
  59722. this.textureAdderFinalPostProcess.dispose(camera);
  59723. this.lensFlarePostProcess.dispose(camera);
  59724. this.lensFlareComposePostProcess.dispose(camera);
  59725. this.depthOfFieldPostProcess.dispose(camera);
  59726. }
  59727. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59728. _super.prototype.dispose.call(this);
  59729. };
  59730. // Serialize rendering pipeline
  59731. StandardRenderingPipeline.prototype.serialize = function () {
  59732. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59733. serializationObject.customType = "StandardRenderingPipeline";
  59734. return serializationObject;
  59735. };
  59736. // Parse serialized pipeline
  59737. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59738. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59739. };
  59740. return StandardRenderingPipeline;
  59741. }(BABYLON.PostProcessRenderPipeline));
  59742. __decorate([
  59743. BABYLON.serialize()
  59744. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59745. __decorate([
  59746. BABYLON.serialize()
  59747. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59748. __decorate([
  59749. BABYLON.serialize()
  59750. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59751. __decorate([
  59752. BABYLON.serialize()
  59753. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  59754. __decorate([
  59755. BABYLON.serialize()
  59756. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  59757. __decorate([
  59758. BABYLON.serialize()
  59759. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  59760. __decorate([
  59761. BABYLON.serialize()
  59762. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59763. __decorate([
  59764. BABYLON.serializeAsTexture("lensTexture")
  59765. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59766. __decorate([
  59767. BABYLON.serializeAsTexture("lensColorTexture")
  59768. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59769. __decorate([
  59770. BABYLON.serialize()
  59771. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59772. __decorate([
  59773. BABYLON.serialize()
  59774. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59775. __decorate([
  59776. BABYLON.serialize()
  59777. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59778. __decorate([
  59779. BABYLON.serialize()
  59780. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59781. __decorate([
  59782. BABYLON.serializeAsTexture("lensStarTexture")
  59783. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59784. __decorate([
  59785. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59786. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59787. __decorate([
  59788. BABYLON.serialize()
  59789. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59790. __decorate([
  59791. BABYLON.serialize()
  59792. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59793. __decorate([
  59794. BABYLON.serialize()
  59795. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59796. __decorate([
  59797. BABYLON.serialize()
  59798. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59799. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59800. })(BABYLON || (BABYLON = {}));
  59801. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59802. 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#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#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#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#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}"};
  59803. 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)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nconst float shadowStrength=80.;\nfloat visibility=1.0-clamp(exp(shadowStrength*shadowPixelDepth)*shadowMapSample-darkness,0.,1.);\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,visibility,vOverloadedShadowIntensity.x);\n#else\nreturn visibility;\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,min(1.0,visibility+darkness),vOverloadedShadowIntensity.x);\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n\n\n\n\n\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  59804. 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={}));";
  59805. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  59806. module.exports = BABYLON;
  59807. };