babylon.max.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214
  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 Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2 set from the passed index element of the passed array.
  845. */
  846. Vector2.FromArray = function (array, offset) {
  847. if (offset === void 0) { offset = 0; }
  848. return new Vector2(array[offset], array[offset + 1]);
  849. };
  850. /**
  851. * Sets "result" from the passed index element of the passed array.
  852. */
  853. Vector2.FromArrayToRef = function (array, offset, result) {
  854. result.x = array[offset];
  855. result.y = array[offset + 1];
  856. };
  857. /**
  858. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  859. */
  860. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  861. var squared = amount * amount;
  862. var cubed = amount * squared;
  863. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  864. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  865. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  866. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  867. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  868. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  869. return new Vector2(x, y);
  870. };
  871. /**
  872. * 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".
  873. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  874. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  875. */
  876. Vector2.Clamp = function (value, min, max) {
  877. var x = value.x;
  878. x = (x > max.x) ? max.x : x;
  879. x = (x < min.x) ? min.x : x;
  880. var y = value.y;
  881. y = (y > max.y) ? max.y : y;
  882. y = (y < min.y) ? min.y : y;
  883. return new Vector2(x, y);
  884. };
  885. /**
  886. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  887. */
  888. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  889. var squared = amount * amount;
  890. var cubed = amount * squared;
  891. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  892. var part2 = (-2.0 * cubed) + (3.0 * squared);
  893. var part3 = (cubed - (2.0 * squared)) + amount;
  894. var part4 = cubed - squared;
  895. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  896. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  897. return new Vector2(x, y);
  898. };
  899. /**
  900. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  901. */
  902. Vector2.Lerp = function (start, end, amount) {
  903. var x = start.x + ((end.x - start.x) * amount);
  904. var y = start.y + ((end.y - start.y) * amount);
  905. return new Vector2(x, y);
  906. };
  907. /**
  908. * Returns the dot product (float) of the vector "left" and the vector "right".
  909. */
  910. Vector2.Dot = function (left, right) {
  911. return left.x * right.x + left.y * right.y;
  912. };
  913. /**
  914. * Returns a new Vector2 equal to the normalized passed vector.
  915. */
  916. Vector2.Normalize = function (vector) {
  917. var newVector = vector.clone();
  918. newVector.normalize();
  919. return newVector;
  920. };
  921. /**
  922. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  923. */
  924. Vector2.Minimize = function (left, right) {
  925. var x = (left.x < right.x) ? left.x : right.x;
  926. var y = (left.y < right.y) ? left.y : right.y;
  927. return new Vector2(x, y);
  928. };
  929. /**
  930. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  931. */
  932. Vector2.Maximize = function (left, right) {
  933. var x = (left.x > right.x) ? left.x : right.x;
  934. var y = (left.y > right.y) ? left.y : right.y;
  935. return new Vector2(x, y);
  936. };
  937. /**
  938. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  939. */
  940. Vector2.Transform = function (vector, transformation) {
  941. var r = Vector2.Zero();
  942. Vector2.TransformToRef(vector, transformation, r);
  943. return r;
  944. };
  945. /**
  946. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  947. */
  948. Vector2.TransformToRef = function (vector, transformation, result) {
  949. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  950. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  951. result.x = x;
  952. result.y = y;
  953. };
  954. /**
  955. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  956. */
  957. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  958. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  959. var sign = a < 0 ? -1 : 1;
  960. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  961. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  962. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  963. };
  964. /**
  965. * Returns the distance (float) between the vectors "value1" and "value2".
  966. */
  967. Vector2.Distance = function (value1, value2) {
  968. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  969. };
  970. /**
  971. * Returns the squared distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.DistanceSquared = function (value1, value2) {
  974. var x = value1.x - value2.x;
  975. var y = value1.y - value2.y;
  976. return (x * x) + (y * y);
  977. };
  978. /**
  979. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  980. */
  981. Vector2.Center = function (value1, value2) {
  982. var center = value1.add(value2);
  983. center.scaleInPlace(0.5);
  984. return center;
  985. };
  986. /**
  987. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  988. */
  989. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  990. var l2 = Vector2.DistanceSquared(segA, segB);
  991. if (l2 === 0.0) {
  992. return Vector2.Distance(p, segA);
  993. }
  994. var v = segB.subtract(segA);
  995. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  996. var proj = segA.add(v.multiplyByFloats(t, t));
  997. return Vector2.Distance(p, proj);
  998. };
  999. return Vector2;
  1000. }());
  1001. BABYLON.Vector2 = Vector2;
  1002. var Vector3 = (function () {
  1003. /**
  1004. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1005. * A Vector3 is the main object used in 3D geometry.
  1006. * It can represent etiher the coordinates of a point the space, either a direction.
  1007. */
  1008. function Vector3(x, y, z) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. }
  1013. /**
  1014. * Returns a string with the Vector3 coordinates.
  1015. */
  1016. Vector3.prototype.toString = function () {
  1017. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Vector3"
  1021. */
  1022. Vector3.prototype.getClassName = function () {
  1023. return "Vector3";
  1024. };
  1025. /**
  1026. * Returns the Vector hash code.
  1027. */
  1028. Vector3.prototype.getHashCode = function () {
  1029. var hash = this.x || 0;
  1030. hash = (hash * 397) ^ (this.y || 0);
  1031. hash = (hash * 397) ^ (this.z || 0);
  1032. return hash;
  1033. };
  1034. // Operators
  1035. /**
  1036. * Returns a new array with three elements : the coordinates the Vector3.
  1037. */
  1038. Vector3.prototype.asArray = function () {
  1039. var result = [];
  1040. this.toArray(result, 0);
  1041. return result;
  1042. };
  1043. /**
  1044. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1045. * Returns the Vector3.
  1046. */
  1047. Vector3.prototype.toArray = function (array, index) {
  1048. if (index === void 0) { index = 0; }
  1049. array[index] = this.x;
  1050. array[index + 1] = this.y;
  1051. array[index + 2] = this.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1056. */
  1057. Vector3.prototype.toQuaternion = function () {
  1058. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1059. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1060. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1061. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1062. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1063. var cosy = Math.cos(this.y * 0.5);
  1064. var siny = Math.sin(this.y * 0.5);
  1065. result.x = coszMinusx * siny;
  1066. result.y = -sinzMinusx * siny;
  1067. result.z = sinxPlusz * cosy;
  1068. result.w = cosxPlusz * cosy;
  1069. return result;
  1070. };
  1071. /**
  1072. * Adds the passed vector to the current Vector3.
  1073. * Returns the updated Vector3.
  1074. */
  1075. Vector3.prototype.addInPlace = function (otherVector) {
  1076. this.x += otherVector.x;
  1077. this.y += otherVector.y;
  1078. this.z += otherVector.z;
  1079. return this;
  1080. };
  1081. /**
  1082. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1083. */
  1084. Vector3.prototype.add = function (otherVector) {
  1085. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1086. };
  1087. /**
  1088. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1089. * Returns the current Vector3.
  1090. */
  1091. Vector3.prototype.addToRef = function (otherVector, result) {
  1092. result.x = this.x + otherVector.x;
  1093. result.y = this.y + otherVector.y;
  1094. result.z = this.z + otherVector.z;
  1095. return this;
  1096. };
  1097. /**
  1098. * Subtract the passed vector from the current Vector3.
  1099. * Returns the updated Vector3.
  1100. */
  1101. Vector3.prototype.subtractInPlace = function (otherVector) {
  1102. this.x -= otherVector.x;
  1103. this.y -= otherVector.y;
  1104. this.z -= otherVector.z;
  1105. return this;
  1106. };
  1107. /**
  1108. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1109. */
  1110. Vector3.prototype.subtract = function (otherVector) {
  1111. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1112. };
  1113. /**
  1114. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1115. * Returns the current Vector3.
  1116. */
  1117. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1118. result.x = this.x - otherVector.x;
  1119. result.y = this.y - otherVector.y;
  1120. result.z = this.z - otherVector.z;
  1121. return this;
  1122. };
  1123. /**
  1124. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1125. */
  1126. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1127. return new Vector3(this.x - x, this.y - y, this.z - z);
  1128. };
  1129. /**
  1130. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1131. * Returns the current Vector3.
  1132. */
  1133. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1134. result.x = this.x - x;
  1135. result.y = this.y - y;
  1136. result.z = this.z - z;
  1137. return this;
  1138. };
  1139. /**
  1140. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1141. */
  1142. Vector3.prototype.negate = function () {
  1143. return new Vector3(-this.x, -this.y, -this.z);
  1144. };
  1145. /**
  1146. * Multiplies the Vector3 coordinates by the float "scale".
  1147. * Returns the updated Vector3.
  1148. */
  1149. Vector3.prototype.scaleInPlace = function (scale) {
  1150. this.x *= scale;
  1151. this.y *= scale;
  1152. this.z *= scale;
  1153. return this;
  1154. };
  1155. /**
  1156. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1157. */
  1158. Vector3.prototype.scale = function (scale) {
  1159. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1160. };
  1161. /**
  1162. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1163. * Returns the current Vector3.
  1164. */
  1165. Vector3.prototype.scaleToRef = function (scale, result) {
  1166. result.x = this.x * scale;
  1167. result.y = this.y * scale;
  1168. result.z = this.z * scale;
  1169. return this;
  1170. };
  1171. /**
  1172. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1173. */
  1174. Vector3.prototype.equals = function (otherVector) {
  1175. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1179. */
  1180. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1181. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1182. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1183. };
  1184. /**
  1185. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1186. */
  1187. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1188. return this.x === x && this.y === y && this.z === z;
  1189. };
  1190. /**
  1191. * Muliplies the current Vector3 coordinates by the passed ones.
  1192. * Returns the updated Vector3.
  1193. */
  1194. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1195. this.x *= otherVector.x;
  1196. this.y *= otherVector.y;
  1197. this.z *= otherVector.z;
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1202. */
  1203. Vector3.prototype.multiply = function (otherVector) {
  1204. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1205. };
  1206. /**
  1207. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1208. * Returns the current Vector3.
  1209. */
  1210. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1211. result.x = this.x * otherVector.x;
  1212. result.y = this.y * otherVector.y;
  1213. result.z = this.z * otherVector.z;
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1218. */
  1219. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1220. return new Vector3(this.x * x, this.y * y, this.z * z);
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1224. */
  1225. Vector3.prototype.divide = function (otherVector) {
  1226. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1227. };
  1228. /**
  1229. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1230. * Returns the current Vector3.
  1231. */
  1232. Vector3.prototype.divideToRef = function (otherVector, result) {
  1233. result.x = this.x / otherVector.x;
  1234. result.y = this.y / otherVector.y;
  1235. result.z = this.z / otherVector.z;
  1236. return this;
  1237. };
  1238. /**
  1239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1240. * Returns the updated Vector3.
  1241. */
  1242. Vector3.prototype.MinimizeInPlace = function (other) {
  1243. if (other.x < this.x)
  1244. this.x = other.x;
  1245. if (other.y < this.y)
  1246. this.y = other.y;
  1247. if (other.z < this.z)
  1248. this.z = other.z;
  1249. return this;
  1250. };
  1251. /**
  1252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.MaximizeInPlace = function (other) {
  1256. if (other.x > this.x)
  1257. this.x = other.x;
  1258. if (other.y > this.y)
  1259. this.y = other.y;
  1260. if (other.z > this.z)
  1261. this.z = other.z;
  1262. return this;
  1263. };
  1264. // Properties
  1265. /**
  1266. * Returns the length of the Vector3 (float).
  1267. */
  1268. Vector3.prototype.length = function () {
  1269. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1270. };
  1271. /**
  1272. * Returns the squared length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.lengthSquared = function () {
  1275. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. // Methods
  1278. /**
  1279. * Normalize the current Vector3.
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.normalize = function () {
  1283. var len = this.length();
  1284. if (len === 0 || len === 1.0)
  1285. return this;
  1286. var num = 1.0 / len;
  1287. this.x *= num;
  1288. this.y *= num;
  1289. this.z *= num;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3 copied from the current Vector3.
  1294. */
  1295. Vector3.prototype.clone = function () {
  1296. return new Vector3(this.x, this.y, this.z);
  1297. };
  1298. /**
  1299. * Copies the passed vector coordinates to the current Vector3 ones.
  1300. * Returns the updated Vector3.
  1301. */
  1302. Vector3.prototype.copyFrom = function (source) {
  1303. this.x = source.x;
  1304. this.y = source.y;
  1305. this.z = source.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Copies the passed floats to the current Vector3 coordinates.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1313. this.x = x;
  1314. this.y = y;
  1315. this.z = z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Copies the passed floats to the current Vector3 coordinates.
  1320. * Returns the updated Vector3.
  1321. */
  1322. Vector3.prototype.set = function (x, y, z) {
  1323. return this.copyFromFloats(x, y, z);
  1324. };
  1325. // Statics
  1326. /**
  1327. *
  1328. */
  1329. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1330. var d0 = Vector3.Dot(vector0, axis) - size;
  1331. var d1 = Vector3.Dot(vector1, axis) - size;
  1332. var s = d0 / (d0 - d1);
  1333. return s;
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set from the index "offset" of the passed array.
  1337. */
  1338. Vector3.FromArray = function (array, offset) {
  1339. if (!offset) {
  1340. offset = 0;
  1341. }
  1342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1343. };
  1344. /**
  1345. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1346. * This function is deprecated. Use FromArray instead.
  1347. */
  1348. Vector3.FromFloatArray = function (array, offset) {
  1349. return Vector3.FromArray(array, offset);
  1350. };
  1351. /**
  1352. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1353. */
  1354. Vector3.FromArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. };
  1359. /**
  1360. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1361. * This function is deprecated. Use FromArrayToRef instead.
  1362. */
  1363. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1364. return Vector3.FromArrayToRef(array, offset, result);
  1365. };
  1366. /**
  1367. * Sets the passed vector "result" with the passed floats.
  1368. */
  1369. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1370. result.x = x;
  1371. result.y = y;
  1372. result.z = z;
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1376. */
  1377. Vector3.Zero = function () {
  1378. return new Vector3(0.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1382. */
  1383. Vector3.Up = function () {
  1384. return new Vector3(0.0, 1.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1388. */
  1389. Vector3.Forward = function () {
  1390. return new Vector3(0.0, 0.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1394. */
  1395. Vector3.Right = function () {
  1396. return new Vector3(1.0, 0.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1400. */
  1401. Vector3.Left = function () {
  1402. return new Vector3(-1.0, 0.0, 0.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1406. * This method computes tranformed coordinates only, not transformed direction vectors.
  1407. */
  1408. Vector3.TransformCoordinates = function (vector, transformation) {
  1409. var result = Vector3.Zero();
  1410. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1411. return result;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1418. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1419. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1420. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1421. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1422. result.x = x / w;
  1423. result.y = y / w;
  1424. result.z = z / w;
  1425. };
  1426. /**
  1427. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1428. * This method computes tranformed coordinates only, not transformed direction vectors.
  1429. */
  1430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1435. result.x = rx / rw;
  1436. result.y = ry / rw;
  1437. result.z = rz / rw;
  1438. };
  1439. /**
  1440. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1441. * This methods computes transformed normalized direction vectors only.
  1442. */
  1443. Vector3.TransformNormal = function (vector, transformation) {
  1444. var result = Vector3.Zero();
  1445. Vector3.TransformNormalToRef(vector, transformation, result);
  1446. return result;
  1447. };
  1448. /**
  1449. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1450. * This methods computes transformed normalized direction vectors only.
  1451. */
  1452. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1456. result.x = x;
  1457. result.y = y;
  1458. result.z = z;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1465. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1466. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1467. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1468. };
  1469. /**
  1470. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1471. */
  1472. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1473. var squared = amount * amount;
  1474. var cubed = amount * squared;
  1475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1481. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1482. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1483. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1484. return new Vector3(x, y, z);
  1485. };
  1486. /**
  1487. * 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".
  1488. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1489. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1490. */
  1491. Vector3.Clamp = function (value, min, max) {
  1492. var x = value.x;
  1493. x = (x > max.x) ? max.x : x;
  1494. x = (x < min.x) ? min.x : x;
  1495. var y = value.y;
  1496. y = (y > max.y) ? max.y : y;
  1497. y = (y < min.y) ? min.y : y;
  1498. var z = value.z;
  1499. z = (z > max.z) ? max.z : z;
  1500. z = (z < min.z) ? min.z : z;
  1501. return new Vector3(x, y, z);
  1502. };
  1503. /**
  1504. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1505. */
  1506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1507. var squared = amount * amount;
  1508. var cubed = amount * squared;
  1509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1511. var part3 = (cubed - (2.0 * squared)) + amount;
  1512. var part4 = cubed - squared;
  1513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1516. return new Vector3(x, y, z);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1520. */
  1521. Vector3.Lerp = function (start, end, amount) {
  1522. var result = new Vector3(0, 0, 0);
  1523. Vector3.LerpToRef(start, end, amount, result);
  1524. return result;
  1525. };
  1526. /**
  1527. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1528. */
  1529. Vector3.LerpToRef = function (start, end, amount, result) {
  1530. result.x = start.x + ((end.x - start.x) * amount);
  1531. result.y = start.y + ((end.y - start.y) * amount);
  1532. result.z = start.z + ((end.z - start.z) * amount);
  1533. };
  1534. /**
  1535. * Returns the dot product (float) between the vectors "left" and "right".
  1536. */
  1537. Vector3.Dot = function (left, right) {
  1538. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1539. };
  1540. /**
  1541. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1542. * The cross product is then orthogonal to both "left" and "right".
  1543. */
  1544. Vector3.Cross = function (left, right) {
  1545. var result = Vector3.Zero();
  1546. Vector3.CrossToRef(left, right, result);
  1547. return result;
  1548. };
  1549. /**
  1550. * Sets the passed vector "result" with the cross product of "left" and "right".
  1551. * The cross product is then orthogonal to both "left" and "right".
  1552. */
  1553. Vector3.CrossToRef = function (left, right, result) {
  1554. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1555. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1556. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1557. result.copyFrom(MathTmp.Vector3[0]);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 as the normalization of the passed vector.
  1561. */
  1562. Vector3.Normalize = function (vector) {
  1563. var result = Vector3.Zero();
  1564. Vector3.NormalizeToRef(vector, result);
  1565. return result;
  1566. };
  1567. /**
  1568. * Sets the passed vector "result" with the normalization of the passed first vector.
  1569. */
  1570. Vector3.NormalizeToRef = function (vector, result) {
  1571. result.copyFrom(vector);
  1572. result.normalize();
  1573. };
  1574. Vector3.Project = function (vector, world, transform, viewport) {
  1575. var cw = viewport.width;
  1576. var ch = viewport.height;
  1577. var cx = viewport.x;
  1578. var cy = viewport.y;
  1579. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1580. 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);
  1581. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1582. world.multiplyToRef(transform, matrix);
  1583. matrix.multiplyToRef(viewportMatrix, matrix);
  1584. return Vector3.TransformCoordinates(vector, matrix);
  1585. };
  1586. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1587. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1588. world.multiplyToRef(transform, matrix);
  1589. matrix.invert();
  1590. source.x = source.x / viewportWidth * 2 - 1;
  1591. source.y = -(source.y / viewportHeight * 2 - 1);
  1592. var vector = Vector3.TransformCoordinates(source, matrix);
  1593. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1594. if (MathTools.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1600. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1601. world.multiplyToRef(view, matrix);
  1602. matrix.multiplyToRef(projection, matrix);
  1603. matrix.invert();
  1604. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1605. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1607. if (MathTools.WithinEpsilon(num, 1.0)) {
  1608. vector = vector.scale(1.0 / num);
  1609. }
  1610. return vector;
  1611. };
  1612. Vector3.Minimize = function (left, right) {
  1613. var min = left.clone();
  1614. min.MinimizeInPlace(right);
  1615. return min;
  1616. };
  1617. Vector3.Maximize = function (left, right) {
  1618. var max = left.clone();
  1619. max.MaximizeInPlace(right);
  1620. return max;
  1621. };
  1622. /**
  1623. * Returns the distance (float) between the vectors "value1" and "value2".
  1624. */
  1625. Vector3.Distance = function (value1, value2) {
  1626. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1627. };
  1628. /**
  1629. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1630. */
  1631. Vector3.DistanceSquared = function (value1, value2) {
  1632. var x = value1.x - value2.x;
  1633. var y = value1.y - value2.y;
  1634. var z = value1.z - value2.z;
  1635. return (x * x) + (y * y) + (z * z);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 located at the center between "value1" and "value2".
  1639. */
  1640. Vector3.Center = function (value1, value2) {
  1641. var center = value1.add(value2);
  1642. center.scaleInPlace(0.5);
  1643. return center;
  1644. };
  1645. /**
  1646. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1647. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1648. * to something in order to rotate it from its local system to the given target system.
  1649. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1650. * Returns a new Vector3.
  1651. */
  1652. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1653. var rotation = Vector3.Zero();
  1654. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1655. return rotation;
  1656. };
  1657. /**
  1658. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1659. */
  1660. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1661. var quat = MathTmp.Quaternion[0];
  1662. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1663. quat.toEulerAnglesToRef(ref);
  1664. };
  1665. return Vector3;
  1666. }());
  1667. BABYLON.Vector3 = Vector3;
  1668. //Vector4 class created for EulerAngle class conversion to Quaternion
  1669. var Vector4 = (function () {
  1670. /**
  1671. * Creates a Vector4 object from the passed floats.
  1672. */
  1673. function Vector4(x, y, z, w) {
  1674. this.x = x;
  1675. this.y = y;
  1676. this.z = z;
  1677. this.w = w;
  1678. }
  1679. /**
  1680. * Returns the string with the Vector4 coordinates.
  1681. */
  1682. Vector4.prototype.toString = function () {
  1683. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1684. };
  1685. /**
  1686. * Returns the string "Vector4".
  1687. */
  1688. Vector4.prototype.getClassName = function () {
  1689. return "Vector4";
  1690. };
  1691. /**
  1692. * Returns the Vector4 hash code.
  1693. */
  1694. Vector4.prototype.getHashCode = function () {
  1695. var hash = this.x || 0;
  1696. hash = (hash * 397) ^ (this.y || 0);
  1697. hash = (hash * 397) ^ (this.z || 0);
  1698. hash = (hash * 397) ^ (this.w || 0);
  1699. return hash;
  1700. };
  1701. // Operators
  1702. /**
  1703. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1704. */
  1705. Vector4.prototype.asArray = function () {
  1706. var result = [];
  1707. this.toArray(result, 0);
  1708. return result;
  1709. };
  1710. /**
  1711. * Populates the passed array from the passed index with the Vector4 coordinates.
  1712. * Returns the Vector4.
  1713. */
  1714. Vector4.prototype.toArray = function (array, index) {
  1715. if (index === undefined) {
  1716. index = 0;
  1717. }
  1718. array[index] = this.x;
  1719. array[index + 1] = this.y;
  1720. array[index + 2] = this.z;
  1721. array[index + 3] = this.w;
  1722. return this;
  1723. };
  1724. /**
  1725. * Adds the passed vector to the current Vector4.
  1726. * Returns the updated Vector4.
  1727. */
  1728. Vector4.prototype.addInPlace = function (otherVector) {
  1729. this.x += otherVector.x;
  1730. this.y += otherVector.y;
  1731. this.z += otherVector.z;
  1732. this.w += otherVector.w;
  1733. return this;
  1734. };
  1735. /**
  1736. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1737. */
  1738. Vector4.prototype.add = function (otherVector) {
  1739. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1740. };
  1741. /**
  1742. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1743. * Returns the current Vector4.
  1744. */
  1745. Vector4.prototype.addToRef = function (otherVector, result) {
  1746. result.x = this.x + otherVector.x;
  1747. result.y = this.y + otherVector.y;
  1748. result.z = this.z + otherVector.z;
  1749. result.w = this.w + otherVector.w;
  1750. return this;
  1751. };
  1752. /**
  1753. * Subtract in place the passed vector from the current Vector4.
  1754. * Returns the updated Vector4.
  1755. */
  1756. Vector4.prototype.subtractInPlace = function (otherVector) {
  1757. this.x -= otherVector.x;
  1758. this.y -= otherVector.y;
  1759. this.z -= otherVector.z;
  1760. this.w -= otherVector.w;
  1761. return this;
  1762. };
  1763. /**
  1764. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1765. */
  1766. Vector4.prototype.subtract = function (otherVector) {
  1767. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1768. };
  1769. /**
  1770. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1771. * Returns the current Vector4.
  1772. */
  1773. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1774. result.x = this.x - otherVector.x;
  1775. result.y = this.y - otherVector.y;
  1776. result.z = this.z - otherVector.z;
  1777. result.w = this.w - otherVector.w;
  1778. return this;
  1779. };
  1780. /**
  1781. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1782. */
  1783. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1784. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1785. };
  1786. /**
  1787. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1788. * Returns the current Vector4.
  1789. */
  1790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1791. result.x = this.x - x;
  1792. result.y = this.y - y;
  1793. result.z = this.z - z;
  1794. result.w = this.w - w;
  1795. return this;
  1796. };
  1797. /**
  1798. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1799. */
  1800. Vector4.prototype.negate = function () {
  1801. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1802. };
  1803. /**
  1804. * Multiplies the current Vector4 coordinates by scale (float).
  1805. * Returns the updated Vector4.
  1806. */
  1807. Vector4.prototype.scaleInPlace = function (scale) {
  1808. this.x *= scale;
  1809. this.y *= scale;
  1810. this.z *= scale;
  1811. this.w *= scale;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1816. */
  1817. Vector4.prototype.scale = function (scale) {
  1818. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1819. };
  1820. /**
  1821. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1822. * Returns the current Vector4.
  1823. */
  1824. Vector4.prototype.scaleToRef = function (scale, result) {
  1825. result.x = this.x * scale;
  1826. result.y = this.y * scale;
  1827. result.z = this.z * scale;
  1828. result.w = this.w * scale;
  1829. return this;
  1830. };
  1831. /**
  1832. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1833. */
  1834. Vector4.prototype.equals = function (otherVector) {
  1835. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1836. };
  1837. /**
  1838. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1839. */
  1840. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1841. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1842. return otherVector
  1843. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1844. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1845. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1846. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1847. };
  1848. /**
  1849. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1850. */
  1851. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1852. return this.x === x && this.y === y && this.z === z && this.w === w;
  1853. };
  1854. /**
  1855. * Multiplies in place the current Vector4 by the passed one.
  1856. * Returns the updated Vector4.
  1857. */
  1858. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1859. this.x *= otherVector.x;
  1860. this.y *= otherVector.y;
  1861. this.z *= otherVector.z;
  1862. this.w *= otherVector.w;
  1863. return this;
  1864. };
  1865. /**
  1866. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1867. */
  1868. Vector4.prototype.multiply = function (otherVector) {
  1869. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1870. };
  1871. /**
  1872. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1873. * Returns the current Vector4.
  1874. */
  1875. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1876. result.x = this.x * otherVector.x;
  1877. result.y = this.y * otherVector.y;
  1878. result.z = this.z * otherVector.z;
  1879. result.w = this.w * otherVector.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1884. */
  1885. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1886. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1887. };
  1888. /**
  1889. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1890. */
  1891. Vector4.prototype.divide = function (otherVector) {
  1892. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1893. };
  1894. /**
  1895. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1896. * Returns the current Vector4.
  1897. */
  1898. Vector4.prototype.divideToRef = function (otherVector, result) {
  1899. result.x = this.x / otherVector.x;
  1900. result.y = this.y / otherVector.y;
  1901. result.z = this.z / otherVector.z;
  1902. result.w = this.w / otherVector.w;
  1903. return this;
  1904. };
  1905. /**
  1906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1907. */
  1908. Vector4.prototype.MinimizeInPlace = function (other) {
  1909. if (other.x < this.x)
  1910. this.x = other.x;
  1911. if (other.y < this.y)
  1912. this.y = other.y;
  1913. if (other.z < this.z)
  1914. this.z = other.z;
  1915. if (other.w < this.w)
  1916. this.w = other.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1921. */
  1922. Vector4.prototype.MaximizeInPlace = function (other) {
  1923. if (other.x > this.x)
  1924. this.x = other.x;
  1925. if (other.y > this.y)
  1926. this.y = other.y;
  1927. if (other.z > this.z)
  1928. this.z = other.z;
  1929. if (other.w > this.w)
  1930. this.w = other.w;
  1931. return this;
  1932. };
  1933. // Properties
  1934. /**
  1935. * Returns the Vector4 length (float).
  1936. */
  1937. Vector4.prototype.length = function () {
  1938. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1939. };
  1940. /**
  1941. * Returns the Vector4 squared length (float).
  1942. */
  1943. Vector4.prototype.lengthSquared = function () {
  1944. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1945. };
  1946. // Methods
  1947. /**
  1948. * Normalizes in place the Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.normalize = function () {
  1952. var len = this.length();
  1953. if (len === 0)
  1954. return this;
  1955. var num = 1.0 / len;
  1956. this.x *= num;
  1957. this.y *= num;
  1958. this.z *= num;
  1959. this.w *= num;
  1960. return this;
  1961. };
  1962. /**
  1963. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1964. */
  1965. Vector4.prototype.toVector3 = function () {
  1966. return new Vector3(this.x, this.y, this.z);
  1967. };
  1968. /**
  1969. * Returns a new Vector4 copied from the current one.
  1970. */
  1971. Vector4.prototype.clone = function () {
  1972. return new Vector4(this.x, this.y, this.z, this.w);
  1973. };
  1974. /**
  1975. * Updates the current Vector4 with the passed one coordinates.
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.copyFrom = function (source) {
  1979. this.x = source.x;
  1980. this.y = source.y;
  1981. this.z = source.z;
  1982. this.w = source.w;
  1983. return this;
  1984. };
  1985. /**
  1986. * Updates the current Vector4 coordinates with the passed floats.
  1987. * Returns the updated Vector4.
  1988. */
  1989. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1990. this.x = x;
  1991. this.y = y;
  1992. this.z = z;
  1993. this.w = w;
  1994. return this;
  1995. };
  1996. /**
  1997. * Updates the current Vector4 coordinates with the passed floats.
  1998. * Returns the updated Vector4.
  1999. */
  2000. Vector4.prototype.set = function (x, y, z, w) {
  2001. return this.copyFromFloats(x, y, z, w);
  2002. };
  2003. // Statics
  2004. /**
  2005. * Returns a new Vector4 set from the starting index of the passed array.
  2006. */
  2007. Vector4.FromArray = function (array, offset) {
  2008. if (!offset) {
  2009. offset = 0;
  2010. }
  2011. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2012. };
  2013. /**
  2014. * Updates the passed vector "result" from the starting index of the passed array.
  2015. */
  2016. Vector4.FromArrayToRef = function (array, offset, result) {
  2017. result.x = array[offset];
  2018. result.y = array[offset + 1];
  2019. result.z = array[offset + 2];
  2020. result.w = array[offset + 3];
  2021. };
  2022. /**
  2023. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2024. */
  2025. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2026. Vector4.FromArrayToRef(array, offset, result);
  2027. };
  2028. /**
  2029. * Updates the passed vector "result" coordinates from the passed floats.
  2030. */
  2031. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2032. result.x = x;
  2033. result.y = y;
  2034. result.z = z;
  2035. result.w = w;
  2036. };
  2037. /**
  2038. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2039. */
  2040. Vector4.Zero = function () {
  2041. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2042. };
  2043. /**
  2044. * Returns a new normalized Vector4 from the passed one.
  2045. */
  2046. Vector4.Normalize = function (vector) {
  2047. var result = Vector4.Zero();
  2048. Vector4.NormalizeToRef(vector, result);
  2049. return result;
  2050. };
  2051. /**
  2052. * Updates the passed vector "result" from the normalization of the passed one.
  2053. */
  2054. Vector4.NormalizeToRef = function (vector, result) {
  2055. result.copyFrom(vector);
  2056. result.normalize();
  2057. };
  2058. Vector4.Minimize = function (left, right) {
  2059. var min = left.clone();
  2060. min.MinimizeInPlace(right);
  2061. return min;
  2062. };
  2063. Vector4.Maximize = function (left, right) {
  2064. var max = left.clone();
  2065. max.MaximizeInPlace(right);
  2066. return max;
  2067. };
  2068. /**
  2069. * Returns the distance (float) between the vectors "value1" and "value2".
  2070. */
  2071. Vector4.Distance = function (value1, value2) {
  2072. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2073. };
  2074. /**
  2075. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2076. */
  2077. Vector4.DistanceSquared = function (value1, value2) {
  2078. var x = value1.x - value2.x;
  2079. var y = value1.y - value2.y;
  2080. var z = value1.z - value2.z;
  2081. var w = value1.w - value2.w;
  2082. return (x * x) + (y * y) + (z * z) + (w * w);
  2083. };
  2084. /**
  2085. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2086. */
  2087. Vector4.Center = function (value1, value2) {
  2088. var center = value1.add(value2);
  2089. center.scaleInPlace(0.5);
  2090. return center;
  2091. };
  2092. /**
  2093. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2094. * This methods computes transformed normalized direction vectors only.
  2095. */
  2096. Vector4.TransformNormal = function (vector, transformation) {
  2097. var result = Vector4.Zero();
  2098. Vector4.TransformNormalToRef(vector, transformation, result);
  2099. return result;
  2100. };
  2101. /**
  2102. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2103. * This methods computes transformed normalized direction vectors only.
  2104. */
  2105. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2106. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2107. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2108. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2109. result.x = x;
  2110. result.y = y;
  2111. result.z = z;
  2112. result.w = vector.w;
  2113. };
  2114. /**
  2115. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2116. * This methods computes transformed normalized direction vectors only.
  2117. */
  2118. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2119. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2120. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2121. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2122. result.w = w;
  2123. };
  2124. return Vector4;
  2125. }());
  2126. BABYLON.Vector4 = Vector4;
  2127. var Size = (function () {
  2128. /**
  2129. * Creates a Size object from the passed width and height (floats).
  2130. */
  2131. function Size(width, height) {
  2132. this.width = width;
  2133. this.height = height;
  2134. }
  2135. // Returns a string with the Size width and height.
  2136. Size.prototype.toString = function () {
  2137. return "{W: " + this.width + ", H: " + this.height + "}";
  2138. };
  2139. /**
  2140. * Returns the string "Size"
  2141. */
  2142. Size.prototype.getClassName = function () {
  2143. return "Size";
  2144. };
  2145. /**
  2146. * Returns the Size hash code.
  2147. */
  2148. Size.prototype.getHashCode = function () {
  2149. var hash = this.width || 0;
  2150. hash = (hash * 397) ^ (this.height || 0);
  2151. return hash;
  2152. };
  2153. /**
  2154. * Updates the current size from the passed one.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.copyFrom = function (src) {
  2158. this.width = src.width;
  2159. this.height = src.height;
  2160. };
  2161. /**
  2162. * Updates in place the current Size from the passed floats.
  2163. * Returns the updated Size.
  2164. */
  2165. Size.prototype.copyFromFloats = function (width, height) {
  2166. this.width = width;
  2167. this.height = height;
  2168. return this;
  2169. };
  2170. /**
  2171. * Updates in place the current Size from the passed floats.
  2172. * Returns the updated Size.
  2173. */
  2174. Size.prototype.set = function (width, height) {
  2175. return this.copyFromFloats(width, height);
  2176. };
  2177. /**
  2178. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2179. */
  2180. Size.prototype.multiplyByFloats = function (w, h) {
  2181. return new Size(this.width * w, this.height * h);
  2182. };
  2183. /**
  2184. * Returns a new Size copied from the passed one.
  2185. */
  2186. Size.prototype.clone = function () {
  2187. return new Size(this.width, this.height);
  2188. };
  2189. /**
  2190. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2191. */
  2192. Size.prototype.equals = function (other) {
  2193. if (!other) {
  2194. return false;
  2195. }
  2196. return (this.width === other.width) && (this.height === other.height);
  2197. };
  2198. Object.defineProperty(Size.prototype, "surface", {
  2199. /**
  2200. * Returns the surface of the Size : width * height (float).
  2201. */
  2202. get: function () {
  2203. return this.width * this.height;
  2204. },
  2205. enumerable: true,
  2206. configurable: true
  2207. });
  2208. /**
  2209. * Returns a new Size set to (0.0, 0.0)
  2210. */
  2211. Size.Zero = function () {
  2212. return new Size(0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Size set as the addition result of the current Size and the passed one.
  2216. */
  2217. Size.prototype.add = function (otherSize) {
  2218. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2223. */
  2224. Size.prototype.subtract = function (otherSize) {
  2225. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2226. return r;
  2227. };
  2228. /**
  2229. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2230. */
  2231. Size.Lerp = function (start, end, amount) {
  2232. var w = start.width + ((end.width - start.width) * amount);
  2233. var h = start.height + ((end.height - start.height) * amount);
  2234. return new Size(w, h);
  2235. };
  2236. return Size;
  2237. }());
  2238. BABYLON.Size = Size;
  2239. var Quaternion = (function () {
  2240. /**
  2241. * Creates a new Quaternion from the passed floats.
  2242. */
  2243. function Quaternion(x, y, z, w) {
  2244. if (x === void 0) { x = 0.0; }
  2245. if (y === void 0) { y = 0.0; }
  2246. if (z === void 0) { z = 0.0; }
  2247. if (w === void 0) { w = 1.0; }
  2248. this.x = x;
  2249. this.y = y;
  2250. this.z = z;
  2251. this.w = w;
  2252. }
  2253. /**
  2254. * Returns a string with the Quaternion coordinates.
  2255. */
  2256. Quaternion.prototype.toString = function () {
  2257. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2258. };
  2259. /**
  2260. * Returns the string "Quaternion".
  2261. */
  2262. Quaternion.prototype.getClassName = function () {
  2263. return "Quaternion";
  2264. };
  2265. /**
  2266. * Returns the Quaternion hash code.
  2267. */
  2268. Quaternion.prototype.getHashCode = function () {
  2269. var hash = this.x || 0;
  2270. hash = (hash * 397) ^ (this.y || 0);
  2271. hash = (hash * 397) ^ (this.z || 0);
  2272. hash = (hash * 397) ^ (this.w || 0);
  2273. return hash;
  2274. };
  2275. /**
  2276. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2277. */
  2278. Quaternion.prototype.asArray = function () {
  2279. return [this.x, this.y, this.z, this.w];
  2280. };
  2281. /**
  2282. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2283. */
  2284. Quaternion.prototype.equals = function (otherQuaternion) {
  2285. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2286. };
  2287. /**
  2288. * Returns a new Quaternion copied from the current one.
  2289. */
  2290. Quaternion.prototype.clone = function () {
  2291. return new Quaternion(this.x, this.y, this.z, this.w);
  2292. };
  2293. /**
  2294. * Updates the current Quaternion from the passed one coordinates.
  2295. * Returns the updated Quaterion.
  2296. */
  2297. Quaternion.prototype.copyFrom = function (other) {
  2298. this.x = other.x;
  2299. this.y = other.y;
  2300. this.z = other.z;
  2301. this.w = other.w;
  2302. return this;
  2303. };
  2304. /**
  2305. * Updates the current Quaternion from the passed float coordinates.
  2306. * Returns the updated Quaterion.
  2307. */
  2308. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2309. this.x = x;
  2310. this.y = y;
  2311. this.z = z;
  2312. this.w = w;
  2313. return this;
  2314. };
  2315. /**
  2316. * Updates the current Quaternion from the passed float coordinates.
  2317. * Returns the updated Quaterion.
  2318. */
  2319. Quaternion.prototype.set = function (x, y, z, w) {
  2320. return this.copyFromFloats(x, y, z, w);
  2321. };
  2322. /**
  2323. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2324. */
  2325. Quaternion.prototype.add = function (other) {
  2326. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2327. };
  2328. /**
  2329. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2330. */
  2331. Quaternion.prototype.subtract = function (other) {
  2332. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2333. };
  2334. /**
  2335. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2336. */
  2337. Quaternion.prototype.scale = function (value) {
  2338. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2342. */
  2343. Quaternion.prototype.multiply = function (q1) {
  2344. var result = new Quaternion(0, 0, 0, 1.0);
  2345. this.multiplyToRef(q1, result);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2350. * Returns the current Quaternion.
  2351. */
  2352. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2353. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2354. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2355. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2356. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2357. result.copyFromFloats(x, y, z, w);
  2358. return this;
  2359. };
  2360. /**
  2361. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2362. * Returns the updated Quaternion.
  2363. */
  2364. Quaternion.prototype.multiplyInPlace = function (q1) {
  2365. this.multiplyToRef(q1, this);
  2366. return this;
  2367. };
  2368. /**
  2369. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2370. * Returns the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugateToRef = function (ref) {
  2373. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2374. return this;
  2375. };
  2376. /**
  2377. * Conjugates in place the current Quaternion.
  2378. * Returns the updated Quaternion.
  2379. */
  2380. Quaternion.prototype.conjugateInPlace = function () {
  2381. this.x *= -1;
  2382. this.y *= -1;
  2383. this.z *= -1;
  2384. return this;
  2385. };
  2386. /**
  2387. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2388. */
  2389. Quaternion.prototype.conjugate = function () {
  2390. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2391. return result;
  2392. };
  2393. /**
  2394. * Returns the Quaternion length (float).
  2395. */
  2396. Quaternion.prototype.length = function () {
  2397. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2398. };
  2399. /**
  2400. * Normalize in place the current Quaternion.
  2401. * Returns the updated Quaternion.
  2402. */
  2403. Quaternion.prototype.normalize = function () {
  2404. var length = 1.0 / this.length();
  2405. this.x *= length;
  2406. this.y *= length;
  2407. this.z *= length;
  2408. this.w *= length;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2413. */
  2414. Quaternion.prototype.toEulerAngles = function (order) {
  2415. if (order === void 0) { order = "YZX"; }
  2416. var result = Vector3.Zero();
  2417. this.toEulerAnglesToRef(result, order);
  2418. return result;
  2419. };
  2420. /**
  2421. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2422. * Returns the current Quaternion.
  2423. */
  2424. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2425. if (order === void 0) { order = "YZX"; }
  2426. var qz = this.z;
  2427. var qx = this.x;
  2428. var qy = this.y;
  2429. var qw = this.w;
  2430. var sqw = qw * qw;
  2431. var sqz = qz * qz;
  2432. var sqx = qx * qx;
  2433. var sqy = qy * qy;
  2434. var zAxisY = qy * qz - qx * qw;
  2435. var limit = .4999999;
  2436. if (zAxisY < -limit) {
  2437. result.y = 2 * Math.atan2(qy, qw);
  2438. result.x = Math.PI / 2;
  2439. result.z = 0;
  2440. }
  2441. else if (zAxisY > limit) {
  2442. result.y = 2 * Math.atan2(qy, qw);
  2443. result.x = -Math.PI / 2;
  2444. result.z = 0;
  2445. }
  2446. else {
  2447. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2448. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2449. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2450. }
  2451. return this;
  2452. };
  2453. /**
  2454. * Updates the passed rotation matrix with the current Quaternion values.
  2455. * Returns the current Quaternion.
  2456. */
  2457. Quaternion.prototype.toRotationMatrix = function (result) {
  2458. var xx = this.x * this.x;
  2459. var yy = this.y * this.y;
  2460. var zz = this.z * this.z;
  2461. var xy = this.x * this.y;
  2462. var zw = this.z * this.w;
  2463. var zx = this.z * this.x;
  2464. var yw = this.y * this.w;
  2465. var yz = this.y * this.z;
  2466. var xw = this.x * this.w;
  2467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2468. result.m[1] = 2.0 * (xy + zw);
  2469. result.m[2] = 2.0 * (zx - yw);
  2470. result.m[3] = 0;
  2471. result.m[4] = 2.0 * (xy - zw);
  2472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2473. result.m[6] = 2.0 * (yz + xw);
  2474. result.m[7] = 0;
  2475. result.m[8] = 2.0 * (zx + yw);
  2476. result.m[9] = 2.0 * (yz - xw);
  2477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2478. result.m[11] = 0;
  2479. result.m[12] = 0;
  2480. result.m[13] = 0;
  2481. result.m[14] = 0;
  2482. result.m[15] = 1.0;
  2483. result._markAsUpdated();
  2484. return this;
  2485. };
  2486. /**
  2487. * Updates the current Quaternion from the passed rotation matrix values.
  2488. * Returns the updated Quaternion.
  2489. */
  2490. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2491. Quaternion.FromRotationMatrixToRef(matrix, this);
  2492. return this;
  2493. };
  2494. // Statics
  2495. /**
  2496. * Returns a new Quaternion set from the passed rotation matrix values.
  2497. */
  2498. Quaternion.FromRotationMatrix = function (matrix) {
  2499. var result = new Quaternion();
  2500. Quaternion.FromRotationMatrixToRef(matrix, result);
  2501. return result;
  2502. };
  2503. /**
  2504. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2505. */
  2506. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2507. var data = matrix.m;
  2508. var m11 = data[0], m12 = data[4], m13 = data[8];
  2509. var m21 = data[1], m22 = data[5], m23 = data[9];
  2510. var m31 = data[2], m32 = data[6], m33 = data[10];
  2511. var trace = m11 + m22 + m33;
  2512. var s;
  2513. if (trace > 0) {
  2514. s = 0.5 / Math.sqrt(trace + 1.0);
  2515. result.w = 0.25 / s;
  2516. result.x = (m32 - m23) * s;
  2517. result.y = (m13 - m31) * s;
  2518. result.z = (m21 - m12) * s;
  2519. }
  2520. else if (m11 > m22 && m11 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2522. result.w = (m32 - m23) / s;
  2523. result.x = 0.25 * s;
  2524. result.y = (m12 + m21) / s;
  2525. result.z = (m13 + m31) / s;
  2526. }
  2527. else if (m22 > m33) {
  2528. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2529. result.w = (m13 - m31) / s;
  2530. result.x = (m12 + m21) / s;
  2531. result.y = 0.25 * s;
  2532. result.z = (m23 + m32) / s;
  2533. }
  2534. else {
  2535. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2536. result.w = (m21 - m12) / s;
  2537. result.x = (m13 + m31) / s;
  2538. result.y = (m23 + m32) / s;
  2539. result.z = 0.25 * s;
  2540. }
  2541. };
  2542. /**
  2543. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2544. */
  2545. Quaternion.Zero = function () {
  2546. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2547. };
  2548. /**
  2549. * Returns a new Quaternion as the inverted current Quaternion.
  2550. */
  2551. Quaternion.Inverse = function (q) {
  2552. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2553. };
  2554. /**
  2555. * Returns the identity Quaternion.
  2556. */
  2557. Quaternion.Identity = function () {
  2558. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2559. };
  2560. Quaternion.IsIdentity = function (quaternion) {
  2561. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2565. */
  2566. Quaternion.RotationAxis = function (axis, angle) {
  2567. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2568. };
  2569. /**
  2570. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2571. */
  2572. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2573. var sin = Math.sin(angle / 2);
  2574. axis.normalize();
  2575. result.w = Math.cos(angle / 2);
  2576. result.x = axis.x * sin;
  2577. result.y = axis.y * sin;
  2578. result.z = axis.z * sin;
  2579. return result;
  2580. };
  2581. /**
  2582. * Retuns a new Quaternion set from the starting index of the passed array.
  2583. */
  2584. Quaternion.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2589. };
  2590. /**
  2591. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2592. */
  2593. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2594. var q = new Quaternion();
  2595. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2596. return q;
  2597. };
  2598. /**
  2599. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2600. */
  2601. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2602. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2603. var halfRoll = roll * 0.5;
  2604. var halfPitch = pitch * 0.5;
  2605. var halfYaw = yaw * 0.5;
  2606. var sinRoll = Math.sin(halfRoll);
  2607. var cosRoll = Math.cos(halfRoll);
  2608. var sinPitch = Math.sin(halfPitch);
  2609. var cosPitch = Math.cos(halfPitch);
  2610. var sinYaw = Math.sin(halfYaw);
  2611. var cosYaw = Math.cos(halfYaw);
  2612. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2613. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2614. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2615. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2616. };
  2617. /**
  2618. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2619. */
  2620. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2621. var result = new Quaternion();
  2622. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2623. return result;
  2624. };
  2625. /**
  2626. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2627. */
  2628. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2629. // Produces a quaternion from Euler angles in the z-x-z orientation
  2630. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2631. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2632. var halfBeta = beta * 0.5;
  2633. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2634. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2635. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2636. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2637. };
  2638. /**
  2639. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2640. * cf to Vector3.RotationFromAxis() documentation.
  2641. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2642. */
  2643. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2644. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2645. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2646. return quat;
  2647. };
  2648. /**
  2649. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2650. * cf to Vector3.RotationFromAxis() documentation.
  2651. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2652. */
  2653. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2654. var rotMat = MathTmp.Matrix[0];
  2655. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2656. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2657. };
  2658. Quaternion.Slerp = function (left, right, amount) {
  2659. var result = Quaternion.Identity();
  2660. Quaternion.SlerpToRef(left, right, amount, result);
  2661. return result;
  2662. };
  2663. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2664. var num2;
  2665. var num3;
  2666. var num = amount;
  2667. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2668. var flag = false;
  2669. if (num4 < 0) {
  2670. flag = true;
  2671. num4 = -num4;
  2672. }
  2673. if (num4 > 0.999999) {
  2674. num3 = 1 - num;
  2675. num2 = flag ? -num : num;
  2676. }
  2677. else {
  2678. var num5 = Math.acos(num4);
  2679. var num6 = (1.0 / Math.sin(num5));
  2680. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2681. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2682. }
  2683. result.x = (num3 * left.x) + (num2 * right.x);
  2684. result.y = (num3 * left.y) + (num2 * right.y);
  2685. result.z = (num3 * left.z) + (num2 * right.z);
  2686. result.w = (num3 * left.w) + (num2 * right.w);
  2687. };
  2688. /**
  2689. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2690. */
  2691. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2692. var squared = amount * amount;
  2693. var cubed = amount * squared;
  2694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2696. var part3 = (cubed - (2.0 * squared)) + amount;
  2697. var part4 = cubed - squared;
  2698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2701. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2702. return new Quaternion(x, y, z, w);
  2703. };
  2704. return Quaternion;
  2705. }());
  2706. BABYLON.Quaternion = Quaternion;
  2707. var Matrix = (function () {
  2708. function Matrix() {
  2709. this.m = new Float32Array(16);
  2710. this._markAsUpdated();
  2711. }
  2712. Matrix.prototype._markAsUpdated = function () {
  2713. this.updateFlag = Matrix._updateFlagSeed++;
  2714. };
  2715. // Properties
  2716. /**
  2717. * Boolean : True is the matrix is the identity matrix
  2718. */
  2719. Matrix.prototype.isIdentity = function () {
  2720. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2721. return false;
  2722. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2726. return false;
  2727. return true;
  2728. };
  2729. /**
  2730. * Returns the matrix determinant (float).
  2731. */
  2732. Matrix.prototype.determinant = function () {
  2733. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2734. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2735. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2736. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2737. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2738. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2739. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2740. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2741. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2742. };
  2743. // Methods
  2744. /**
  2745. * Returns the matrix underlying array.
  2746. */
  2747. Matrix.prototype.toArray = function () {
  2748. return this.m;
  2749. };
  2750. /**
  2751. * Returns the matrix underlying array.
  2752. */
  2753. Matrix.prototype.asArray = function () {
  2754. return this.toArray();
  2755. };
  2756. /**
  2757. * Inverts in place the Matrix.
  2758. * Returns the Matrix inverted.
  2759. */
  2760. Matrix.prototype.invert = function () {
  2761. this.invertToRef(this);
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets all the matrix elements to zero.
  2766. * Returns the Matrix.
  2767. */
  2768. Matrix.prototype.reset = function () {
  2769. for (var index = 0; index < 16; index++) {
  2770. this.m[index] = 0.0;
  2771. }
  2772. this._markAsUpdated();
  2773. return this;
  2774. };
  2775. /**
  2776. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2777. */
  2778. Matrix.prototype.add = function (other) {
  2779. var result = new Matrix();
  2780. this.addToRef(other, result);
  2781. return result;
  2782. };
  2783. /**
  2784. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2785. * Returns the Matrix.
  2786. */
  2787. Matrix.prototype.addToRef = function (other, result) {
  2788. for (var index = 0; index < 16; index++) {
  2789. result.m[index] = this.m[index] + other.m[index];
  2790. }
  2791. result._markAsUpdated();
  2792. return this;
  2793. };
  2794. /**
  2795. * Adds in place the passed matrix to the current Matrix.
  2796. * Returns the updated Matrix.
  2797. */
  2798. Matrix.prototype.addToSelf = function (other) {
  2799. for (var index = 0; index < 16; index++) {
  2800. this.m[index] += other.m[index];
  2801. }
  2802. this._markAsUpdated();
  2803. return this;
  2804. };
  2805. /**
  2806. * Sets the passed matrix with the current inverted Matrix.
  2807. * Returns the unmodified current Matrix.
  2808. */
  2809. Matrix.prototype.invertToRef = function (other) {
  2810. var l1 = this.m[0];
  2811. var l2 = this.m[1];
  2812. var l3 = this.m[2];
  2813. var l4 = this.m[3];
  2814. var l5 = this.m[4];
  2815. var l6 = this.m[5];
  2816. var l7 = this.m[6];
  2817. var l8 = this.m[7];
  2818. var l9 = this.m[8];
  2819. var l10 = this.m[9];
  2820. var l11 = this.m[10];
  2821. var l12 = this.m[11];
  2822. var l13 = this.m[12];
  2823. var l14 = this.m[13];
  2824. var l15 = this.m[14];
  2825. var l16 = this.m[15];
  2826. var l17 = (l11 * l16) - (l12 * l15);
  2827. var l18 = (l10 * l16) - (l12 * l14);
  2828. var l19 = (l10 * l15) - (l11 * l14);
  2829. var l20 = (l9 * l16) - (l12 * l13);
  2830. var l21 = (l9 * l15) - (l11 * l13);
  2831. var l22 = (l9 * l14) - (l10 * l13);
  2832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2837. var l28 = (l7 * l16) - (l8 * l15);
  2838. var l29 = (l6 * l16) - (l8 * l14);
  2839. var l30 = (l6 * l15) - (l7 * l14);
  2840. var l31 = (l5 * l16) - (l8 * l13);
  2841. var l32 = (l5 * l15) - (l7 * l13);
  2842. var l33 = (l5 * l14) - (l6 * l13);
  2843. var l34 = (l7 * l12) - (l8 * l11);
  2844. var l35 = (l6 * l12) - (l8 * l10);
  2845. var l36 = (l6 * l11) - (l7 * l10);
  2846. var l37 = (l5 * l12) - (l8 * l9);
  2847. var l38 = (l5 * l11) - (l7 * l9);
  2848. var l39 = (l5 * l10) - (l6 * l9);
  2849. other.m[0] = l23 * l27;
  2850. other.m[4] = l24 * l27;
  2851. other.m[8] = l25 * l27;
  2852. other.m[12] = l26 * l27;
  2853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2865. other._markAsUpdated();
  2866. return this;
  2867. };
  2868. /**
  2869. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2870. * Returns the updated Matrix.
  2871. */
  2872. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2873. this.m[12] = x;
  2874. this.m[13] = y;
  2875. this.m[14] = z;
  2876. this._markAsUpdated();
  2877. return this;
  2878. };
  2879. /**
  2880. * Inserts the translation vector in the current Matrix.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.setTranslation = function (vector3) {
  2884. this.m[12] = vector3.x;
  2885. this.m[13] = vector3.y;
  2886. this.m[14] = vector3.z;
  2887. this._markAsUpdated();
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 as the extracted translation from the Matrix.
  2892. */
  2893. Matrix.prototype.getTranslation = function () {
  2894. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2895. };
  2896. /**
  2897. * Fill a Vector3 with the extracted translation from the Matrix.
  2898. */
  2899. Matrix.prototype.getTranslationToRef = function (result) {
  2900. result.x = this.m[12];
  2901. result.y = this.m[13];
  2902. result.z = this.m[14];
  2903. return this;
  2904. };
  2905. /**
  2906. * Remove rotation and scaling part from the Matrix.
  2907. * Returns the updated Matrix.
  2908. */
  2909. Matrix.prototype.removeRotationAndScaling = function () {
  2910. this.setRowFromFloats(0, 1, 0, 0, 0);
  2911. this.setRowFromFloats(1, 0, 1, 0, 0);
  2912. this.setRowFromFloats(2, 0, 0, 1, 0);
  2913. return this;
  2914. };
  2915. /**
  2916. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2917. */
  2918. Matrix.prototype.multiply = function (other) {
  2919. var result = new Matrix();
  2920. this.multiplyToRef(other, result);
  2921. return result;
  2922. };
  2923. /**
  2924. * Updates the current Matrix from the passed one values.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.copyFrom = function (other) {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = other.m[index];
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Populates the passed array from the starting index with the Matrix values.
  2936. * Returns the Matrix.
  2937. */
  2938. Matrix.prototype.copyToArray = function (array, offset) {
  2939. if (offset === void 0) { offset = 0; }
  2940. for (var index = 0; index < 16; index++) {
  2941. array[offset + index] = this.m[index];
  2942. }
  2943. return this;
  2944. };
  2945. /**
  2946. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2947. */
  2948. Matrix.prototype.multiplyToRef = function (other, result) {
  2949. this.multiplyToArray(other, result.m, 0);
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2957. var tm0 = this.m[0];
  2958. var tm1 = this.m[1];
  2959. var tm2 = this.m[2];
  2960. var tm3 = this.m[3];
  2961. var tm4 = this.m[4];
  2962. var tm5 = this.m[5];
  2963. var tm6 = this.m[6];
  2964. var tm7 = this.m[7];
  2965. var tm8 = this.m[8];
  2966. var tm9 = this.m[9];
  2967. var tm10 = this.m[10];
  2968. var tm11 = this.m[11];
  2969. var tm12 = this.m[12];
  2970. var tm13 = this.m[13];
  2971. var tm14 = this.m[14];
  2972. var tm15 = this.m[15];
  2973. var om0 = other.m[0];
  2974. var om1 = other.m[1];
  2975. var om2 = other.m[2];
  2976. var om3 = other.m[3];
  2977. var om4 = other.m[4];
  2978. var om5 = other.m[5];
  2979. var om6 = other.m[6];
  2980. var om7 = other.m[7];
  2981. var om8 = other.m[8];
  2982. var om9 = other.m[9];
  2983. var om10 = other.m[10];
  2984. var om11 = other.m[11];
  2985. var om12 = other.m[12];
  2986. var om13 = other.m[13];
  2987. var om14 = other.m[14];
  2988. var om15 = other.m[15];
  2989. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2990. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2991. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2992. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2993. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2994. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2995. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2996. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2997. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2998. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2999. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3000. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3001. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3002. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3003. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3004. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3005. return this;
  3006. };
  3007. /**
  3008. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3009. */
  3010. Matrix.prototype.equals = function (value) {
  3011. return value &&
  3012. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3013. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3014. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3015. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3016. };
  3017. /**
  3018. * Returns a new Matrix from the current Matrix.
  3019. */
  3020. Matrix.prototype.clone = function () {
  3021. 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]);
  3022. };
  3023. /**
  3024. * Returns the string "Matrix"
  3025. */
  3026. Matrix.prototype.getClassName = function () {
  3027. return "Matrix";
  3028. };
  3029. /**
  3030. * Returns the Matrix hash code.
  3031. */
  3032. Matrix.prototype.getHashCode = function () {
  3033. var hash = this.m[0] || 0;
  3034. for (var i = 1; i < 16; i++) {
  3035. hash = (hash * 397) ^ (this.m[i] || 0);
  3036. }
  3037. return hash;
  3038. };
  3039. /**
  3040. * Decomposes the current Matrix into :
  3041. * - a scale vector3 passed as a reference to update,
  3042. * - a rotation quaternion passed as a reference to update,
  3043. * - a translation vector3 passed as a reference to update.
  3044. * Returns the boolean `true`.
  3045. */
  3046. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3047. translation.x = this.m[12];
  3048. translation.y = this.m[13];
  3049. translation.z = this.m[14];
  3050. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3051. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3052. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3053. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3054. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3055. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3056. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3057. rotation.x = 0;
  3058. rotation.y = 0;
  3059. rotation.z = 0;
  3060. rotation.w = 1;
  3061. return false;
  3062. }
  3063. 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]);
  3064. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3065. return true;
  3066. };
  3067. /**
  3068. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3069. */
  3070. Matrix.prototype.getRotationMatrix = function () {
  3071. var result = Matrix.Identity();
  3072. this.getRotationMatrixToRef(result);
  3073. return result;
  3074. };
  3075. /**
  3076. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3077. * Returns the current Matrix.
  3078. */
  3079. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3080. var m = this.m;
  3081. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3082. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3083. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3084. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3085. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3086. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3087. 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);
  3088. return this;
  3089. };
  3090. // Statics
  3091. /**
  3092. * Returns a new Matrix set from the starting index of the passed array.
  3093. */
  3094. Matrix.FromArray = function (array, offset) {
  3095. var result = new Matrix();
  3096. if (!offset) {
  3097. offset = 0;
  3098. }
  3099. Matrix.FromArrayToRef(array, offset, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Sets the passed "result" matrix from the starting index of the passed array.
  3104. */
  3105. Matrix.FromArrayToRef = function (array, offset, result) {
  3106. for (var index = 0; index < 16; index++) {
  3107. result.m[index] = array[index + offset];
  3108. }
  3109. result._markAsUpdated();
  3110. };
  3111. /**
  3112. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3113. */
  3114. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3115. for (var index = 0; index < 16; index++) {
  3116. result.m[index] = array[index + offset] * scale;
  3117. }
  3118. result._markAsUpdated();
  3119. };
  3120. /**
  3121. * Sets the passed matrix "result" with the 16 passed floats.
  3122. */
  3123. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3124. result.m[0] = initialM11;
  3125. result.m[1] = initialM12;
  3126. result.m[2] = initialM13;
  3127. result.m[3] = initialM14;
  3128. result.m[4] = initialM21;
  3129. result.m[5] = initialM22;
  3130. result.m[6] = initialM23;
  3131. result.m[7] = initialM24;
  3132. result.m[8] = initialM31;
  3133. result.m[9] = initialM32;
  3134. result.m[10] = initialM33;
  3135. result.m[11] = initialM34;
  3136. result.m[12] = initialM41;
  3137. result.m[13] = initialM42;
  3138. result.m[14] = initialM43;
  3139. result.m[15] = initialM44;
  3140. result._markAsUpdated();
  3141. };
  3142. /**
  3143. * Returns the index-th row of the current matrix as a new Vector4.
  3144. */
  3145. Matrix.prototype.getRow = function (index) {
  3146. if (index < 0 || index > 3) {
  3147. return null;
  3148. }
  3149. var i = index * 4;
  3150. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3151. };
  3152. /**
  3153. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3154. * Returns the updated Matrix.
  3155. */
  3156. Matrix.prototype.setRow = function (index, row) {
  3157. if (index < 0 || index > 3) {
  3158. return this;
  3159. }
  3160. var i = index * 4;
  3161. this.m[i + 0] = row.x;
  3162. this.m[i + 1] = row.y;
  3163. this.m[i + 2] = row.z;
  3164. this.m[i + 3] = row.w;
  3165. this._markAsUpdated();
  3166. return this;
  3167. };
  3168. /**
  3169. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3170. * Returns the updated Matrix.
  3171. */
  3172. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3173. if (index < 0 || index > 3) {
  3174. return this;
  3175. }
  3176. var i = index * 4;
  3177. this.m[i + 0] = x;
  3178. this.m[i + 1] = y;
  3179. this.m[i + 2] = z;
  3180. this.m[i + 3] = w;
  3181. this._markAsUpdated();
  3182. return this;
  3183. };
  3184. /**
  3185. * Returns a new Matrix set from the 16 passed floats.
  3186. */
  3187. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3188. var result = new Matrix();
  3189. result.m[0] = initialM11;
  3190. result.m[1] = initialM12;
  3191. result.m[2] = initialM13;
  3192. result.m[3] = initialM14;
  3193. result.m[4] = initialM21;
  3194. result.m[5] = initialM22;
  3195. result.m[6] = initialM23;
  3196. result.m[7] = initialM24;
  3197. result.m[8] = initialM31;
  3198. result.m[9] = initialM32;
  3199. result.m[10] = initialM33;
  3200. result.m[11] = initialM34;
  3201. result.m[12] = initialM41;
  3202. result.m[13] = initialM42;
  3203. result.m[14] = initialM43;
  3204. result.m[15] = initialM44;
  3205. return result;
  3206. };
  3207. /**
  3208. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3209. */
  3210. Matrix.Compose = function (scale, rotation, translation) {
  3211. var result = Matrix.Identity();
  3212. Matrix.ComposeToRef(scale, rotation, translation, result);
  3213. return result;
  3214. };
  3215. /**
  3216. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3219. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3220. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3221. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3222. result.setTranslation(translation);
  3223. };
  3224. /**
  3225. * Returns a new indentity Matrix.
  3226. */
  3227. Matrix.Identity = function () {
  3228. 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);
  3229. };
  3230. /**
  3231. * Sets the passed "result" as an identity matrix.
  3232. */
  3233. Matrix.IdentityToRef = function (result) {
  3234. 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);
  3235. };
  3236. /**
  3237. * Returns a new zero Matrix.
  3238. */
  3239. Matrix.Zero = function () {
  3240. 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);
  3241. };
  3242. /**
  3243. * Returns a new rotation matrix for "angle" radians around the X axis.
  3244. */
  3245. Matrix.RotationX = function (angle) {
  3246. var result = new Matrix();
  3247. Matrix.RotationXToRef(angle, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Returns a new Matrix as the passed inverted one.
  3252. */
  3253. Matrix.Invert = function (source) {
  3254. var result = new Matrix();
  3255. source.invertToRef(result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3260. */
  3261. Matrix.RotationXToRef = function (angle, result) {
  3262. var s = Math.sin(angle);
  3263. var c = Math.cos(angle);
  3264. result.m[0] = 1.0;
  3265. result.m[15] = 1.0;
  3266. result.m[5] = c;
  3267. result.m[10] = c;
  3268. result.m[9] = -s;
  3269. result.m[6] = s;
  3270. result.m[1] = 0.0;
  3271. result.m[2] = 0.0;
  3272. result.m[3] = 0.0;
  3273. result.m[4] = 0.0;
  3274. result.m[7] = 0.0;
  3275. result.m[8] = 0.0;
  3276. result.m[11] = 0.0;
  3277. result.m[12] = 0.0;
  3278. result.m[13] = 0.0;
  3279. result.m[14] = 0.0;
  3280. result._markAsUpdated();
  3281. };
  3282. /**
  3283. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3284. */
  3285. Matrix.RotationY = function (angle) {
  3286. var result = new Matrix();
  3287. Matrix.RotationYToRef(angle, result);
  3288. return result;
  3289. };
  3290. /**
  3291. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationYToRef = function (angle, result) {
  3294. var s = Math.sin(angle);
  3295. var c = Math.cos(angle);
  3296. result.m[5] = 1.0;
  3297. result.m[15] = 1.0;
  3298. result.m[0] = c;
  3299. result.m[2] = -s;
  3300. result.m[8] = s;
  3301. result.m[10] = c;
  3302. result.m[1] = 0.0;
  3303. result.m[3] = 0.0;
  3304. result.m[4] = 0.0;
  3305. result.m[6] = 0.0;
  3306. result.m[7] = 0.0;
  3307. result.m[9] = 0.0;
  3308. result.m[11] = 0.0;
  3309. result.m[12] = 0.0;
  3310. result.m[13] = 0.0;
  3311. result.m[14] = 0.0;
  3312. result._markAsUpdated();
  3313. };
  3314. /**
  3315. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3316. */
  3317. Matrix.RotationZ = function (angle) {
  3318. var result = new Matrix();
  3319. Matrix.RotationZToRef(angle, result);
  3320. return result;
  3321. };
  3322. /**
  3323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZToRef = function (angle, result) {
  3326. var s = Math.sin(angle);
  3327. var c = Math.cos(angle);
  3328. result.m[10] = 1.0;
  3329. result.m[15] = 1.0;
  3330. result.m[0] = c;
  3331. result.m[1] = s;
  3332. result.m[4] = -s;
  3333. result.m[5] = c;
  3334. result.m[2] = 0.0;
  3335. result.m[3] = 0.0;
  3336. result.m[6] = 0.0;
  3337. result.m[7] = 0.0;
  3338. result.m[8] = 0.0;
  3339. result.m[9] = 0.0;
  3340. result.m[11] = 0.0;
  3341. result.m[12] = 0.0;
  3342. result.m[13] = 0.0;
  3343. result.m[14] = 0.0;
  3344. result._markAsUpdated();
  3345. };
  3346. /**
  3347. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3348. */
  3349. Matrix.RotationAxis = function (axis, angle) {
  3350. var result = Matrix.Zero();
  3351. Matrix.RotationAxisToRef(axis, angle, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3358. var s = Math.sin(-angle);
  3359. var c = Math.cos(-angle);
  3360. var c1 = 1 - c;
  3361. axis.normalize();
  3362. result.m[0] = (axis.x * axis.x) * c1 + c;
  3363. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3364. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3365. result.m[3] = 0.0;
  3366. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3367. result.m[5] = (axis.y * axis.y) * c1 + c;
  3368. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3369. result.m[7] = 0.0;
  3370. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3371. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3372. result.m[10] = (axis.z * axis.z) * c1 + c;
  3373. result.m[11] = 0.0;
  3374. result.m[15] = 1.0;
  3375. result._markAsUpdated();
  3376. };
  3377. /**
  3378. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3379. */
  3380. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3381. var result = new Matrix();
  3382. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3389. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3390. this._tempQuaternion.toRotationMatrix(result);
  3391. };
  3392. /**
  3393. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3394. */
  3395. Matrix.Scaling = function (x, y, z) {
  3396. var result = Matrix.Zero();
  3397. Matrix.ScalingToRef(x, y, z, result);
  3398. return result;
  3399. };
  3400. /**
  3401. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.ScalingToRef = function (x, y, z, result) {
  3404. result.m[0] = x;
  3405. result.m[1] = 0.0;
  3406. result.m[2] = 0.0;
  3407. result.m[3] = 0.0;
  3408. result.m[4] = 0.0;
  3409. result.m[5] = y;
  3410. result.m[6] = 0.0;
  3411. result.m[7] = 0.0;
  3412. result.m[8] = 0.0;
  3413. result.m[9] = 0.0;
  3414. result.m[10] = z;
  3415. result.m[11] = 0.0;
  3416. result.m[12] = 0.0;
  3417. result.m[13] = 0.0;
  3418. result.m[14] = 0.0;
  3419. result.m[15] = 1.0;
  3420. result._markAsUpdated();
  3421. };
  3422. /**
  3423. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3424. */
  3425. Matrix.Translation = function (x, y, z) {
  3426. var result = Matrix.Identity();
  3427. Matrix.TranslationToRef(x, y, z, result);
  3428. return result;
  3429. };
  3430. /**
  3431. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.TranslationToRef = function (x, y, z, result) {
  3434. 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);
  3435. };
  3436. /**
  3437. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3438. */
  3439. Matrix.Lerp = function (startValue, endValue, gradient) {
  3440. var result = Matrix.Zero();
  3441. for (var index = 0; index < 16; index++) {
  3442. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3443. }
  3444. result._markAsUpdated();
  3445. return result;
  3446. };
  3447. /**
  3448. * Returns a new Matrix whose values are computed by :
  3449. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3450. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3451. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3452. */
  3453. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3454. var startScale = new Vector3(0, 0, 0);
  3455. var startRotation = new Quaternion();
  3456. var startTranslation = new Vector3(0, 0, 0);
  3457. startValue.decompose(startScale, startRotation, startTranslation);
  3458. var endScale = new Vector3(0, 0, 0);
  3459. var endRotation = new Quaternion();
  3460. var endTranslation = new Vector3(0, 0, 0);
  3461. endValue.decompose(endScale, endRotation, endTranslation);
  3462. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3463. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3464. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3465. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3466. };
  3467. /**
  3468. * 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".
  3469. * This methods works for a Left-Handed system.
  3470. */
  3471. Matrix.LookAtLH = function (eye, target, up) {
  3472. var result = Matrix.Zero();
  3473. Matrix.LookAtLHToRef(eye, target, up, result);
  3474. return result;
  3475. };
  3476. /**
  3477. * 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".
  3478. * This methods works for a Left-Handed system.
  3479. */
  3480. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3481. // Z axis
  3482. target.subtractToRef(eye, this._zAxis);
  3483. this._zAxis.normalize();
  3484. // X axis
  3485. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3486. if (this._xAxis.lengthSquared() === 0) {
  3487. this._xAxis.x = 1.0;
  3488. }
  3489. else {
  3490. this._xAxis.normalize();
  3491. }
  3492. // Y axis
  3493. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3494. this._yAxis.normalize();
  3495. // Eye angles
  3496. var ex = -Vector3.Dot(this._xAxis, eye);
  3497. var ey = -Vector3.Dot(this._yAxis, eye);
  3498. var ez = -Vector3.Dot(this._zAxis, eye);
  3499. 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);
  3500. };
  3501. /**
  3502. * 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".
  3503. * This methods works for a Right-Handed system.
  3504. */
  3505. Matrix.LookAtRH = function (eye, target, up) {
  3506. var result = Matrix.Zero();
  3507. Matrix.LookAtRHToRef(eye, target, up, result);
  3508. return result;
  3509. };
  3510. /**
  3511. * 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".
  3512. * This methods works for a Left-Handed system.
  3513. */
  3514. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3515. // Z axis
  3516. eye.subtractToRef(target, this._zAxis);
  3517. this._zAxis.normalize();
  3518. // X axis
  3519. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3520. if (this._xAxis.lengthSquared() === 0) {
  3521. this._xAxis.x = 1.0;
  3522. }
  3523. else {
  3524. this._xAxis.normalize();
  3525. }
  3526. // Y axis
  3527. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3528. this._yAxis.normalize();
  3529. // Eye angles
  3530. var ex = -Vector3.Dot(this._xAxis, eye);
  3531. var ey = -Vector3.Dot(this._yAxis, eye);
  3532. var ez = -Vector3.Dot(this._zAxis, eye);
  3533. 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);
  3534. };
  3535. /**
  3536. * 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.
  3537. */
  3538. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3541. return matrix;
  3542. };
  3543. /**
  3544. * 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.
  3545. */
  3546. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3547. var n = znear;
  3548. var f = zfar;
  3549. var a = 2.0 / width;
  3550. var b = 2.0 / height;
  3551. var c = 2.0 / (f - n);
  3552. var d = -(f + n) / (f - n);
  3553. 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);
  3554. };
  3555. /**
  3556. * 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.
  3557. */
  3558. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3559. var matrix = Matrix.Zero();
  3560. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3561. return matrix;
  3562. };
  3563. /**
  3564. * 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.
  3565. */
  3566. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3567. var n = znear;
  3568. var f = zfar;
  3569. var a = 2.0 / (right - left);
  3570. var b = 2.0 / (top - bottom);
  3571. var c = 2.0 / (f - n);
  3572. var d = -(f + n) / (f - n);
  3573. var i0 = (left + right) / (left - right);
  3574. var i1 = (top + bottom) / (bottom - top);
  3575. 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);
  3576. };
  3577. /**
  3578. * 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.
  3579. */
  3580. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3581. var matrix = Matrix.Zero();
  3582. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3583. return matrix;
  3584. };
  3585. /**
  3586. * 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.
  3587. */
  3588. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3589. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3590. result.m[10] *= -1.0;
  3591. };
  3592. /**
  3593. * 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.
  3594. */
  3595. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3596. var matrix = Matrix.Zero();
  3597. var n = znear;
  3598. var f = zfar;
  3599. var a = 2.0 * n / width;
  3600. var b = 2.0 * n / height;
  3601. var c = (f + n) / (f - n);
  3602. var d = -2.0 * f * n / (f - n);
  3603. 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);
  3604. return matrix;
  3605. };
  3606. /**
  3607. * 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.
  3608. */
  3609. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3610. var matrix = Matrix.Zero();
  3611. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * 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.
  3616. */
  3617. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3618. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3619. var n = znear;
  3620. var f = zfar;
  3621. var t = 1.0 / (Math.tan(fov * 0.5));
  3622. var a = isVerticalFovFixed ? (t / aspect) : t;
  3623. var b = isVerticalFovFixed ? t : (t * aspect);
  3624. var c = (f + n) / (f - n);
  3625. var d = -2.0 * f * n / (f - n);
  3626. 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);
  3627. };
  3628. /**
  3629. * 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.
  3630. */
  3631. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3632. var matrix = Matrix.Zero();
  3633. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3634. return matrix;
  3635. };
  3636. /**
  3637. * 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.
  3638. */
  3639. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3640. //alternatively this could be expressed as:
  3641. // m = PerspectiveFovLHToRef
  3642. // m[10] *= -1.0;
  3643. // m[11] *= -1.0;
  3644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3645. var n = znear;
  3646. var f = zfar;
  3647. var t = 1.0 / (Math.tan(fov * 0.5));
  3648. var a = isVerticalFovFixed ? (t / aspect) : t;
  3649. var b = isVerticalFovFixed ? t : (t * aspect);
  3650. var c = -(f + n) / (f - n);
  3651. var d = -2 * f * n / (f - n);
  3652. 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);
  3653. };
  3654. /**
  3655. * 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.
  3656. */
  3657. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3658. if (rightHanded === void 0) { rightHanded = false; }
  3659. var rightHandedFactor = rightHanded ? -1 : 1;
  3660. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3661. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3662. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3663. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3664. var xScale = 2.0 / (leftTan + rightTan);
  3665. var yScale = 2.0 / (upTan + downTan);
  3666. result.m[0] = xScale;
  3667. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3668. result.m[5] = yScale;
  3669. result.m[6] = result.m[7] = 0.0;
  3670. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3671. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3672. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3673. result.m[10] = -zfar / (znear - zfar);
  3674. result.m[11] = 1.0 * rightHandedFactor;
  3675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3676. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3677. // result.m[14] = (znear * zfar) / (znear - zfar);
  3678. result._markAsUpdated();
  3679. };
  3680. /**
  3681. * Returns the final transformation matrix : world * view * projection * viewport
  3682. */
  3683. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3684. var cw = viewport.width;
  3685. var ch = viewport.height;
  3686. var cx = viewport.x;
  3687. var cy = viewport.y;
  3688. 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);
  3689. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3690. };
  3691. /**
  3692. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3693. */
  3694. Matrix.GetAsMatrix2x2 = function (matrix) {
  3695. return new Float32Array([
  3696. matrix.m[0], matrix.m[1],
  3697. matrix.m[4], matrix.m[5]
  3698. ]);
  3699. };
  3700. /**
  3701. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3702. */
  3703. Matrix.GetAsMatrix3x3 = function (matrix) {
  3704. return new Float32Array([
  3705. matrix.m[0], matrix.m[1], matrix.m[2],
  3706. matrix.m[4], matrix.m[5], matrix.m[6],
  3707. matrix.m[8], matrix.m[9], matrix.m[10]
  3708. ]);
  3709. };
  3710. /**
  3711. * Compute the transpose of the passed Matrix.
  3712. * Returns a new Matrix.
  3713. */
  3714. Matrix.Transpose = function (matrix) {
  3715. var result = new Matrix();
  3716. result.m[0] = matrix.m[0];
  3717. result.m[1] = matrix.m[4];
  3718. result.m[2] = matrix.m[8];
  3719. result.m[3] = matrix.m[12];
  3720. result.m[4] = matrix.m[1];
  3721. result.m[5] = matrix.m[5];
  3722. result.m[6] = matrix.m[9];
  3723. result.m[7] = matrix.m[13];
  3724. result.m[8] = matrix.m[2];
  3725. result.m[9] = matrix.m[6];
  3726. result.m[10] = matrix.m[10];
  3727. result.m[11] = matrix.m[14];
  3728. result.m[12] = matrix.m[3];
  3729. result.m[13] = matrix.m[7];
  3730. result.m[14] = matrix.m[11];
  3731. result.m[15] = matrix.m[15];
  3732. return result;
  3733. };
  3734. /**
  3735. * Returns a new Matrix as the reflection matrix across the passed plane.
  3736. */
  3737. Matrix.Reflection = function (plane) {
  3738. var matrix = new Matrix();
  3739. Matrix.ReflectionToRef(plane, matrix);
  3740. return matrix;
  3741. };
  3742. /**
  3743. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.ReflectionToRef = function (plane, result) {
  3746. plane.normalize();
  3747. var x = plane.normal.x;
  3748. var y = plane.normal.y;
  3749. var z = plane.normal.z;
  3750. var temp = -2 * x;
  3751. var temp2 = -2 * y;
  3752. var temp3 = -2 * z;
  3753. result.m[0] = (temp * x) + 1;
  3754. result.m[1] = temp2 * x;
  3755. result.m[2] = temp3 * x;
  3756. result.m[3] = 0.0;
  3757. result.m[4] = temp * y;
  3758. result.m[5] = (temp2 * y) + 1;
  3759. result.m[6] = temp3 * y;
  3760. result.m[7] = 0.0;
  3761. result.m[8] = temp * z;
  3762. result.m[9] = temp2 * z;
  3763. result.m[10] = (temp3 * z) + 1;
  3764. result.m[11] = 0.0;
  3765. result.m[12] = temp * plane.d;
  3766. result.m[13] = temp2 * plane.d;
  3767. result.m[14] = temp3 * plane.d;
  3768. result.m[15] = 1.0;
  3769. result._markAsUpdated();
  3770. };
  3771. /**
  3772. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3773. */
  3774. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3775. result.m[0] = xaxis.x;
  3776. result.m[1] = xaxis.y;
  3777. result.m[2] = xaxis.z;
  3778. result.m[3] = 0.0;
  3779. result.m[4] = yaxis.x;
  3780. result.m[5] = yaxis.y;
  3781. result.m[6] = yaxis.z;
  3782. result.m[7] = 0.0;
  3783. result.m[8] = zaxis.x;
  3784. result.m[9] = zaxis.y;
  3785. result.m[10] = zaxis.z;
  3786. result.m[11] = 0.0;
  3787. result.m[12] = 0.0;
  3788. result.m[13] = 0.0;
  3789. result.m[14] = 0.0;
  3790. result.m[15] = 1.0;
  3791. result._markAsUpdated();
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3795. */
  3796. Matrix.FromQuaternionToRef = function (quat, result) {
  3797. var xx = quat.x * quat.x;
  3798. var yy = quat.y * quat.y;
  3799. var zz = quat.z * quat.z;
  3800. var xy = quat.x * quat.y;
  3801. var zw = quat.z * quat.w;
  3802. var zx = quat.z * quat.x;
  3803. var yw = quat.y * quat.w;
  3804. var yz = quat.y * quat.z;
  3805. var xw = quat.x * quat.w;
  3806. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3807. result.m[1] = 2.0 * (xy + zw);
  3808. result.m[2] = 2.0 * (zx - yw);
  3809. result.m[3] = 0.0;
  3810. result.m[4] = 2.0 * (xy - zw);
  3811. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3812. result.m[6] = 2.0 * (yz + xw);
  3813. result.m[7] = 0.0;
  3814. result.m[8] = 2.0 * (zx + yw);
  3815. result.m[9] = 2.0 * (yz - xw);
  3816. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3817. result.m[11] = 0.0;
  3818. result.m[12] = 0.0;
  3819. result.m[13] = 0.0;
  3820. result.m[14] = 0.0;
  3821. result.m[15] = 1.0;
  3822. result._markAsUpdated();
  3823. };
  3824. return Matrix;
  3825. }());
  3826. Matrix._tempQuaternion = new Quaternion();
  3827. Matrix._xAxis = Vector3.Zero();
  3828. Matrix._yAxis = Vector3.Zero();
  3829. Matrix._zAxis = Vector3.Zero();
  3830. Matrix._updateFlagSeed = 0;
  3831. BABYLON.Matrix = Matrix;
  3832. var Plane = (function () {
  3833. /**
  3834. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3835. */
  3836. function Plane(a, b, c, d) {
  3837. this.normal = new Vector3(a, b, c);
  3838. this.d = d;
  3839. }
  3840. /**
  3841. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3842. */
  3843. Plane.prototype.asArray = function () {
  3844. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3845. };
  3846. // Methods
  3847. /**
  3848. * Returns a new plane copied from the current Plane.
  3849. */
  3850. Plane.prototype.clone = function () {
  3851. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3852. };
  3853. /**
  3854. * Returns the string "Plane".
  3855. */
  3856. Plane.prototype.getClassName = function () {
  3857. return "Plane";
  3858. };
  3859. /**
  3860. * Returns the Plane hash code.
  3861. */
  3862. Plane.prototype.getHashCode = function () {
  3863. var hash = this.normal.getHashCode();
  3864. hash = (hash * 397) ^ (this.d || 0);
  3865. return hash;
  3866. };
  3867. /**
  3868. * Normalize the current Plane in place.
  3869. * Returns the updated Plane.
  3870. */
  3871. Plane.prototype.normalize = function () {
  3872. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3873. var magnitude = 0.0;
  3874. if (norm !== 0) {
  3875. magnitude = 1.0 / norm;
  3876. }
  3877. this.normal.x *= magnitude;
  3878. this.normal.y *= magnitude;
  3879. this.normal.z *= magnitude;
  3880. this.d *= magnitude;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3885. */
  3886. Plane.prototype.transform = function (transformation) {
  3887. var transposedMatrix = Matrix.Transpose(transformation);
  3888. var x = this.normal.x;
  3889. var y = this.normal.y;
  3890. var z = this.normal.z;
  3891. var d = this.d;
  3892. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3893. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3894. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3895. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3896. return new Plane(normalX, normalY, normalZ, finalD);
  3897. };
  3898. /**
  3899. * Returns the dot product (float) of the point coordinates and the plane normal.
  3900. */
  3901. Plane.prototype.dotCoordinate = function (point) {
  3902. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3903. };
  3904. /**
  3905. * Updates the current Plane from the plane defined by the three passed points.
  3906. * Returns the updated Plane.
  3907. */
  3908. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3909. var x1 = point2.x - point1.x;
  3910. var y1 = point2.y - point1.y;
  3911. var z1 = point2.z - point1.z;
  3912. var x2 = point3.x - point1.x;
  3913. var y2 = point3.y - point1.y;
  3914. var z2 = point3.z - point1.z;
  3915. var yz = (y1 * z2) - (z1 * y2);
  3916. var xz = (z1 * x2) - (x1 * z2);
  3917. var xy = (x1 * y2) - (y1 * x2);
  3918. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3919. var invPyth;
  3920. if (pyth !== 0) {
  3921. invPyth = 1.0 / pyth;
  3922. }
  3923. else {
  3924. invPyth = 0.0;
  3925. }
  3926. this.normal.x = yz * invPyth;
  3927. this.normal.y = xz * invPyth;
  3928. this.normal.z = xy * invPyth;
  3929. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3930. return this;
  3931. };
  3932. /**
  3933. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3934. */
  3935. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3936. var dot = Vector3.Dot(this.normal, direction);
  3937. return (dot <= epsilon);
  3938. };
  3939. /**
  3940. * Returns the signed distance (float) from the passed point to the Plane.
  3941. */
  3942. Plane.prototype.signedDistanceTo = function (point) {
  3943. return Vector3.Dot(point, this.normal) + this.d;
  3944. };
  3945. // Statics
  3946. /**
  3947. * Returns a new Plane from the passed array.
  3948. */
  3949. Plane.FromArray = function (array) {
  3950. return new Plane(array[0], array[1], array[2], array[3]);
  3951. };
  3952. /**
  3953. * Returns a new Plane defined by the three passed points.
  3954. */
  3955. Plane.FromPoints = function (point1, point2, point3) {
  3956. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3957. result.copyFromPoints(point1, point2, point3);
  3958. return result;
  3959. };
  3960. /**
  3961. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3962. * Note : the vector "normal" is updated because normalized.
  3963. */
  3964. Plane.FromPositionAndNormal = function (origin, normal) {
  3965. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3966. normal.normalize();
  3967. result.normal = normal;
  3968. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3969. return result;
  3970. };
  3971. /**
  3972. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3973. */
  3974. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3975. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3976. return Vector3.Dot(point, normal) + d;
  3977. };
  3978. return Plane;
  3979. }());
  3980. BABYLON.Plane = Plane;
  3981. var Viewport = (function () {
  3982. /**
  3983. * Creates a Viewport object located at (x, y) and sized (width, height).
  3984. */
  3985. function Viewport(x, y, width, height) {
  3986. this.x = x;
  3987. this.y = y;
  3988. this.width = width;
  3989. this.height = height;
  3990. }
  3991. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3992. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3993. };
  3994. /**
  3995. * Returns a new Viewport copied from the current one.
  3996. */
  3997. Viewport.prototype.clone = function () {
  3998. return new Viewport(this.x, this.y, this.width, this.height);
  3999. };
  4000. return Viewport;
  4001. }());
  4002. BABYLON.Viewport = Viewport;
  4003. var Frustum = (function () {
  4004. function Frustum() {
  4005. }
  4006. /**
  4007. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4008. */
  4009. Frustum.GetPlanes = function (transform) {
  4010. var frustumPlanes = [];
  4011. for (var index = 0; index < 6; index++) {
  4012. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4013. }
  4014. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4015. return frustumPlanes;
  4016. };
  4017. /**
  4018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4019. */
  4020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4021. // Near
  4022. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4023. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4024. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4025. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4026. frustumPlanes[0].normalize();
  4027. // Far
  4028. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4029. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4030. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4031. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4032. frustumPlanes[1].normalize();
  4033. // Left
  4034. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4035. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4036. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4037. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4038. frustumPlanes[2].normalize();
  4039. // Right
  4040. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4041. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4042. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4043. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4044. frustumPlanes[3].normalize();
  4045. // Top
  4046. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4047. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4048. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4049. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4050. frustumPlanes[4].normalize();
  4051. // Bottom
  4052. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4053. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4054. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4055. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4056. frustumPlanes[5].normalize();
  4057. };
  4058. return Frustum;
  4059. }());
  4060. BABYLON.Frustum = Frustum;
  4061. var Space;
  4062. (function (Space) {
  4063. Space[Space["LOCAL"] = 0] = "LOCAL";
  4064. Space[Space["WORLD"] = 1] = "WORLD";
  4065. Space[Space["BONE"] = 2] = "BONE";
  4066. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4067. var Axis = (function () {
  4068. function Axis() {
  4069. }
  4070. return Axis;
  4071. }());
  4072. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4073. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4074. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4075. BABYLON.Axis = Axis;
  4076. ;
  4077. var BezierCurve = (function () {
  4078. function BezierCurve() {
  4079. }
  4080. /**
  4081. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4082. */
  4083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4084. // Extract X (which is equal to time here)
  4085. var f0 = 1 - 3 * x2 + 3 * x1;
  4086. var f1 = 3 * x2 - 6 * x1;
  4087. var f2 = 3 * x1;
  4088. var refinedT = t;
  4089. for (var i = 0; i < 5; i++) {
  4090. var refinedT2 = refinedT * refinedT;
  4091. var refinedT3 = refinedT2 * refinedT;
  4092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4094. refinedT -= (x - t) * slope;
  4095. refinedT = Math.min(1, Math.max(0, refinedT));
  4096. }
  4097. // Resolve cubic bezier for the given x
  4098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4099. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4100. Math.pow(refinedT, 3);
  4101. };
  4102. return BezierCurve;
  4103. }());
  4104. BABYLON.BezierCurve = BezierCurve;
  4105. var Orientation;
  4106. (function (Orientation) {
  4107. Orientation[Orientation["CW"] = 0] = "CW";
  4108. Orientation[Orientation["CCW"] = 1] = "CCW";
  4109. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4110. var Angle = (function () {
  4111. /**
  4112. * Creates an Angle object of "radians" radians (float).
  4113. */
  4114. function Angle(radians) {
  4115. var _this = this;
  4116. /**
  4117. * Returns the Angle value in degrees (float).
  4118. */
  4119. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4120. /**
  4121. * Returns the Angle value in radians (float).
  4122. */
  4123. this.radians = function () { return _this._radians; };
  4124. this._radians = radians;
  4125. if (this._radians < 0.0)
  4126. this._radians += (2.0 * Math.PI);
  4127. }
  4128. /**
  4129. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4130. */
  4131. Angle.BetweenTwoPoints = function (a, b) {
  4132. var delta = b.subtract(a);
  4133. var theta = Math.atan2(delta.y, delta.x);
  4134. return new Angle(theta);
  4135. };
  4136. /**
  4137. * Returns a new Angle object from the passed float in radians.
  4138. */
  4139. Angle.FromRadians = function (radians) {
  4140. return new Angle(radians);
  4141. };
  4142. /**
  4143. * Returns a new Angle object from the passed float in degrees.
  4144. */
  4145. Angle.FromDegrees = function (degrees) {
  4146. return new Angle(degrees * Math.PI / 180.0);
  4147. };
  4148. return Angle;
  4149. }());
  4150. BABYLON.Angle = Angle;
  4151. var Arc2 = (function () {
  4152. /**
  4153. * Creates an Arc object from the three passed points : start, middle and end.
  4154. */
  4155. function Arc2(startPoint, midPoint, endPoint) {
  4156. this.startPoint = startPoint;
  4157. this.midPoint = midPoint;
  4158. this.endPoint = endPoint;
  4159. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4160. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4161. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4162. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4163. 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);
  4164. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4165. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4166. var a1 = this.startAngle.degrees();
  4167. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4168. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4169. // angles correction
  4170. if (a2 - a1 > +180.0)
  4171. a2 -= 360.0;
  4172. if (a2 - a1 < -180.0)
  4173. a2 += 360.0;
  4174. if (a3 - a2 > +180.0)
  4175. a3 -= 360.0;
  4176. if (a3 - a2 < -180.0)
  4177. a3 += 360.0;
  4178. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4179. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4180. }
  4181. return Arc2;
  4182. }());
  4183. BABYLON.Arc2 = Arc2;
  4184. var Path2 = (function () {
  4185. /**
  4186. * Creates a Path2 object from the starting 2D coordinates x and y.
  4187. */
  4188. function Path2(x, y) {
  4189. this._points = new Array();
  4190. this._length = 0.0;
  4191. this.closed = false;
  4192. this._points.push(new Vector2(x, y));
  4193. }
  4194. /**
  4195. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4196. * Returns the updated Path2.
  4197. */
  4198. Path2.prototype.addLineTo = function (x, y) {
  4199. if (closed) {
  4200. //Tools.Error("cannot add lines to closed paths");
  4201. return this;
  4202. }
  4203. var newPoint = new Vector2(x, y);
  4204. var previousPoint = this._points[this._points.length - 1];
  4205. this._points.push(newPoint);
  4206. this._length += newPoint.subtract(previousPoint).length();
  4207. return this;
  4208. };
  4209. /**
  4210. * 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.
  4211. * Returns the updated Path2.
  4212. */
  4213. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4214. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4215. if (closed) {
  4216. //Tools.Error("cannot add arcs to closed paths");
  4217. return this;
  4218. }
  4219. var startPoint = this._points[this._points.length - 1];
  4220. var midPoint = new Vector2(midX, midY);
  4221. var endPoint = new Vector2(endX, endY);
  4222. var arc = new Arc2(startPoint, midPoint, endPoint);
  4223. var increment = arc.angle.radians() / numberOfSegments;
  4224. if (arc.orientation === Orientation.CW)
  4225. increment *= -1;
  4226. var currentAngle = arc.startAngle.radians() + increment;
  4227. for (var i = 0; i < numberOfSegments; i++) {
  4228. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4229. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4230. this.addLineTo(x, y);
  4231. currentAngle += increment;
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Closes the Path2.
  4237. * Returns the Path2.
  4238. */
  4239. Path2.prototype.close = function () {
  4240. this.closed = true;
  4241. return this;
  4242. };
  4243. /**
  4244. * Returns the Path2 total length (float).
  4245. */
  4246. Path2.prototype.length = function () {
  4247. var result = this._length;
  4248. if (!this.closed) {
  4249. var lastPoint = this._points[this._points.length - 1];
  4250. var firstPoint = this._points[0];
  4251. result += (firstPoint.subtract(lastPoint).length());
  4252. }
  4253. return result;
  4254. };
  4255. /**
  4256. * Returns the Path2 internal array of points.
  4257. */
  4258. Path2.prototype.getPoints = function () {
  4259. return this._points;
  4260. };
  4261. /**
  4262. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4263. */
  4264. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4265. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4266. //Tools.Error("normalized length position should be between 0 and 1.");
  4267. return Vector2.Zero();
  4268. }
  4269. var lengthPosition = normalizedLengthPosition * this.length();
  4270. var previousOffset = 0;
  4271. for (var i = 0; i < this._points.length; i++) {
  4272. var j = (i + 1) % this._points.length;
  4273. var a = this._points[i];
  4274. var b = this._points[j];
  4275. var bToA = b.subtract(a);
  4276. var nextOffset = (bToA.length() + previousOffset);
  4277. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4278. var dir = bToA.normalize();
  4279. var localOffset = lengthPosition - previousOffset;
  4280. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4281. }
  4282. previousOffset = nextOffset;
  4283. }
  4284. //Tools.Error("internal error");
  4285. return Vector2.Zero();
  4286. };
  4287. /**
  4288. * Returns a new Path2 starting at the coordinates (x, y).
  4289. */
  4290. Path2.StartingAt = function (x, y) {
  4291. return new Path2(x, y);
  4292. };
  4293. return Path2;
  4294. }());
  4295. BABYLON.Path2 = Path2;
  4296. var Path3D = (function () {
  4297. /**
  4298. * new Path3D(path, normal, raw)
  4299. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4300. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4301. * path : an array of Vector3, the curve axis of the Path3D
  4302. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4303. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4304. */
  4305. function Path3D(path, firstNormal, raw) {
  4306. this.path = path;
  4307. this._curve = new Array();
  4308. this._distances = new Array();
  4309. this._tangents = new Array();
  4310. this._normals = new Array();
  4311. this._binormals = new Array();
  4312. for (var p = 0; p < path.length; p++) {
  4313. this._curve[p] = path[p].clone(); // hard copy
  4314. }
  4315. this._raw = raw || false;
  4316. this._compute(firstNormal);
  4317. }
  4318. /**
  4319. * Returns the Path3D array of successive Vector3 designing its curve.
  4320. */
  4321. Path3D.prototype.getCurve = function () {
  4322. return this._curve;
  4323. };
  4324. /**
  4325. * Returns an array populated with tangent vectors on each Path3D curve point.
  4326. */
  4327. Path3D.prototype.getTangents = function () {
  4328. return this._tangents;
  4329. };
  4330. /**
  4331. * Returns an array populated with normal vectors on each Path3D curve point.
  4332. */
  4333. Path3D.prototype.getNormals = function () {
  4334. return this._normals;
  4335. };
  4336. /**
  4337. * Returns an array populated with binormal vectors on each Path3D curve point.
  4338. */
  4339. Path3D.prototype.getBinormals = function () {
  4340. return this._binormals;
  4341. };
  4342. /**
  4343. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4344. */
  4345. Path3D.prototype.getDistances = function () {
  4346. return this._distances;
  4347. };
  4348. /**
  4349. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4350. * Returns the same object updated.
  4351. */
  4352. Path3D.prototype.update = function (path, firstNormal) {
  4353. for (var p = 0; p < path.length; p++) {
  4354. this._curve[p].x = path[p].x;
  4355. this._curve[p].y = path[p].y;
  4356. this._curve[p].z = path[p].z;
  4357. }
  4358. this._compute(firstNormal);
  4359. return this;
  4360. };
  4361. // private function compute() : computes tangents, normals and binormals
  4362. Path3D.prototype._compute = function (firstNormal) {
  4363. var l = this._curve.length;
  4364. // first and last tangents
  4365. this._tangents[0] = this._getFirstNonNullVector(0);
  4366. if (!this._raw) {
  4367. this._tangents[0].normalize();
  4368. }
  4369. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4370. if (!this._raw) {
  4371. this._tangents[l - 1].normalize();
  4372. }
  4373. // normals and binormals at first point : arbitrary vector with _normalVector()
  4374. var tg0 = this._tangents[0];
  4375. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4376. this._normals[0] = pp0;
  4377. if (!this._raw) {
  4378. this._normals[0].normalize();
  4379. }
  4380. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4381. if (!this._raw) {
  4382. this._binormals[0].normalize();
  4383. }
  4384. this._distances[0] = 0.0;
  4385. // normals and binormals : next points
  4386. var prev; // previous vector (segment)
  4387. var cur; // current vector (segment)
  4388. var curTang; // current tangent
  4389. // previous normal
  4390. var prevBinor; // previous binormal
  4391. for (var i = 1; i < l; i++) {
  4392. // tangents
  4393. prev = this._getLastNonNullVector(i);
  4394. if (i < l - 1) {
  4395. cur = this._getFirstNonNullVector(i);
  4396. this._tangents[i] = prev.add(cur);
  4397. this._tangents[i].normalize();
  4398. }
  4399. this._distances[i] = this._distances[i - 1] + prev.length();
  4400. // normals and binormals
  4401. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4402. curTang = this._tangents[i];
  4403. prevBinor = this._binormals[i - 1];
  4404. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4405. if (!this._raw) {
  4406. this._normals[i].normalize();
  4407. }
  4408. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4409. if (!this._raw) {
  4410. this._binormals[i].normalize();
  4411. }
  4412. }
  4413. };
  4414. // private function getFirstNonNullVector(index)
  4415. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4416. Path3D.prototype._getFirstNonNullVector = function (index) {
  4417. var i = 1;
  4418. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4419. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4420. i++;
  4421. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4422. }
  4423. return nNVector;
  4424. };
  4425. // private function getLastNonNullVector(index)
  4426. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4427. Path3D.prototype._getLastNonNullVector = function (index) {
  4428. var i = 1;
  4429. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4430. while (nLVector.length() === 0 && index > i + 1) {
  4431. i++;
  4432. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4433. }
  4434. return nLVector;
  4435. };
  4436. // private function normalVector(v0, vt, va) :
  4437. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4438. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4439. Path3D.prototype._normalVector = function (v0, vt, va) {
  4440. var normal0;
  4441. var tgl = vt.length();
  4442. if (tgl === 0.0) {
  4443. tgl = 1.0;
  4444. }
  4445. if (va === undefined || va === null) {
  4446. var point;
  4447. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4448. point = new Vector3(0.0, -1.0, 0.0);
  4449. }
  4450. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4451. point = new Vector3(1.0, 0.0, 0.0);
  4452. }
  4453. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4454. point = new Vector3(0.0, 0.0, 1.0);
  4455. }
  4456. normal0 = Vector3.Cross(vt, point);
  4457. }
  4458. else {
  4459. normal0 = Vector3.Cross(vt, va);
  4460. Vector3.CrossToRef(normal0, vt, normal0);
  4461. }
  4462. normal0.normalize();
  4463. return normal0;
  4464. };
  4465. return Path3D;
  4466. }());
  4467. BABYLON.Path3D = Path3D;
  4468. var Curve3 = (function () {
  4469. /**
  4470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4471. * A Curve3 is designed from a series of successive Vector3.
  4472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4473. */
  4474. function Curve3(points) {
  4475. this._length = 0.0;
  4476. this._points = points;
  4477. this._length = this._computeLength(points);
  4478. }
  4479. /**
  4480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4482. * @param v1 (Vector3) the control point
  4483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4484. * @param nbPoints (integer) the wanted number of points in the curve
  4485. */
  4486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4488. var bez = new Array();
  4489. var equation = function (t, val0, val1, val2) {
  4490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4491. return res;
  4492. };
  4493. for (var i = 0; i <= nbPoints; i++) {
  4494. 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)));
  4495. }
  4496. return new Curve3(bez);
  4497. };
  4498. /**
  4499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4501. * @param v1 (Vector3) the first control point
  4502. * @param v2 (Vector3) the second control point
  4503. * @param v3 (Vector3) the end point of the Cubic Bezier
  4504. * @param nbPoints (integer) the wanted number of points in the curve
  4505. */
  4506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4508. var bez = new Array();
  4509. var equation = function (t, val0, val1, val2, val3) {
  4510. 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;
  4511. return res;
  4512. };
  4513. for (var i = 0; i <= nbPoints; i++) {
  4514. 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)));
  4515. }
  4516. return new Curve3(bez);
  4517. };
  4518. /**
  4519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4520. * @param p1 (Vector3) the origin point of the Hermite Spline
  4521. * @param t1 (Vector3) the tangent vector at the origin point
  4522. * @param p2 (Vector3) the end point of the Hermite Spline
  4523. * @param t2 (Vector3) the tangent vector at the end point
  4524. * @param nbPoints (integer) the wanted number of points in the curve
  4525. */
  4526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4527. var hermite = new Array();
  4528. var step = 1.0 / nbPoints;
  4529. for (var i = 0; i <= nbPoints; i++) {
  4530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4531. }
  4532. return new Curve3(hermite);
  4533. };
  4534. /**
  4535. * Returns a Curve3 object along a CatmullRom Spline curve :
  4536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4538. */
  4539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4540. var totalPoints = new Array();
  4541. totalPoints.push(points[0].clone());
  4542. Array.prototype.push.apply(totalPoints, points);
  4543. totalPoints.push(points[points.length - 1].clone());
  4544. var catmullRom = new Array();
  4545. var step = 1.0 / nbPoints;
  4546. for (var i = 0; i < totalPoints.length - 3; i++) {
  4547. var amount = 0.0;
  4548. for (var c = 0; c < nbPoints; c++) {
  4549. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4550. amount += step;
  4551. }
  4552. }
  4553. i--;
  4554. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4555. return new Curve3(catmullRom);
  4556. };
  4557. /**
  4558. * Returns the Curve3 stored array of successive Vector3
  4559. */
  4560. Curve3.prototype.getPoints = function () {
  4561. return this._points;
  4562. };
  4563. /**
  4564. * Returns the computed length (float) of the curve.
  4565. */
  4566. Curve3.prototype.length = function () {
  4567. return this._length;
  4568. };
  4569. /**
  4570. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4571. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4572. * curveA and curveB keep unchanged.
  4573. */
  4574. Curve3.prototype.continue = function (curve) {
  4575. var lastPoint = this._points[this._points.length - 1];
  4576. var continuedPoints = this._points.slice();
  4577. var curvePoints = curve.getPoints();
  4578. for (var i = 1; i < curvePoints.length; i++) {
  4579. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4580. }
  4581. var continuedCurve = new Curve3(continuedPoints);
  4582. return continuedCurve;
  4583. };
  4584. Curve3.prototype._computeLength = function (path) {
  4585. var l = 0;
  4586. for (var i = 1; i < path.length; i++) {
  4587. l += (path[i].subtract(path[i - 1])).length();
  4588. }
  4589. return l;
  4590. };
  4591. return Curve3;
  4592. }());
  4593. BABYLON.Curve3 = Curve3;
  4594. // SphericalHarmonics
  4595. var SphericalHarmonics = (function () {
  4596. function SphericalHarmonics() {
  4597. this.L00 = Vector3.Zero();
  4598. this.L1_1 = Vector3.Zero();
  4599. this.L10 = Vector3.Zero();
  4600. this.L11 = Vector3.Zero();
  4601. this.L2_2 = Vector3.Zero();
  4602. this.L2_1 = Vector3.Zero();
  4603. this.L20 = Vector3.Zero();
  4604. this.L21 = Vector3.Zero();
  4605. this.L22 = Vector3.Zero();
  4606. }
  4607. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4608. var colorVector = new Vector3(color.r, color.g, color.b);
  4609. var c = colorVector.scale(deltaSolidAngle);
  4610. this.L00 = this.L00.add(c.scale(0.282095));
  4611. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4612. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4613. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4614. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4615. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4616. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4617. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4618. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4619. };
  4620. SphericalHarmonics.prototype.scale = function (scale) {
  4621. this.L00 = this.L00.scale(scale);
  4622. this.L1_1 = this.L1_1.scale(scale);
  4623. this.L10 = this.L10.scale(scale);
  4624. this.L11 = this.L11.scale(scale);
  4625. this.L2_2 = this.L2_2.scale(scale);
  4626. this.L2_1 = this.L2_1.scale(scale);
  4627. this.L20 = this.L20.scale(scale);
  4628. this.L21 = this.L21.scale(scale);
  4629. this.L22 = this.L22.scale(scale);
  4630. };
  4631. return SphericalHarmonics;
  4632. }());
  4633. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4634. // SphericalPolynomial
  4635. var SphericalPolynomial = (function () {
  4636. function SphericalPolynomial() {
  4637. this.x = Vector3.Zero();
  4638. this.y = Vector3.Zero();
  4639. this.z = Vector3.Zero();
  4640. this.xx = Vector3.Zero();
  4641. this.yy = Vector3.Zero();
  4642. this.zz = Vector3.Zero();
  4643. this.xy = Vector3.Zero();
  4644. this.yz = Vector3.Zero();
  4645. this.zx = Vector3.Zero();
  4646. }
  4647. SphericalPolynomial.prototype.addAmbient = function (color) {
  4648. var colorVector = new Vector3(color.r, color.g, color.b);
  4649. this.xx = this.xx.add(colorVector);
  4650. this.yy = this.yy.add(colorVector);
  4651. this.zz = this.zz.add(colorVector);
  4652. };
  4653. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4654. var result = new SphericalPolynomial();
  4655. result.x = harmonics.L11.scale(1.02333);
  4656. result.y = harmonics.L1_1.scale(1.02333);
  4657. result.z = harmonics.L10.scale(1.02333);
  4658. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4659. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4660. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4661. result.yz = harmonics.L2_1.scale(0.858086);
  4662. result.zx = harmonics.L21.scale(0.858086);
  4663. result.xy = harmonics.L2_2.scale(0.858086);
  4664. return result;
  4665. };
  4666. return SphericalPolynomial;
  4667. }());
  4668. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4669. // Vertex formats
  4670. var PositionNormalVertex = (function () {
  4671. function PositionNormalVertex(position, normal) {
  4672. if (position === void 0) { position = Vector3.Zero(); }
  4673. if (normal === void 0) { normal = Vector3.Up(); }
  4674. this.position = position;
  4675. this.normal = normal;
  4676. }
  4677. PositionNormalVertex.prototype.clone = function () {
  4678. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4679. };
  4680. return PositionNormalVertex;
  4681. }());
  4682. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4683. var PositionNormalTextureVertex = (function () {
  4684. function PositionNormalTextureVertex(position, normal, uv) {
  4685. if (position === void 0) { position = Vector3.Zero(); }
  4686. if (normal === void 0) { normal = Vector3.Up(); }
  4687. if (uv === void 0) { uv = Vector2.Zero(); }
  4688. this.position = position;
  4689. this.normal = normal;
  4690. this.uv = uv;
  4691. }
  4692. PositionNormalTextureVertex.prototype.clone = function () {
  4693. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4694. };
  4695. return PositionNormalTextureVertex;
  4696. }());
  4697. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4698. // Temporary pre-allocated objects for engine internal use
  4699. // usage in any internal function :
  4700. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4701. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4702. var Tmp = (function () {
  4703. function Tmp() {
  4704. }
  4705. return Tmp;
  4706. }());
  4707. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4708. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4709. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4710. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4711. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4712. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4713. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4714. Matrix.Zero(), Matrix.Zero(),
  4715. Matrix.Zero(), Matrix.Zero(),
  4716. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4717. BABYLON.Tmp = Tmp;
  4718. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4719. var MathTmp = (function () {
  4720. function MathTmp() {
  4721. }
  4722. return MathTmp;
  4723. }());
  4724. MathTmp.Vector3 = [Vector3.Zero()];
  4725. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4726. MathTmp.Quaternion = [Quaternion.Zero()];
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=babylon.math.js.map
  4729. //# sourceMappingURL=babylon.mixins.js.map
  4730. var BABYLON;
  4731. (function (BABYLON) {
  4732. function generateSerializableMember(type, sourceName) {
  4733. return function (target, propertyKey) {
  4734. if (!target.__serializableMembers) {
  4735. target.__serializableMembers = {};
  4736. }
  4737. if (!target.__serializableMembers[propertyKey]) {
  4738. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4739. }
  4740. };
  4741. }
  4742. function generateExpandMember(setCallback, targetKey) {
  4743. return function (target, propertyKey) {
  4744. var key = targetKey || ("_" + propertyKey);
  4745. Object.defineProperty(target, propertyKey, {
  4746. get: function () {
  4747. return this[key];
  4748. },
  4749. set: function (value) {
  4750. if (this[key] === value) {
  4751. return;
  4752. }
  4753. this[key] = value;
  4754. if (setCallback) {
  4755. target[setCallback].apply(this);
  4756. }
  4757. },
  4758. enumerable: true,
  4759. configurable: true
  4760. });
  4761. };
  4762. }
  4763. function expandToProperty(callback, targetKey) {
  4764. return generateExpandMember(callback, targetKey);
  4765. }
  4766. BABYLON.expandToProperty = expandToProperty;
  4767. function serialize(sourceName) {
  4768. return generateSerializableMember(0, sourceName); // value member
  4769. }
  4770. BABYLON.serialize = serialize;
  4771. function serializeAsTexture(sourceName) {
  4772. return generateSerializableMember(1, sourceName); // texture member
  4773. }
  4774. BABYLON.serializeAsTexture = serializeAsTexture;
  4775. function serializeAsColor3(sourceName) {
  4776. return generateSerializableMember(2, sourceName); // color3 member
  4777. }
  4778. BABYLON.serializeAsColor3 = serializeAsColor3;
  4779. function serializeAsFresnelParameters(sourceName) {
  4780. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4781. }
  4782. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4783. function serializeAsVector2(sourceName) {
  4784. return generateSerializableMember(4, sourceName); // vector2 member
  4785. }
  4786. BABYLON.serializeAsVector2 = serializeAsVector2;
  4787. function serializeAsVector3(sourceName) {
  4788. return generateSerializableMember(5, sourceName); // vector3 member
  4789. }
  4790. BABYLON.serializeAsVector3 = serializeAsVector3;
  4791. function serializeAsMeshReference(sourceName) {
  4792. return generateSerializableMember(6, sourceName); // mesh reference member
  4793. }
  4794. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4795. function serializeAsColorCurves(sourceName) {
  4796. return generateSerializableMember(7, sourceName); // color curves
  4797. }
  4798. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4799. var SerializationHelper = (function () {
  4800. function SerializationHelper() {
  4801. }
  4802. SerializationHelper.Serialize = function (entity, serializationObject) {
  4803. if (!serializationObject) {
  4804. serializationObject = {};
  4805. }
  4806. // Tags
  4807. if (BABYLON.Tags) {
  4808. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4809. }
  4810. // Properties
  4811. for (var property in entity.__serializableMembers) {
  4812. var propertyDescriptor = entity.__serializableMembers[property];
  4813. var targetPropertyName = propertyDescriptor.sourceName || property;
  4814. var propertyType = propertyDescriptor.type;
  4815. var sourceProperty = entity[property];
  4816. if (sourceProperty !== undefined && sourceProperty !== null) {
  4817. switch (propertyType) {
  4818. case 0:
  4819. serializationObject[targetPropertyName] = sourceProperty;
  4820. break;
  4821. case 1:
  4822. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4823. break;
  4824. case 2:
  4825. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4826. break;
  4827. case 3:
  4828. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4829. break;
  4830. case 4:
  4831. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4832. break;
  4833. case 5:
  4834. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4835. break;
  4836. case 6:
  4837. serializationObject[targetPropertyName] = sourceProperty.id;
  4838. break;
  4839. case 7:
  4840. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4841. break;
  4842. }
  4843. }
  4844. }
  4845. return serializationObject;
  4846. };
  4847. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4848. var destination = creationFunction();
  4849. // Tags
  4850. if (BABYLON.Tags) {
  4851. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4852. }
  4853. // Properties
  4854. for (var property in destination.__serializableMembers) {
  4855. var propertyDescriptor = destination.__serializableMembers[property];
  4856. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4857. var propertyType = propertyDescriptor.type;
  4858. if (sourceProperty !== undefined && sourceProperty !== null) {
  4859. switch (propertyType) {
  4860. case 0:
  4861. destination[property] = sourceProperty;
  4862. break;
  4863. case 1:
  4864. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4865. break;
  4866. case 2:
  4867. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4868. break;
  4869. case 3:
  4870. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4871. break;
  4872. case 4:
  4873. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4874. break;
  4875. case 5:
  4876. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4877. break;
  4878. case 6:
  4879. destination[property] = scene.getLastMeshByID(sourceProperty);
  4880. break;
  4881. case 7:
  4882. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4883. break;
  4884. }
  4885. }
  4886. }
  4887. return destination;
  4888. };
  4889. SerializationHelper.Clone = function (creationFunction, source) {
  4890. var destination = creationFunction();
  4891. // Tags
  4892. if (BABYLON.Tags) {
  4893. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4894. }
  4895. // Properties
  4896. for (var property in destination.__serializableMembers) {
  4897. var propertyDescriptor = destination.__serializableMembers[property];
  4898. var sourceProperty = source[property];
  4899. var propertyType = propertyDescriptor.type;
  4900. if (sourceProperty !== undefined && sourceProperty !== null) {
  4901. switch (propertyType) {
  4902. case 0: // Value
  4903. case 6:
  4904. destination[property] = sourceProperty;
  4905. break;
  4906. case 1: // Texture
  4907. case 2: // Color3
  4908. case 3: // FresnelParameters
  4909. case 4: // Vector2
  4910. case 5: // Vector3
  4911. case 7:
  4912. destination[property] = sourceProperty.clone();
  4913. break;
  4914. }
  4915. }
  4916. }
  4917. return destination;
  4918. };
  4919. return SerializationHelper;
  4920. }());
  4921. BABYLON.SerializationHelper = SerializationHelper;
  4922. })(BABYLON || (BABYLON = {}));
  4923. //# sourceMappingURL=babylon.decorators.js.map
  4924. var BABYLON;
  4925. (function (BABYLON) {
  4926. /**
  4927. * A class serves as a medium between the observable and its observers
  4928. */
  4929. var EventState = (function () {
  4930. /**
  4931. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4932. */
  4933. function EventState(mask, skipNextObservers) {
  4934. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4935. this.initalize(mask, skipNextObservers);
  4936. }
  4937. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4938. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4939. this.mask = mask;
  4940. this.skipNextObservers = skipNextObservers;
  4941. return this;
  4942. };
  4943. return EventState;
  4944. }());
  4945. BABYLON.EventState = EventState;
  4946. /**
  4947. * Represent an Observer registered to a given Observable object.
  4948. */
  4949. var Observer = (function () {
  4950. function Observer(callback, mask) {
  4951. this.callback = callback;
  4952. this.mask = mask;
  4953. }
  4954. return Observer;
  4955. }());
  4956. BABYLON.Observer = Observer;
  4957. /**
  4958. * The Observable class is a simple implementation of the Observable pattern.
  4959. * 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.
  4960. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4961. * 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).
  4962. * 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.
  4963. */
  4964. var Observable = (function () {
  4965. function Observable() {
  4966. this._observers = new Array();
  4967. this._eventState = new EventState(0);
  4968. }
  4969. /**
  4970. * Create a new Observer with the specified callback
  4971. * @param callback the callback that will be executed for that Observer
  4972. * @param mask the mask used to filter observers
  4973. * @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.
  4974. */
  4975. Observable.prototype.add = function (callback, mask, insertFirst) {
  4976. if (mask === void 0) { mask = -1; }
  4977. if (insertFirst === void 0) { insertFirst = false; }
  4978. if (!callback) {
  4979. return null;
  4980. }
  4981. var observer = new Observer(callback, mask);
  4982. if (insertFirst) {
  4983. this._observers.unshift(observer);
  4984. }
  4985. else {
  4986. this._observers.push(observer);
  4987. }
  4988. return observer;
  4989. };
  4990. /**
  4991. * Remove an Observer from the Observable object
  4992. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4993. */
  4994. Observable.prototype.remove = function (observer) {
  4995. var index = this._observers.indexOf(observer);
  4996. if (index !== -1) {
  4997. this._observers.splice(index, 1);
  4998. return true;
  4999. }
  5000. return false;
  5001. };
  5002. /**
  5003. * Remove a callback from the Observable object
  5004. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5005. */
  5006. Observable.prototype.removeCallback = function (callback) {
  5007. for (var index = 0; index < this._observers.length; index++) {
  5008. if (this._observers[index].callback === callback) {
  5009. this._observers.splice(index, 1);
  5010. return true;
  5011. }
  5012. }
  5013. return false;
  5014. };
  5015. /**
  5016. * Notify all Observers by calling their respective callback with the given data
  5017. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5018. * @param eventData
  5019. * @param mask
  5020. */
  5021. Observable.prototype.notifyObservers = function (eventData, mask) {
  5022. if (mask === void 0) { mask = -1; }
  5023. var state = this._eventState;
  5024. state.mask = mask;
  5025. state.skipNextObservers = false;
  5026. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5027. var obs = _a[_i];
  5028. if (obs.mask & mask) {
  5029. obs.callback(eventData, state);
  5030. }
  5031. if (state.skipNextObservers) {
  5032. return false;
  5033. }
  5034. }
  5035. return true;
  5036. };
  5037. /**
  5038. * return true is the Observable has at least one Observer registered
  5039. */
  5040. Observable.prototype.hasObservers = function () {
  5041. return this._observers.length > 0;
  5042. };
  5043. /**
  5044. * Clear the list of observers
  5045. */
  5046. Observable.prototype.clear = function () {
  5047. this._observers = new Array();
  5048. };
  5049. /**
  5050. * Clone the current observable
  5051. */
  5052. Observable.prototype.clone = function () {
  5053. var result = new Observable();
  5054. result._observers = this._observers.slice(0);
  5055. return result;
  5056. };
  5057. /**
  5058. * Does this observable handles observer registered with a given mask
  5059. * @param {number} trigger - the mask to be tested
  5060. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5061. **/
  5062. Observable.prototype.hasSpecificMask = function (mask) {
  5063. if (mask === void 0) { mask = -1; }
  5064. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5065. var obs = _a[_i];
  5066. if (obs.mask & mask && obs.mask === mask) {
  5067. return true;
  5068. }
  5069. }
  5070. return false;
  5071. };
  5072. return Observable;
  5073. }());
  5074. BABYLON.Observable = Observable;
  5075. })(BABYLON || (BABYLON = {}));
  5076. //# sourceMappingURL=babylon.observable.js.map
  5077. var BABYLON;
  5078. (function (BABYLON) {
  5079. var SmartArray = (function () {
  5080. function SmartArray(capacity) {
  5081. this.length = 0;
  5082. this._duplicateId = 0;
  5083. this.data = new Array(capacity);
  5084. this._id = SmartArray._GlobalId++;
  5085. }
  5086. SmartArray.prototype.push = function (value) {
  5087. this.data[this.length++] = value;
  5088. if (this.length > this.data.length) {
  5089. this.data.length *= 2;
  5090. }
  5091. if (!value.__smartArrayFlags) {
  5092. value.__smartArrayFlags = {};
  5093. }
  5094. value.__smartArrayFlags[this._id] = this._duplicateId;
  5095. };
  5096. SmartArray.prototype.forEach = function (func) {
  5097. for (var index = 0; index < this.length; index++) {
  5098. func(this.data[index]);
  5099. }
  5100. };
  5101. SmartArray.prototype.pushNoDuplicate = function (value) {
  5102. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5103. return false;
  5104. }
  5105. this.push(value);
  5106. return true;
  5107. };
  5108. SmartArray.prototype.sort = function (compareFn) {
  5109. this.data.sort(compareFn);
  5110. };
  5111. SmartArray.prototype.reset = function () {
  5112. this.length = 0;
  5113. this._duplicateId++;
  5114. };
  5115. SmartArray.prototype.dispose = function () {
  5116. this.reset();
  5117. this.data.length = 0;
  5118. };
  5119. SmartArray.prototype.concat = function (array) {
  5120. if (array.length === 0) {
  5121. return;
  5122. }
  5123. if (this.length + array.length > this.data.length) {
  5124. this.data.length = (this.length + array.length) * 2;
  5125. }
  5126. for (var index = 0; index < array.length; index++) {
  5127. this.data[this.length++] = (array.data || array)[index];
  5128. }
  5129. };
  5130. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5131. if (array.length === 0) {
  5132. return;
  5133. }
  5134. if (this.length + array.length > this.data.length) {
  5135. this.data.length = (this.length + array.length) * 2;
  5136. }
  5137. for (var index = 0; index < array.length; index++) {
  5138. var item = (array.data || array)[index];
  5139. this.pushNoDuplicate(item);
  5140. }
  5141. };
  5142. SmartArray.prototype.indexOf = function (value) {
  5143. var position = this.data.indexOf(value);
  5144. if (position >= this.length) {
  5145. return -1;
  5146. }
  5147. return position;
  5148. };
  5149. SmartArray.prototype.contains = function (value) {
  5150. return this.data.indexOf(value) !== -1;
  5151. };
  5152. return SmartArray;
  5153. }());
  5154. // Statics
  5155. SmartArray._GlobalId = 0;
  5156. BABYLON.SmartArray = SmartArray;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.smartArray.js.map
  5159. var BABYLON;
  5160. (function (BABYLON) {
  5161. // Screenshots
  5162. var screenshotCanvas;
  5163. var cloneValue = function (source, destinationObject) {
  5164. if (!source)
  5165. return null;
  5166. if (source instanceof BABYLON.Mesh) {
  5167. return null;
  5168. }
  5169. if (source instanceof BABYLON.SubMesh) {
  5170. return source.clone(destinationObject);
  5171. }
  5172. else if (source.clone) {
  5173. return source.clone();
  5174. }
  5175. return null;
  5176. };
  5177. var Tools = (function () {
  5178. function Tools() {
  5179. }
  5180. ;
  5181. /**
  5182. * Interpolates between a and b via alpha
  5183. * @param a The lower value (returned when alpha = 0)
  5184. * @param b The upper value (returned when alpha = 1)
  5185. * @param alpha The interpolation-factor
  5186. * @return The mixed value
  5187. */
  5188. Tools.Mix = function (a, b, alpha) {
  5189. return a * (1 - alpha) + b * alpha;
  5190. };
  5191. Tools.Instantiate = function (className) {
  5192. var arr = className.split(".");
  5193. var fn = (window || this);
  5194. for (var i = 0, len = arr.length; i < len; i++) {
  5195. fn = fn[arr[i]];
  5196. }
  5197. if (typeof fn !== "function") {
  5198. return null;
  5199. }
  5200. return fn;
  5201. };
  5202. Tools.SetImmediate = function (action) {
  5203. if (window.setImmediate) {
  5204. window.setImmediate(action);
  5205. }
  5206. else {
  5207. setTimeout(action, 1);
  5208. }
  5209. };
  5210. Tools.IsExponentOfTwo = function (value) {
  5211. var count = 1;
  5212. do {
  5213. count *= 2;
  5214. } while (count < value);
  5215. return count === value;
  5216. };
  5217. Tools.GetExponentOfTwo = function (value, max) {
  5218. var count = 1;
  5219. do {
  5220. count *= 2;
  5221. } while (count < value);
  5222. if (count > max)
  5223. count = max;
  5224. return count;
  5225. };
  5226. Tools.GetFilename = function (path) {
  5227. var index = path.lastIndexOf("/");
  5228. if (index < 0)
  5229. return path;
  5230. return path.substring(index + 1);
  5231. };
  5232. Tools.GetDOMTextContent = function (element) {
  5233. var result = "";
  5234. var child = element.firstChild;
  5235. while (child) {
  5236. if (child.nodeType === 3) {
  5237. result += child.textContent;
  5238. }
  5239. child = child.nextSibling;
  5240. }
  5241. return result;
  5242. };
  5243. Tools.ToDegrees = function (angle) {
  5244. return angle * 180 / Math.PI;
  5245. };
  5246. Tools.ToRadians = function (angle) {
  5247. return angle * Math.PI / 180;
  5248. };
  5249. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5250. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5251. var output = "";
  5252. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5253. var i = 0;
  5254. var bytes = new Uint8Array(buffer);
  5255. while (i < bytes.length) {
  5256. chr1 = bytes[i++];
  5257. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5258. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5259. enc1 = chr1 >> 2;
  5260. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5261. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5262. enc4 = chr3 & 63;
  5263. if (isNaN(chr2)) {
  5264. enc3 = enc4 = 64;
  5265. }
  5266. else if (isNaN(chr3)) {
  5267. enc4 = 64;
  5268. }
  5269. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5270. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5271. }
  5272. return "data:image/png;base64," + output;
  5273. };
  5274. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5275. if (bias === void 0) { bias = null; }
  5276. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5277. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5278. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5279. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5280. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5281. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5282. }
  5283. if (bias) {
  5284. minimum.x -= minimum.x * bias.x + bias.y;
  5285. minimum.y -= minimum.y * bias.x + bias.y;
  5286. minimum.z -= minimum.z * bias.x + bias.y;
  5287. maximum.x += maximum.x * bias.x + bias.y;
  5288. maximum.y += maximum.y * bias.x + bias.y;
  5289. maximum.z += maximum.z * bias.x + bias.y;
  5290. }
  5291. return {
  5292. minimum: minimum,
  5293. maximum: maximum
  5294. };
  5295. };
  5296. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5297. if (bias === void 0) { bias = null; }
  5298. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5299. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5300. if (!stride) {
  5301. stride = 3;
  5302. }
  5303. for (var index = start; index < start + count; index++) {
  5304. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5305. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5306. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5307. }
  5308. if (bias) {
  5309. minimum.x -= minimum.x * bias.x + bias.y;
  5310. minimum.y -= minimum.y * bias.x + bias.y;
  5311. minimum.z -= minimum.z * bias.x + bias.y;
  5312. maximum.x += maximum.x * bias.x + bias.y;
  5313. maximum.y += maximum.y * bias.x + bias.y;
  5314. maximum.z += maximum.z * bias.x + bias.y;
  5315. }
  5316. return {
  5317. minimum: minimum,
  5318. maximum: maximum
  5319. };
  5320. };
  5321. Tools.Vector2ArrayFeeder = function (array) {
  5322. return function (index) {
  5323. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5324. var length = isFloatArray ? array.length / 2 : array.length;
  5325. if (index >= length) {
  5326. return null;
  5327. }
  5328. if (isFloatArray) {
  5329. var fa = array;
  5330. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5331. }
  5332. var a = array;
  5333. return a[index];
  5334. };
  5335. };
  5336. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5337. if (bias === void 0) { bias = null; }
  5338. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5339. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5340. var i = 0;
  5341. var cur = feeder(i++);
  5342. while (cur) {
  5343. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5344. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5345. cur = feeder(i++);
  5346. }
  5347. if (bias) {
  5348. minimum.x -= minimum.x * bias.x + bias.y;
  5349. minimum.y -= minimum.y * bias.x + bias.y;
  5350. maximum.x += maximum.x * bias.x + bias.y;
  5351. maximum.y += maximum.y * bias.x + bias.y;
  5352. }
  5353. return {
  5354. minimum: minimum,
  5355. maximum: maximum
  5356. };
  5357. };
  5358. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5359. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5360. return undefined;
  5361. return Array.isArray(obj) ? obj : [obj];
  5362. };
  5363. // Misc.
  5364. Tools.GetPointerPrefix = function () {
  5365. var eventPrefix = "pointer";
  5366. // Check if pointer events are supported
  5367. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5368. eventPrefix = "mouse";
  5369. }
  5370. return eventPrefix;
  5371. };
  5372. /**
  5373. * @param func - the function to be called
  5374. * @param requester - the object that will request the next frame. Falls back to window.
  5375. */
  5376. Tools.QueueNewFrame = function (func, requester) {
  5377. if (requester === void 0) { requester = window; }
  5378. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5379. /*if(requester.isPresenting) {
  5380. return;
  5381. } else*/ if (requester.requestAnimationFrame)
  5382. requester.requestAnimationFrame(func);
  5383. else if (requester.msRequestAnimationFrame)
  5384. requester.msRequestAnimationFrame(func);
  5385. else if (requester.webkitRequestAnimationFrame)
  5386. requester.webkitRequestAnimationFrame(func);
  5387. else if (requester.mozRequestAnimationFrame)
  5388. requester.mozRequestAnimationFrame(func);
  5389. else if (requester.oRequestAnimationFrame)
  5390. requester.oRequestAnimationFrame(func);
  5391. else {
  5392. window.setTimeout(func, 16);
  5393. }
  5394. };
  5395. Tools.RequestFullscreen = function (element) {
  5396. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5397. if (!requestFunction)
  5398. return;
  5399. requestFunction.call(element);
  5400. };
  5401. Tools.ExitFullscreen = function () {
  5402. if (document.exitFullscreen) {
  5403. document.exitFullscreen();
  5404. }
  5405. else if (document.mozCancelFullScreen) {
  5406. document.mozCancelFullScreen();
  5407. }
  5408. else if (document.webkitCancelFullScreen) {
  5409. document.webkitCancelFullScreen();
  5410. }
  5411. else if (document.msCancelFullScreen) {
  5412. document.msCancelFullScreen();
  5413. }
  5414. };
  5415. Tools.SetCorsBehavior = function (url, img) {
  5416. if (Tools.CorsBehavior) {
  5417. switch (typeof (Tools.CorsBehavior)) {
  5418. case "function":
  5419. var result = Tools.CorsBehavior(url);
  5420. if (result) {
  5421. img.crossOrigin = result;
  5422. }
  5423. break;
  5424. case "string":
  5425. default:
  5426. img.crossOrigin = Tools.CorsBehavior;
  5427. break;
  5428. }
  5429. }
  5430. };
  5431. // External files
  5432. Tools.CleanUrl = function (url) {
  5433. url = url.replace(/#/mg, "%23");
  5434. return url;
  5435. };
  5436. Tools.LoadImage = function (url, onload, onerror, database) {
  5437. if (url instanceof ArrayBuffer) {
  5438. url = Tools.EncodeArrayBufferTobase64(url);
  5439. }
  5440. url = Tools.CleanUrl(url);
  5441. var img = new Image();
  5442. if (url.substr(0, 5) !== "data:") {
  5443. Tools.SetCorsBehavior(url, img);
  5444. }
  5445. img.onload = function () {
  5446. onload(img);
  5447. };
  5448. img.onerror = function (err) {
  5449. Tools.Error("Error while trying to load image: " + url);
  5450. if (Tools.UseFallbackTexture) {
  5451. img.src = Tools.fallbackTexture;
  5452. onload(img);
  5453. }
  5454. else {
  5455. onerror();
  5456. }
  5457. };
  5458. var noIndexedDB = function () {
  5459. img.src = url;
  5460. };
  5461. var loadFromIndexedDB = function () {
  5462. database.loadImageFromDB(url, img);
  5463. };
  5464. //ANY database to do!
  5465. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5466. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5467. }
  5468. else {
  5469. if (url.indexOf("file:") !== 0) {
  5470. noIndexedDB();
  5471. }
  5472. else {
  5473. var textureName = url.substring(5).toLowerCase();
  5474. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5475. try {
  5476. var blobURL;
  5477. try {
  5478. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5479. }
  5480. catch (ex) {
  5481. // Chrome doesn't support oneTimeOnly parameter
  5482. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5483. }
  5484. img.src = blobURL;
  5485. }
  5486. catch (e) {
  5487. img.src = null;
  5488. }
  5489. }
  5490. else {
  5491. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5492. img.src = Tools.fallbackTexture;
  5493. }
  5494. }
  5495. }
  5496. return img;
  5497. };
  5498. //ANY
  5499. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5500. url = Tools.CleanUrl(url);
  5501. var noIndexedDB = function () {
  5502. var request = new XMLHttpRequest();
  5503. var loadUrl = Tools.BaseUrl + url;
  5504. request.open('GET', loadUrl, true);
  5505. if (useArrayBuffer) {
  5506. request.responseType = "arraybuffer";
  5507. }
  5508. request.onprogress = progressCallBack;
  5509. request.onreadystatechange = function () {
  5510. // In case of undefined state in some browsers.
  5511. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5512. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5513. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5514. callback(!useArrayBuffer ? request.responseText : request.response);
  5515. }
  5516. else {
  5517. if (onError) {
  5518. onError(request);
  5519. }
  5520. else {
  5521. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5522. }
  5523. }
  5524. }
  5525. };
  5526. request.send(null);
  5527. };
  5528. var loadFromIndexedDB = function () {
  5529. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5530. };
  5531. if (url.indexOf("file:") !== -1) {
  5532. var fileName = url.substring(5).toLowerCase();
  5533. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5534. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5535. }
  5536. else {
  5537. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5538. }
  5539. }
  5540. else {
  5541. // Caching all files
  5542. if (database && database.enableSceneOffline) {
  5543. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5544. }
  5545. else {
  5546. noIndexedDB();
  5547. }
  5548. }
  5549. };
  5550. /**
  5551. * Load a script (identified by an url). When the url returns, the
  5552. * content of this file is added into a new script element, attached to the DOM (body element)
  5553. */
  5554. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5555. var head = document.getElementsByTagName('head')[0];
  5556. var script = document.createElement('script');
  5557. script.type = 'text/javascript';
  5558. script.src = scriptUrl;
  5559. var self = this;
  5560. script.onload = function () {
  5561. if (onSuccess) {
  5562. onSuccess();
  5563. }
  5564. };
  5565. script.onerror = function () {
  5566. if (onError) {
  5567. onError();
  5568. }
  5569. };
  5570. head.appendChild(script);
  5571. };
  5572. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5573. var reader = new FileReader();
  5574. reader.onload = function (e) {
  5575. //target doesn't have result from ts 1.3
  5576. callback(e.target['result']);
  5577. };
  5578. reader.onprogress = progressCallback;
  5579. reader.readAsDataURL(fileToLoad);
  5580. };
  5581. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5582. var reader = new FileReader();
  5583. reader.onerror = function (e) {
  5584. Tools.Log("Error while reading file: " + fileToLoad.name);
  5585. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5586. };
  5587. reader.onload = function (e) {
  5588. //target doesn't have result from ts 1.3
  5589. callback(e.target['result']);
  5590. };
  5591. reader.onprogress = progressCallBack;
  5592. if (!useArrayBuffer) {
  5593. // Asynchronous read
  5594. reader.readAsText(fileToLoad);
  5595. }
  5596. else {
  5597. reader.readAsArrayBuffer(fileToLoad);
  5598. }
  5599. };
  5600. //returns a downloadable url to a file content.
  5601. Tools.FileAsURL = function (content) {
  5602. var fileBlob = new Blob([content]);
  5603. var url = window.URL || window.webkitURL;
  5604. var link = url.createObjectURL(fileBlob);
  5605. return link;
  5606. };
  5607. // Misc.
  5608. Tools.Format = function (value, decimals) {
  5609. if (decimals === void 0) { decimals = 2; }
  5610. return value.toFixed(decimals);
  5611. };
  5612. Tools.CheckExtends = function (v, min, max) {
  5613. if (v.x < min.x)
  5614. min.x = v.x;
  5615. if (v.y < min.y)
  5616. min.y = v.y;
  5617. if (v.z < min.z)
  5618. min.z = v.z;
  5619. if (v.x > max.x)
  5620. max.x = v.x;
  5621. if (v.y > max.y)
  5622. max.y = v.y;
  5623. if (v.z > max.z)
  5624. max.z = v.z;
  5625. };
  5626. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5627. for (var prop in source) {
  5628. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5629. continue;
  5630. }
  5631. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5632. continue;
  5633. }
  5634. var sourceValue = source[prop];
  5635. var typeOfSourceValue = typeof sourceValue;
  5636. if (typeOfSourceValue === "function") {
  5637. continue;
  5638. }
  5639. if (typeOfSourceValue === "object") {
  5640. if (sourceValue instanceof Array) {
  5641. destination[prop] = [];
  5642. if (sourceValue.length > 0) {
  5643. if (typeof sourceValue[0] == "object") {
  5644. for (var index = 0; index < sourceValue.length; index++) {
  5645. var clonedValue = cloneValue(sourceValue[index], destination);
  5646. if (destination[prop].indexOf(clonedValue) === -1) {
  5647. destination[prop].push(clonedValue);
  5648. }
  5649. }
  5650. }
  5651. else {
  5652. destination[prop] = sourceValue.slice(0);
  5653. }
  5654. }
  5655. }
  5656. else {
  5657. destination[prop] = cloneValue(sourceValue, destination);
  5658. }
  5659. }
  5660. else {
  5661. destination[prop] = sourceValue;
  5662. }
  5663. }
  5664. };
  5665. Tools.IsEmpty = function (obj) {
  5666. for (var i in obj) {
  5667. return false;
  5668. }
  5669. return true;
  5670. };
  5671. Tools.RegisterTopRootEvents = function (events) {
  5672. for (var index = 0; index < events.length; index++) {
  5673. var event = events[index];
  5674. window.addEventListener(event.name, event.handler, false);
  5675. try {
  5676. if (window.parent) {
  5677. window.parent.addEventListener(event.name, event.handler, false);
  5678. }
  5679. }
  5680. catch (e) {
  5681. // Silently fails...
  5682. }
  5683. }
  5684. };
  5685. Tools.UnregisterTopRootEvents = function (events) {
  5686. for (var index = 0; index < events.length; index++) {
  5687. var event = events[index];
  5688. window.removeEventListener(event.name, event.handler);
  5689. try {
  5690. if (window.parent) {
  5691. window.parent.removeEventListener(event.name, event.handler);
  5692. }
  5693. }
  5694. catch (e) {
  5695. // Silently fails...
  5696. }
  5697. }
  5698. };
  5699. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5700. if (mimeType === void 0) { mimeType = "image/png"; }
  5701. // Read the contents of the framebuffer
  5702. var numberOfChannelsByLine = width * 4;
  5703. var halfHeight = height / 2;
  5704. //Reading datas from WebGL
  5705. var data = engine.readPixels(0, 0, width, height);
  5706. //To flip image on Y axis.
  5707. for (var i = 0; i < halfHeight; i++) {
  5708. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5709. var currentCell = j + i * numberOfChannelsByLine;
  5710. var targetLine = height - i - 1;
  5711. var targetCell = j + targetLine * numberOfChannelsByLine;
  5712. var temp = data[currentCell];
  5713. data[currentCell] = data[targetCell];
  5714. data[targetCell] = temp;
  5715. }
  5716. }
  5717. // Create a 2D canvas to store the result
  5718. if (!screenshotCanvas) {
  5719. screenshotCanvas = document.createElement('canvas');
  5720. }
  5721. screenshotCanvas.width = width;
  5722. screenshotCanvas.height = height;
  5723. var context = screenshotCanvas.getContext('2d');
  5724. // Copy the pixels to a 2D canvas
  5725. var imageData = context.createImageData(width, height);
  5726. var castData = (imageData.data);
  5727. castData.set(data);
  5728. context.putImageData(imageData, 0, 0);
  5729. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5730. };
  5731. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5732. if (mimeType === void 0) { mimeType = "image/png"; }
  5733. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5734. if (successCallback) {
  5735. successCallback(base64Image);
  5736. }
  5737. else {
  5738. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5739. if (("download" in document.createElement("a"))) {
  5740. var a = window.document.createElement("a");
  5741. a.href = base64Image;
  5742. var date = new Date();
  5743. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5744. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5745. window.document.body.appendChild(a);
  5746. a.addEventListener("click", function () {
  5747. a.parentElement.removeChild(a);
  5748. });
  5749. a.click();
  5750. //Or opening a new tab with the image if it is not possible to automatically start download.
  5751. }
  5752. else {
  5753. var newWindow = window.open("");
  5754. var img = newWindow.document.createElement("img");
  5755. img.src = base64Image;
  5756. newWindow.document.body.appendChild(img);
  5757. }
  5758. }
  5759. };
  5760. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5761. if (mimeType === void 0) { mimeType = "image/png"; }
  5762. var width;
  5763. var height;
  5764. // If a precision value is specified
  5765. if (size.precision) {
  5766. width = Math.round(engine.getRenderWidth() * size.precision);
  5767. height = Math.round(width / engine.getAspectRatio(camera));
  5768. }
  5769. else if (size.width && size.height) {
  5770. width = size.width;
  5771. height = size.height;
  5772. }
  5773. else if (size.width && !size.height) {
  5774. width = size.width;
  5775. height = Math.round(width / engine.getAspectRatio(camera));
  5776. }
  5777. else if (size.height && !size.width) {
  5778. height = size.height;
  5779. width = Math.round(height * engine.getAspectRatio(camera));
  5780. }
  5781. else if (!isNaN(size)) {
  5782. height = size;
  5783. width = size;
  5784. }
  5785. else {
  5786. Tools.Error("Invalid 'size' parameter !");
  5787. return;
  5788. }
  5789. if (!screenshotCanvas) {
  5790. screenshotCanvas = document.createElement('canvas');
  5791. }
  5792. screenshotCanvas.width = width;
  5793. screenshotCanvas.height = height;
  5794. var renderContext = screenshotCanvas.getContext("2d");
  5795. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5796. var newWidth = width;
  5797. var newHeight = newWidth / ratio;
  5798. if (newHeight > height) {
  5799. newHeight = height;
  5800. newWidth = newHeight * ratio;
  5801. }
  5802. var offsetX = Math.max(0, width - newWidth) / 2;
  5803. var offsetY = Math.max(0, height - newHeight) / 2;
  5804. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5805. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5806. };
  5807. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5808. if (mimeType === void 0) { mimeType = "image/png"; }
  5809. if (samples === void 0) { samples = 1; }
  5810. var width;
  5811. var height;
  5812. //If a precision value is specified
  5813. if (size.precision) {
  5814. width = Math.round(engine.getRenderWidth() * size.precision);
  5815. height = Math.round(width / engine.getAspectRatio(camera));
  5816. size = { width: width, height: height };
  5817. }
  5818. else if (size.width && size.height) {
  5819. width = size.width;
  5820. height = size.height;
  5821. }
  5822. else if (size.width && !size.height) {
  5823. width = size.width;
  5824. height = Math.round(width / engine.getAspectRatio(camera));
  5825. size = { width: width, height: height };
  5826. }
  5827. else if (size.height && !size.width) {
  5828. height = size.height;
  5829. width = Math.round(height * engine.getAspectRatio(camera));
  5830. size = { width: width, height: height };
  5831. }
  5832. else if (!isNaN(size)) {
  5833. height = size;
  5834. width = size;
  5835. }
  5836. else {
  5837. Tools.Error("Invalid 'size' parameter !");
  5838. return;
  5839. }
  5840. var scene = camera.getScene();
  5841. var previousCamera = null;
  5842. if (scene.activeCamera !== camera) {
  5843. previousCamera = scene.activeCamera;
  5844. scene.activeCamera = camera;
  5845. }
  5846. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5847. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5848. texture.renderList = scene.meshes;
  5849. texture.samples = samples;
  5850. texture.onAfterRenderObservable.add(function () {
  5851. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5852. });
  5853. scene.incrementRenderId();
  5854. scene.resetCachedMaterial();
  5855. texture.render(true);
  5856. texture.dispose();
  5857. if (previousCamera) {
  5858. scene.activeCamera = previousCamera;
  5859. }
  5860. camera.getProjectionMatrix(true); // Force cache refresh;
  5861. };
  5862. // XHR response validator for local file scenario
  5863. Tools.ValidateXHRData = function (xhr, dataType) {
  5864. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5865. if (dataType === void 0) { dataType = 7; }
  5866. try {
  5867. if (dataType & 1) {
  5868. if (xhr.responseText && xhr.responseText.length > 0) {
  5869. return true;
  5870. }
  5871. else if (dataType === 1) {
  5872. return false;
  5873. }
  5874. }
  5875. if (dataType & 2) {
  5876. // Check header width and height since there is no "TGA" magic number
  5877. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5878. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5879. return true;
  5880. }
  5881. else if (dataType === 2) {
  5882. return false;
  5883. }
  5884. }
  5885. if (dataType & 4) {
  5886. // Check for the "DDS" magic number
  5887. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5888. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5889. return true;
  5890. }
  5891. else {
  5892. return false;
  5893. }
  5894. }
  5895. }
  5896. catch (e) {
  5897. // Global protection
  5898. }
  5899. return false;
  5900. };
  5901. /**
  5902. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5903. * Be aware Math.random() could cause collisions, but:
  5904. * "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"
  5905. */
  5906. Tools.RandomId = function () {
  5907. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5908. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5909. return v.toString(16);
  5910. });
  5911. };
  5912. Object.defineProperty(Tools, "NoneLogLevel", {
  5913. get: function () {
  5914. return Tools._NoneLogLevel;
  5915. },
  5916. enumerable: true,
  5917. configurable: true
  5918. });
  5919. Object.defineProperty(Tools, "MessageLogLevel", {
  5920. get: function () {
  5921. return Tools._MessageLogLevel;
  5922. },
  5923. enumerable: true,
  5924. configurable: true
  5925. });
  5926. Object.defineProperty(Tools, "WarningLogLevel", {
  5927. get: function () {
  5928. return Tools._WarningLogLevel;
  5929. },
  5930. enumerable: true,
  5931. configurable: true
  5932. });
  5933. Object.defineProperty(Tools, "ErrorLogLevel", {
  5934. get: function () {
  5935. return Tools._ErrorLogLevel;
  5936. },
  5937. enumerable: true,
  5938. configurable: true
  5939. });
  5940. Object.defineProperty(Tools, "AllLogLevel", {
  5941. get: function () {
  5942. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5943. },
  5944. enumerable: true,
  5945. configurable: true
  5946. });
  5947. Tools._AddLogEntry = function (entry) {
  5948. Tools._LogCache = entry + Tools._LogCache;
  5949. if (Tools.OnNewCacheEntry) {
  5950. Tools.OnNewCacheEntry(entry);
  5951. }
  5952. };
  5953. Tools._FormatMessage = function (message) {
  5954. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5955. var date = new Date();
  5956. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5957. };
  5958. Tools._LogDisabled = function (message) {
  5959. // nothing to do
  5960. };
  5961. Tools._LogEnabled = function (message) {
  5962. var formattedMessage = Tools._FormatMessage(message);
  5963. console.log("BJS - " + formattedMessage);
  5964. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5965. Tools._AddLogEntry(entry);
  5966. };
  5967. Tools._WarnDisabled = function (message) {
  5968. // nothing to do
  5969. };
  5970. Tools._WarnEnabled = function (message) {
  5971. var formattedMessage = Tools._FormatMessage(message);
  5972. console.warn("BJS - " + formattedMessage);
  5973. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5974. Tools._AddLogEntry(entry);
  5975. };
  5976. Tools._ErrorDisabled = function (message) {
  5977. // nothing to do
  5978. };
  5979. Tools._ErrorEnabled = function (message) {
  5980. Tools.errorsCount++;
  5981. var formattedMessage = Tools._FormatMessage(message);
  5982. console.error("BJS - " + formattedMessage);
  5983. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5984. Tools._AddLogEntry(entry);
  5985. };
  5986. Object.defineProperty(Tools, "LogCache", {
  5987. get: function () {
  5988. return Tools._LogCache;
  5989. },
  5990. enumerable: true,
  5991. configurable: true
  5992. });
  5993. Tools.ClearLogCache = function () {
  5994. Tools._LogCache = "";
  5995. Tools.errorsCount = 0;
  5996. };
  5997. Object.defineProperty(Tools, "LogLevels", {
  5998. set: function (level) {
  5999. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6000. Tools.Log = Tools._LogEnabled;
  6001. }
  6002. else {
  6003. Tools.Log = Tools._LogDisabled;
  6004. }
  6005. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6006. Tools.Warn = Tools._WarnEnabled;
  6007. }
  6008. else {
  6009. Tools.Warn = Tools._WarnDisabled;
  6010. }
  6011. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6012. Tools.Error = Tools._ErrorEnabled;
  6013. }
  6014. else {
  6015. Tools.Error = Tools._ErrorDisabled;
  6016. }
  6017. },
  6018. enumerable: true,
  6019. configurable: true
  6020. });
  6021. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6022. get: function () {
  6023. return Tools._PerformanceNoneLogLevel;
  6024. },
  6025. enumerable: true,
  6026. configurable: true
  6027. });
  6028. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6029. get: function () {
  6030. return Tools._PerformanceUserMarkLogLevel;
  6031. },
  6032. enumerable: true,
  6033. configurable: true
  6034. });
  6035. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6036. get: function () {
  6037. return Tools._PerformanceConsoleLogLevel;
  6038. },
  6039. enumerable: true,
  6040. configurable: true
  6041. });
  6042. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6043. set: function (level) {
  6044. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6045. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6046. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6047. return;
  6048. }
  6049. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6050. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6051. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6052. return;
  6053. }
  6054. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6055. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6056. },
  6057. enumerable: true,
  6058. configurable: true
  6059. });
  6060. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6061. };
  6062. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6063. };
  6064. Tools._StartUserMark = function (counterName, condition) {
  6065. if (condition === void 0) { condition = true; }
  6066. if (!condition || !Tools._performance.mark) {
  6067. return;
  6068. }
  6069. Tools._performance.mark(counterName + "-Begin");
  6070. };
  6071. Tools._EndUserMark = function (counterName, condition) {
  6072. if (condition === void 0) { condition = true; }
  6073. if (!condition || !Tools._performance.mark) {
  6074. return;
  6075. }
  6076. Tools._performance.mark(counterName + "-End");
  6077. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6078. };
  6079. Tools._StartPerformanceConsole = function (counterName, condition) {
  6080. if (condition === void 0) { condition = true; }
  6081. if (!condition) {
  6082. return;
  6083. }
  6084. Tools._StartUserMark(counterName, condition);
  6085. if (console.time) {
  6086. console.time(counterName);
  6087. }
  6088. };
  6089. Tools._EndPerformanceConsole = function (counterName, condition) {
  6090. if (condition === void 0) { condition = true; }
  6091. if (!condition) {
  6092. return;
  6093. }
  6094. Tools._EndUserMark(counterName, condition);
  6095. if (console.time) {
  6096. console.timeEnd(counterName);
  6097. }
  6098. };
  6099. Object.defineProperty(Tools, "Now", {
  6100. get: function () {
  6101. if (window.performance && window.performance.now) {
  6102. return window.performance.now();
  6103. }
  6104. return new Date().getTime();
  6105. },
  6106. enumerable: true,
  6107. configurable: true
  6108. });
  6109. /**
  6110. * This method will return the name of the class used to create the instance of the given object.
  6111. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6112. * @param object the object to get the class name from
  6113. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6114. */
  6115. Tools.getClassName = function (object, isType) {
  6116. if (isType === void 0) { isType = false; }
  6117. var name = null;
  6118. if (!isType && object.getClassName) {
  6119. name = object.getClassName();
  6120. }
  6121. else {
  6122. if (object instanceof Object) {
  6123. var classObj = isType ? object : Object.getPrototypeOf(object);
  6124. name = classObj.constructor["__bjsclassName__"];
  6125. }
  6126. if (!name) {
  6127. name = typeof object;
  6128. }
  6129. }
  6130. return name;
  6131. };
  6132. Tools.first = function (array, predicate) {
  6133. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6134. var el = array_1[_i];
  6135. if (predicate(el)) {
  6136. return el;
  6137. }
  6138. }
  6139. };
  6140. /**
  6141. * This method will return the name of the full name of the class, including its owning module (if any).
  6142. * 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).
  6143. * @param object the object to get the class name from
  6144. * @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.
  6145. */
  6146. Tools.getFullClassName = function (object, isType) {
  6147. if (isType === void 0) { isType = false; }
  6148. var className = null;
  6149. var moduleName = null;
  6150. if (!isType && object.getClassName) {
  6151. className = object.getClassName();
  6152. }
  6153. else {
  6154. if (object instanceof Object) {
  6155. var classObj = isType ? object : Object.getPrototypeOf(object);
  6156. className = classObj.constructor["__bjsclassName__"];
  6157. moduleName = classObj.constructor["__bjsmoduleName__"];
  6158. }
  6159. if (!className) {
  6160. className = typeof object;
  6161. }
  6162. }
  6163. if (!className) {
  6164. return null;
  6165. }
  6166. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6167. };
  6168. /**
  6169. * 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.
  6170. * @param array
  6171. */
  6172. Tools.arrayOrStringFeeder = function (array) {
  6173. return function (index) {
  6174. if (index >= array.length) {
  6175. return null;
  6176. }
  6177. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6178. if (val && val.getHashCode) {
  6179. val = val.getHashCode();
  6180. }
  6181. if (typeof val === "string") {
  6182. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6183. }
  6184. return val;
  6185. };
  6186. };
  6187. /**
  6188. * Compute the hashCode of a stream of number
  6189. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6190. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6191. * @return the hash code computed
  6192. */
  6193. Tools.hashCodeFromStream = function (feeder) {
  6194. // Based from here: http://stackoverflow.com/a/7616484/802124
  6195. var hash = 0;
  6196. var index = 0;
  6197. var chr = feeder(index++);
  6198. while (chr != null) {
  6199. hash = ((hash << 5) - hash) + chr;
  6200. hash |= 0; // Convert to 32bit integer
  6201. chr = feeder(index++);
  6202. }
  6203. return hash;
  6204. };
  6205. return Tools;
  6206. }());
  6207. Tools.BaseUrl = "";
  6208. Tools.CorsBehavior = "anonymous";
  6209. Tools.UseFallbackTexture = true;
  6210. // Used in case of a texture loading problem
  6211. 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";
  6212. // Logs
  6213. Tools._NoneLogLevel = 0;
  6214. Tools._MessageLogLevel = 1;
  6215. Tools._WarningLogLevel = 2;
  6216. Tools._ErrorLogLevel = 4;
  6217. Tools._LogCache = "";
  6218. Tools.errorsCount = 0;
  6219. Tools.Log = Tools._LogEnabled;
  6220. Tools.Warn = Tools._WarnEnabled;
  6221. Tools.Error = Tools._ErrorEnabled;
  6222. // Performances
  6223. Tools._PerformanceNoneLogLevel = 0;
  6224. Tools._PerformanceUserMarkLogLevel = 1;
  6225. Tools._PerformanceConsoleLogLevel = 2;
  6226. Tools._performance = window.performance;
  6227. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6228. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6229. BABYLON.Tools = Tools;
  6230. /**
  6231. * This class is used to track a performance counter which is number based.
  6232. * The user has access to many properties which give statistics of different nature
  6233. *
  6234. * The implementer can track two kinds of Performance Counter: time and count
  6235. * 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.
  6236. * 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.
  6237. */
  6238. var PerfCounter = (function () {
  6239. function PerfCounter() {
  6240. this._startMonitoringTime = 0;
  6241. this._min = 0;
  6242. this._max = 0;
  6243. this._average = 0;
  6244. this._lastSecAverage = 0;
  6245. this._current = 0;
  6246. this._totalValueCount = 0;
  6247. this._totalAccumulated = 0;
  6248. this._lastSecAccumulated = 0;
  6249. this._lastSecTime = 0;
  6250. this._lastSecValueCount = 0;
  6251. }
  6252. Object.defineProperty(PerfCounter.prototype, "min", {
  6253. /**
  6254. * Returns the smallest value ever
  6255. */
  6256. get: function () {
  6257. return this._min;
  6258. },
  6259. enumerable: true,
  6260. configurable: true
  6261. });
  6262. Object.defineProperty(PerfCounter.prototype, "max", {
  6263. /**
  6264. * Returns the biggest value ever
  6265. */
  6266. get: function () {
  6267. return this._max;
  6268. },
  6269. enumerable: true,
  6270. configurable: true
  6271. });
  6272. Object.defineProperty(PerfCounter.prototype, "average", {
  6273. /**
  6274. * Returns the average value since the performance counter is running
  6275. */
  6276. get: function () {
  6277. return this._average;
  6278. },
  6279. enumerable: true,
  6280. configurable: true
  6281. });
  6282. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6283. /**
  6284. * Returns the average value of the last second the counter was monitored
  6285. */
  6286. get: function () {
  6287. return this._lastSecAverage;
  6288. },
  6289. enumerable: true,
  6290. configurable: true
  6291. });
  6292. Object.defineProperty(PerfCounter.prototype, "current", {
  6293. /**
  6294. * Returns the current value
  6295. */
  6296. get: function () {
  6297. return this._current;
  6298. },
  6299. enumerable: true,
  6300. configurable: true
  6301. });
  6302. Object.defineProperty(PerfCounter.prototype, "total", {
  6303. get: function () {
  6304. return this._totalAccumulated;
  6305. },
  6306. enumerable: true,
  6307. configurable: true
  6308. });
  6309. /**
  6310. * Call this method to start monitoring a new frame.
  6311. * 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.
  6312. */
  6313. PerfCounter.prototype.fetchNewFrame = function () {
  6314. this._totalValueCount++;
  6315. this._current = 0;
  6316. this._lastSecValueCount++;
  6317. };
  6318. /**
  6319. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6320. * @param newCount the count value to add to the monitored count
  6321. * @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.
  6322. */
  6323. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6324. if (!PerfCounter.Enabled) {
  6325. return;
  6326. }
  6327. this._current += newCount;
  6328. if (fetchResult) {
  6329. this._fetchResult();
  6330. }
  6331. };
  6332. /**
  6333. * Start monitoring this performance counter
  6334. */
  6335. PerfCounter.prototype.beginMonitoring = function () {
  6336. if (!PerfCounter.Enabled) {
  6337. return;
  6338. }
  6339. this._startMonitoringTime = Tools.Now;
  6340. };
  6341. /**
  6342. * Compute the time lapsed since the previous beginMonitoring() call.
  6343. * @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
  6344. */
  6345. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6346. if (newFrame === void 0) { newFrame = true; }
  6347. if (!PerfCounter.Enabled) {
  6348. return;
  6349. }
  6350. if (newFrame) {
  6351. this.fetchNewFrame();
  6352. }
  6353. var currentTime = Tools.Now;
  6354. this._current = currentTime - this._startMonitoringTime;
  6355. if (newFrame) {
  6356. this._fetchResult();
  6357. }
  6358. };
  6359. PerfCounter.prototype._fetchResult = function () {
  6360. this._totalAccumulated += this._current;
  6361. this._lastSecAccumulated += this._current;
  6362. // Min/Max update
  6363. this._min = Math.min(this._min, this._current);
  6364. this._max = Math.max(this._max, this._current);
  6365. this._average = this._totalAccumulated / this._totalValueCount;
  6366. // Reset last sec?
  6367. var now = Tools.Now;
  6368. if ((now - this._lastSecTime) > 1000) {
  6369. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6370. this._lastSecTime = now;
  6371. this._lastSecAccumulated = 0;
  6372. this._lastSecValueCount = 0;
  6373. }
  6374. };
  6375. return PerfCounter;
  6376. }());
  6377. PerfCounter.Enabled = true;
  6378. BABYLON.PerfCounter = PerfCounter;
  6379. /**
  6380. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6381. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6382. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6383. * @param name The name of the class, case should be preserved
  6384. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6385. */
  6386. function className(name, module) {
  6387. return function (target) {
  6388. target["__bjsclassName__"] = name;
  6389. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6390. };
  6391. }
  6392. BABYLON.className = className;
  6393. /**
  6394. * An implementation of a loop for asynchronous functions.
  6395. */
  6396. var AsyncLoop = (function () {
  6397. /**
  6398. * Constroctor.
  6399. * @param iterations the number of iterations.
  6400. * @param _fn the function to run each iteration
  6401. * @param _successCallback the callback that will be called upon succesful execution
  6402. * @param offset starting offset.
  6403. */
  6404. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6405. if (offset === void 0) { offset = 0; }
  6406. this.iterations = iterations;
  6407. this._fn = _fn;
  6408. this._successCallback = _successCallback;
  6409. this.index = offset - 1;
  6410. this._done = false;
  6411. }
  6412. /**
  6413. * Execute the next iteration. Must be called after the last iteration was finished.
  6414. */
  6415. AsyncLoop.prototype.executeNext = function () {
  6416. if (!this._done) {
  6417. if (this.index + 1 < this.iterations) {
  6418. ++this.index;
  6419. this._fn(this);
  6420. }
  6421. else {
  6422. this.breakLoop();
  6423. }
  6424. }
  6425. };
  6426. /**
  6427. * Break the loop and run the success callback.
  6428. */
  6429. AsyncLoop.prototype.breakLoop = function () {
  6430. this._done = true;
  6431. this._successCallback();
  6432. };
  6433. /**
  6434. * Helper function
  6435. */
  6436. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6437. if (offset === void 0) { offset = 0; }
  6438. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6439. loop.executeNext();
  6440. return loop;
  6441. };
  6442. /**
  6443. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6444. * @param iterations total number of iterations
  6445. * @param syncedIterations number of synchronous iterations in each async iteration.
  6446. * @param fn the function to call each iteration.
  6447. * @param callback a success call back that will be called when iterating stops.
  6448. * @param breakFunction a break condition (optional)
  6449. * @param timeout timeout settings for the setTimeout function. default - 0.
  6450. * @constructor
  6451. */
  6452. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6453. if (timeout === void 0) { timeout = 0; }
  6454. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6455. if (breakFunction && breakFunction())
  6456. loop.breakLoop();
  6457. else {
  6458. setTimeout(function () {
  6459. for (var i = 0; i < syncedIterations; ++i) {
  6460. var iteration = (loop.index * syncedIterations) + i;
  6461. if (iteration >= iterations)
  6462. break;
  6463. fn(iteration);
  6464. if (breakFunction && breakFunction()) {
  6465. loop.breakLoop();
  6466. break;
  6467. }
  6468. }
  6469. loop.executeNext();
  6470. }, timeout);
  6471. }
  6472. }, callback);
  6473. };
  6474. return AsyncLoop;
  6475. }());
  6476. BABYLON.AsyncLoop = AsyncLoop;
  6477. })(BABYLON || (BABYLON = {}));
  6478. //# sourceMappingURL=babylon.tools.js.map
  6479. var BABYLON;
  6480. (function (BABYLON) {
  6481. var Internals;
  6482. (function (Internals) {
  6483. var _AlphaState = (function () {
  6484. /**
  6485. * Initializes the state.
  6486. */
  6487. function _AlphaState() {
  6488. this._isAlphaBlendDirty = false;
  6489. this._isBlendFunctionParametersDirty = false;
  6490. this._isBlendEquationParametersDirty = false;
  6491. this._isBlendConstantsDirty = false;
  6492. this._alphaBlend = false;
  6493. this._blendFunctionParameters = new Array(4);
  6494. this._blendEquationParameters = new Array(2);
  6495. this._blendConstants = new Array(4);
  6496. this.reset();
  6497. }
  6498. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6499. get: function () {
  6500. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6501. },
  6502. enumerable: true,
  6503. configurable: true
  6504. });
  6505. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6506. get: function () {
  6507. return this._alphaBlend;
  6508. },
  6509. set: function (value) {
  6510. if (this._alphaBlend === value) {
  6511. return;
  6512. }
  6513. this._alphaBlend = value;
  6514. this._isAlphaBlendDirty = true;
  6515. },
  6516. enumerable: true,
  6517. configurable: true
  6518. });
  6519. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6520. if (this._blendConstants[0] === r &&
  6521. this._blendConstants[1] === g &&
  6522. this._blendConstants[2] === b &&
  6523. this._blendConstants[3] === a) {
  6524. return;
  6525. }
  6526. this._blendConstants[0] = r;
  6527. this._blendConstants[1] = g;
  6528. this._blendConstants[2] = b;
  6529. this._blendConstants[3] = a;
  6530. this._isBlendConstantsDirty = true;
  6531. };
  6532. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6533. if (this._blendFunctionParameters[0] === value0 &&
  6534. this._blendFunctionParameters[1] === value1 &&
  6535. this._blendFunctionParameters[2] === value2 &&
  6536. this._blendFunctionParameters[3] === value3) {
  6537. return;
  6538. }
  6539. this._blendFunctionParameters[0] = value0;
  6540. this._blendFunctionParameters[1] = value1;
  6541. this._blendFunctionParameters[2] = value2;
  6542. this._blendFunctionParameters[3] = value3;
  6543. this._isBlendFunctionParametersDirty = true;
  6544. };
  6545. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6546. if (this._blendEquationParameters[0] === rgb &&
  6547. this._blendEquationParameters[1] === alpha) {
  6548. return;
  6549. }
  6550. this._blendEquationParameters[0] = rgb;
  6551. this._blendEquationParameters[1] = alpha;
  6552. this._isBlendEquationParametersDirty = true;
  6553. };
  6554. _AlphaState.prototype.reset = function () {
  6555. this._alphaBlend = false;
  6556. this._blendFunctionParameters[0] = null;
  6557. this._blendFunctionParameters[1] = null;
  6558. this._blendFunctionParameters[2] = null;
  6559. this._blendFunctionParameters[3] = null;
  6560. this._blendEquationParameters[0] = null;
  6561. this._blendEquationParameters[1] = null;
  6562. this._blendConstants[0] = null;
  6563. this._blendConstants[1] = null;
  6564. this._blendConstants[2] = null;
  6565. this._blendConstants[3] = null;
  6566. this._isAlphaBlendDirty = true;
  6567. this._isBlendFunctionParametersDirty = false;
  6568. this._isBlendEquationParametersDirty = false;
  6569. this._isBlendConstantsDirty = false;
  6570. };
  6571. _AlphaState.prototype.apply = function (gl) {
  6572. if (!this.isDirty) {
  6573. return;
  6574. }
  6575. // Alpha blend
  6576. if (this._isAlphaBlendDirty) {
  6577. if (this._alphaBlend) {
  6578. gl.enable(gl.BLEND);
  6579. }
  6580. else {
  6581. gl.disable(gl.BLEND);
  6582. }
  6583. this._isAlphaBlendDirty = false;
  6584. }
  6585. // Alpha function
  6586. if (this._isBlendFunctionParametersDirty) {
  6587. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6588. this._isBlendFunctionParametersDirty = false;
  6589. }
  6590. // Alpha equation
  6591. if (this._isBlendEquationParametersDirty) {
  6592. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6593. this._isBlendEquationParametersDirty = false;
  6594. }
  6595. // Constants
  6596. if (this._isBlendConstantsDirty) {
  6597. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6598. this._isBlendConstantsDirty = false;
  6599. }
  6600. };
  6601. return _AlphaState;
  6602. }());
  6603. Internals._AlphaState = _AlphaState;
  6604. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6605. })(BABYLON || (BABYLON = {}));
  6606. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6607. var BABYLON;
  6608. (function (BABYLON) {
  6609. var Internals;
  6610. (function (Internals) {
  6611. var _DepthCullingState = (function () {
  6612. /**
  6613. * Initializes the state.
  6614. */
  6615. function _DepthCullingState() {
  6616. this._isDepthTestDirty = false;
  6617. this._isDepthMaskDirty = false;
  6618. this._isDepthFuncDirty = false;
  6619. this._isCullFaceDirty = false;
  6620. this._isCullDirty = false;
  6621. this._isZOffsetDirty = false;
  6622. this.reset();
  6623. }
  6624. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6625. get: function () {
  6626. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6627. },
  6628. enumerable: true,
  6629. configurable: true
  6630. });
  6631. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6632. get: function () {
  6633. return this._zOffset;
  6634. },
  6635. set: function (value) {
  6636. if (this._zOffset === value) {
  6637. return;
  6638. }
  6639. this._zOffset = value;
  6640. this._isZOffsetDirty = true;
  6641. },
  6642. enumerable: true,
  6643. configurable: true
  6644. });
  6645. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6646. get: function () {
  6647. return this._cullFace;
  6648. },
  6649. set: function (value) {
  6650. if (this._cullFace === value) {
  6651. return;
  6652. }
  6653. this._cullFace = value;
  6654. this._isCullFaceDirty = true;
  6655. },
  6656. enumerable: true,
  6657. configurable: true
  6658. });
  6659. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6660. get: function () {
  6661. return this._cull;
  6662. },
  6663. set: function (value) {
  6664. if (this._cull === value) {
  6665. return;
  6666. }
  6667. this._cull = value;
  6668. this._isCullDirty = true;
  6669. },
  6670. enumerable: true,
  6671. configurable: true
  6672. });
  6673. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6674. get: function () {
  6675. return this._depthFunc;
  6676. },
  6677. set: function (value) {
  6678. if (this._depthFunc === value) {
  6679. return;
  6680. }
  6681. this._depthFunc = value;
  6682. this._isDepthFuncDirty = true;
  6683. },
  6684. enumerable: true,
  6685. configurable: true
  6686. });
  6687. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6688. get: function () {
  6689. return this._depthMask;
  6690. },
  6691. set: function (value) {
  6692. if (this._depthMask === value) {
  6693. return;
  6694. }
  6695. this._depthMask = value;
  6696. this._isDepthMaskDirty = true;
  6697. },
  6698. enumerable: true,
  6699. configurable: true
  6700. });
  6701. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6702. get: function () {
  6703. return this._depthTest;
  6704. },
  6705. set: function (value) {
  6706. if (this._depthTest === value) {
  6707. return;
  6708. }
  6709. this._depthTest = value;
  6710. this._isDepthTestDirty = true;
  6711. },
  6712. enumerable: true,
  6713. configurable: true
  6714. });
  6715. _DepthCullingState.prototype.reset = function () {
  6716. this._depthMask = true;
  6717. this._depthTest = true;
  6718. this._depthFunc = null;
  6719. this._cullFace = null;
  6720. this._cull = null;
  6721. this._zOffset = 0;
  6722. this._isDepthTestDirty = true;
  6723. this._isDepthMaskDirty = true;
  6724. this._isDepthFuncDirty = false;
  6725. this._isCullFaceDirty = false;
  6726. this._isCullDirty = false;
  6727. this._isZOffsetDirty = false;
  6728. };
  6729. _DepthCullingState.prototype.apply = function (gl) {
  6730. if (!this.isDirty) {
  6731. return;
  6732. }
  6733. // Cull
  6734. if (this._isCullDirty) {
  6735. if (this.cull) {
  6736. gl.enable(gl.CULL_FACE);
  6737. }
  6738. else {
  6739. gl.disable(gl.CULL_FACE);
  6740. }
  6741. this._isCullDirty = false;
  6742. }
  6743. // Cull face
  6744. if (this._isCullFaceDirty) {
  6745. gl.cullFace(this.cullFace);
  6746. this._isCullFaceDirty = false;
  6747. }
  6748. // Depth mask
  6749. if (this._isDepthMaskDirty) {
  6750. gl.depthMask(this.depthMask);
  6751. this._isDepthMaskDirty = false;
  6752. }
  6753. // Depth test
  6754. if (this._isDepthTestDirty) {
  6755. if (this.depthTest) {
  6756. gl.enable(gl.DEPTH_TEST);
  6757. }
  6758. else {
  6759. gl.disable(gl.DEPTH_TEST);
  6760. }
  6761. this._isDepthTestDirty = false;
  6762. }
  6763. // Depth func
  6764. if (this._isDepthFuncDirty) {
  6765. gl.depthFunc(this.depthFunc);
  6766. this._isDepthFuncDirty = false;
  6767. }
  6768. // zOffset
  6769. if (this._isZOffsetDirty) {
  6770. if (this.zOffset) {
  6771. gl.enable(gl.POLYGON_OFFSET_FILL);
  6772. gl.polygonOffset(this.zOffset, 0);
  6773. }
  6774. else {
  6775. gl.disable(gl.POLYGON_OFFSET_FILL);
  6776. }
  6777. this._isZOffsetDirty = false;
  6778. }
  6779. };
  6780. return _DepthCullingState;
  6781. }());
  6782. Internals._DepthCullingState = _DepthCullingState;
  6783. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6784. })(BABYLON || (BABYLON = {}));
  6785. //# sourceMappingURL=babylon.depthCullingState.js.map
  6786. var BABYLON;
  6787. (function (BABYLON) {
  6788. var Internals;
  6789. (function (Internals) {
  6790. var _StencilState = (function () {
  6791. function _StencilState() {
  6792. this._isStencilTestDirty = false;
  6793. this._isStencilMaskDirty = false;
  6794. this._isStencilFuncDirty = false;
  6795. this._isStencilOpDirty = false;
  6796. this.reset();
  6797. }
  6798. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6799. get: function () {
  6800. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6801. },
  6802. enumerable: true,
  6803. configurable: true
  6804. });
  6805. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6806. get: function () {
  6807. return this._stencilFunc;
  6808. },
  6809. set: function (value) {
  6810. if (this._stencilFunc === value) {
  6811. return;
  6812. }
  6813. this._stencilFunc = value;
  6814. this._isStencilFuncDirty = true;
  6815. },
  6816. enumerable: true,
  6817. configurable: true
  6818. });
  6819. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6820. get: function () {
  6821. return this._stencilFuncRef;
  6822. },
  6823. set: function (value) {
  6824. if (this._stencilFuncRef === value) {
  6825. return;
  6826. }
  6827. this._stencilFuncRef = value;
  6828. this._isStencilFuncDirty = true;
  6829. },
  6830. enumerable: true,
  6831. configurable: true
  6832. });
  6833. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6834. get: function () {
  6835. return this._stencilFuncMask;
  6836. },
  6837. set: function (value) {
  6838. if (this._stencilFuncMask === value) {
  6839. return;
  6840. }
  6841. this._stencilFuncMask = value;
  6842. this._isStencilFuncDirty = true;
  6843. },
  6844. enumerable: true,
  6845. configurable: true
  6846. });
  6847. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6848. get: function () {
  6849. return this._stencilOpStencilFail;
  6850. },
  6851. set: function (value) {
  6852. if (this._stencilOpStencilFail === value) {
  6853. return;
  6854. }
  6855. this._stencilOpStencilFail = value;
  6856. this._isStencilOpDirty = true;
  6857. },
  6858. enumerable: true,
  6859. configurable: true
  6860. });
  6861. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6862. get: function () {
  6863. return this._stencilOpDepthFail;
  6864. },
  6865. set: function (value) {
  6866. if (this._stencilOpDepthFail === value) {
  6867. return;
  6868. }
  6869. this._stencilOpDepthFail = value;
  6870. this._isStencilOpDirty = true;
  6871. },
  6872. enumerable: true,
  6873. configurable: true
  6874. });
  6875. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6876. get: function () {
  6877. return this._stencilOpStencilDepthPass;
  6878. },
  6879. set: function (value) {
  6880. if (this._stencilOpStencilDepthPass === value) {
  6881. return;
  6882. }
  6883. this._stencilOpStencilDepthPass = value;
  6884. this._isStencilOpDirty = true;
  6885. },
  6886. enumerable: true,
  6887. configurable: true
  6888. });
  6889. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6890. get: function () {
  6891. return this._stencilMask;
  6892. },
  6893. set: function (value) {
  6894. if (this._stencilMask === value) {
  6895. return;
  6896. }
  6897. this._stencilMask = value;
  6898. this._isStencilMaskDirty = true;
  6899. },
  6900. enumerable: true,
  6901. configurable: true
  6902. });
  6903. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6904. get: function () {
  6905. return this._stencilTest;
  6906. },
  6907. set: function (value) {
  6908. if (this._stencilTest === value) {
  6909. return;
  6910. }
  6911. this._stencilTest = value;
  6912. this._isStencilTestDirty = true;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. _StencilState.prototype.reset = function () {
  6918. this._stencilTest = false;
  6919. this._stencilMask = 0xFF;
  6920. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6921. this._stencilFuncRef = 1;
  6922. this._stencilFuncMask = 0xFF;
  6923. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6924. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6925. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6926. this._isStencilTestDirty = true;
  6927. this._isStencilMaskDirty = true;
  6928. this._isStencilFuncDirty = true;
  6929. this._isStencilOpDirty = true;
  6930. };
  6931. _StencilState.prototype.apply = function (gl) {
  6932. if (!this.isDirty) {
  6933. return;
  6934. }
  6935. // Stencil test
  6936. if (this._isStencilTestDirty) {
  6937. if (this.stencilTest) {
  6938. gl.enable(gl.STENCIL_TEST);
  6939. }
  6940. else {
  6941. gl.disable(gl.STENCIL_TEST);
  6942. }
  6943. this._isStencilTestDirty = false;
  6944. }
  6945. // Stencil mask
  6946. if (this._isStencilMaskDirty) {
  6947. gl.stencilMask(this.stencilMask);
  6948. this._isStencilMaskDirty = false;
  6949. }
  6950. // Stencil func
  6951. if (this._isStencilFuncDirty) {
  6952. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6953. this._isStencilFuncDirty = false;
  6954. }
  6955. // Stencil op
  6956. if (this._isStencilOpDirty) {
  6957. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6958. this._isStencilOpDirty = false;
  6959. }
  6960. };
  6961. return _StencilState;
  6962. }());
  6963. Internals._StencilState = _StencilState;
  6964. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6965. })(BABYLON || (BABYLON = {}));
  6966. //# sourceMappingURL=babylon.stencilState.js.map
  6967. var BABYLON;
  6968. (function (BABYLON) {
  6969. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6970. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6971. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6972. gl.compileShader(shader);
  6973. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6974. throw new Error(gl.getShaderInfoLog(shader));
  6975. }
  6976. return shader;
  6977. };
  6978. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6979. var magFilter = gl.NEAREST;
  6980. var minFilter = gl.NEAREST;
  6981. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6982. magFilter = gl.LINEAR;
  6983. if (generateMipMaps) {
  6984. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6985. }
  6986. else {
  6987. minFilter = gl.LINEAR;
  6988. }
  6989. }
  6990. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6991. magFilter = gl.LINEAR;
  6992. if (generateMipMaps) {
  6993. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6994. }
  6995. else {
  6996. minFilter = gl.LINEAR;
  6997. }
  6998. }
  6999. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7000. magFilter = gl.NEAREST;
  7001. if (generateMipMaps) {
  7002. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7003. }
  7004. else {
  7005. minFilter = gl.NEAREST;
  7006. }
  7007. }
  7008. return {
  7009. min: minFilter,
  7010. mag: magFilter
  7011. };
  7012. };
  7013. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7015. var engine = scene.getEngine();
  7016. if (!engine) {
  7017. return;
  7018. }
  7019. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7020. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7021. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7022. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7023. texture._baseWidth = width;
  7024. texture._baseHeight = height;
  7025. texture._width = potWidth;
  7026. texture._height = potHeight;
  7027. texture.isReady = true;
  7028. processFunction(potWidth, potHeight);
  7029. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7032. if (!noMipmap && !isCompressed) {
  7033. gl.generateMipmap(gl.TEXTURE_2D);
  7034. }
  7035. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7036. engine.resetTextureCache();
  7037. scene._removePendingData(texture);
  7038. texture.onLoadedCallbacks.forEach(function (callback) {
  7039. callback();
  7040. });
  7041. texture.onLoadedCallbacks = [];
  7042. };
  7043. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7044. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7045. var img;
  7046. var onload = function () {
  7047. loadedImages[index] = img;
  7048. loadedImages._internalCount++;
  7049. scene._removePendingData(img);
  7050. if (loadedImages._internalCount === 6) {
  7051. onfinish(loadedImages);
  7052. }
  7053. };
  7054. var onerror = function () {
  7055. scene._removePendingData(img);
  7056. if (onErrorCallBack) {
  7057. onErrorCallBack();
  7058. }
  7059. };
  7060. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7061. scene._addPendingData(img);
  7062. };
  7063. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7064. if (onError === void 0) { onError = null; }
  7065. var loadedImages = [];
  7066. loadedImages._internalCount = 0;
  7067. for (var index = 0; index < 6; index++) {
  7068. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7069. }
  7070. };
  7071. var InstancingAttributeInfo = (function () {
  7072. function InstancingAttributeInfo() {
  7073. }
  7074. return InstancingAttributeInfo;
  7075. }());
  7076. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7077. var EngineCapabilities = (function () {
  7078. function EngineCapabilities() {
  7079. }
  7080. return EngineCapabilities;
  7081. }());
  7082. BABYLON.EngineCapabilities = EngineCapabilities;
  7083. /**
  7084. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7085. */
  7086. var Engine = (function () {
  7087. /**
  7088. * @constructor
  7089. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7090. * @param {boolean} [antialias] - enable antialias
  7091. * @param options - further options to be sent to the getContext function
  7092. */
  7093. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7094. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7095. var _this = this;
  7096. // Public members
  7097. this.isFullscreen = false;
  7098. this.isPointerLock = false;
  7099. this.cullBackFaces = true;
  7100. this.renderEvenInBackground = true;
  7101. this.preventCacheWipeBetweenFrames = false;
  7102. // To enable/disable IDB support and avoid XHR on .manifest
  7103. this.enableOfflineSupport = BABYLON.Database;
  7104. this.scenes = new Array();
  7105. // Observables
  7106. /**
  7107. * Observable event triggered each time the rendering canvas is resized
  7108. */
  7109. this.onResizeObservable = new BABYLON.Observable();
  7110. /**
  7111. * Observable event triggered each time the canvas lost focus
  7112. */
  7113. this.onCanvasBlurObservable = new BABYLON.Observable();
  7114. this._windowIsBackground = false;
  7115. this._webGLVersion = 1.0;
  7116. this._badOS = false;
  7117. this._drawCalls = new BABYLON.PerfCounter();
  7118. this._renderingQueueLaunched = false;
  7119. this._activeRenderLoops = [];
  7120. // FPS
  7121. this.fpsRange = 60;
  7122. this.previousFramesDuration = [];
  7123. this.fps = 60;
  7124. this.deltaTime = 0;
  7125. // States
  7126. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7127. this._stencilState = new BABYLON.Internals._StencilState();
  7128. this._alphaState = new BABYLON.Internals._AlphaState();
  7129. this._alphaMode = Engine.ALPHA_DISABLE;
  7130. // Cache
  7131. this._loadedTexturesCache = new Array();
  7132. this._maxTextureChannels = 16;
  7133. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7134. this._compiledEffects = {};
  7135. this._vertexAttribArraysEnabled = [];
  7136. this._uintIndicesCurrentlySet = false;
  7137. this._currentBoundBuffer = new Array();
  7138. this._currentBufferPointers = [];
  7139. this._currentInstanceLocations = new Array();
  7140. this._currentInstanceBuffers = new Array();
  7141. this._vaoRecordInProgress = false;
  7142. this._mustWipeVertexAttributes = false;
  7143. // Hardware supported Compressed Textures
  7144. this._texturesSupported = new Array();
  7145. this._onVRFullScreenTriggered = function () {
  7146. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7147. //get the old size before we change
  7148. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7149. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7150. //get the width and height, change the render size
  7151. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7152. var width, height;
  7153. _this.setHardwareScalingLevel(1);
  7154. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7155. }
  7156. else {
  7157. //When the specs are implemented, need to uncomment this.
  7158. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7159. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7160. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7161. _this._vrDisplayEnabled = undefined;
  7162. }
  7163. };
  7164. this._renderingCanvas = canvas;
  7165. Engine.Instances.push(this);
  7166. options = options || {};
  7167. if (antialias != null) {
  7168. options.antialias = antialias;
  7169. }
  7170. if (options.preserveDrawingBuffer === undefined) {
  7171. options.preserveDrawingBuffer = false;
  7172. }
  7173. if (options.audioEngine === undefined) {
  7174. options.audioEngine = true;
  7175. }
  7176. if (options.stencil === undefined) {
  7177. options.stencil = true;
  7178. }
  7179. // GL
  7180. if (!options.disableWebGL2Support) {
  7181. try {
  7182. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7183. if (this._gl) {
  7184. this._webGLVersion = 2.0;
  7185. }
  7186. }
  7187. catch (e) {
  7188. // Do nothing
  7189. }
  7190. }
  7191. if (!this._gl) {
  7192. if (!canvas) {
  7193. throw new Error("The provided canvas is null or undefined.");
  7194. }
  7195. try {
  7196. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7197. }
  7198. catch (e) {
  7199. throw new Error("WebGL not supported");
  7200. }
  7201. }
  7202. if (!this._gl) {
  7203. throw new Error("WebGL not supported");
  7204. }
  7205. this._onBlur = function () {
  7206. _this._windowIsBackground = true;
  7207. };
  7208. this._onFocus = function () {
  7209. _this._windowIsBackground = false;
  7210. };
  7211. this._onCanvasBlur = function () {
  7212. _this.onCanvasBlurObservable.notifyObservers(_this);
  7213. };
  7214. window.addEventListener("blur", this._onBlur);
  7215. window.addEventListener("focus", this._onFocus);
  7216. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7217. // Viewport
  7218. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7219. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7220. this.resize();
  7221. // Caps
  7222. this._isStencilEnable = options.stencil;
  7223. this._caps = new EngineCapabilities();
  7224. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7225. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7226. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7227. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7228. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7229. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7230. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7231. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7232. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7233. // Infos
  7234. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7235. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7236. if (rendererInfo != null) {
  7237. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7238. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7239. }
  7240. if (!this._glVendor) {
  7241. this._glVendor = "Unknown vendor";
  7242. }
  7243. if (!this._glRenderer) {
  7244. this._glRenderer = "Unknown renderer";
  7245. }
  7246. // Extensions
  7247. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7248. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7249. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7250. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7251. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7252. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7253. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7254. 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');
  7255. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7256. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7257. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7258. this._caps.highPrecisionShaderSupported = true;
  7259. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7260. // Checks if some of the format renders first to allow the use of webgl inspector.
  7261. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7262. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7263. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7264. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7265. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7266. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7267. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7268. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7269. // Vertex array object
  7270. if (this._webGLVersion > 1) {
  7271. this._caps.vertexArrayObject = true;
  7272. }
  7273. else {
  7274. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7275. if (vertexArrayObjectExtension != null) {
  7276. this._caps.vertexArrayObject = true;
  7277. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7278. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7279. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7280. }
  7281. else {
  7282. this._caps.vertexArrayObject = false;
  7283. }
  7284. }
  7285. // Instances count
  7286. if (this._webGLVersion > 1) {
  7287. this._caps.instancedArrays = true;
  7288. }
  7289. else {
  7290. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7291. if (instanceExtension != null) {
  7292. this._caps.instancedArrays = true;
  7293. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7294. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7295. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7296. }
  7297. else {
  7298. this._caps.instancedArrays = false;
  7299. }
  7300. }
  7301. // Intelligently add supported compressed formats in order to check for.
  7302. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7303. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7304. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7305. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7306. if (this._caps.astc)
  7307. this.texturesSupported.push('-astc.ktx');
  7308. if (this._caps.s3tc)
  7309. this.texturesSupported.push('-dxt.ktx');
  7310. if (this._caps.pvrtc)
  7311. this.texturesSupported.push('-pvrtc.ktx');
  7312. if (this._caps.etc2)
  7313. this.texturesSupported.push('-etc2.ktx');
  7314. if (this._caps.etc1)
  7315. this.texturesSupported.push('-etc1.ktx');
  7316. if (this._gl.getShaderPrecisionFormat) {
  7317. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7318. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7319. }
  7320. // Depth buffer
  7321. this.setDepthBuffer(true);
  7322. this.setDepthFunctionToLessOrEqual();
  7323. this.setDepthWrite(true);
  7324. // Fullscreen
  7325. this._onFullscreenChange = function () {
  7326. if (document.fullscreen !== undefined) {
  7327. _this.isFullscreen = document.fullscreen;
  7328. }
  7329. else if (document.mozFullScreen !== undefined) {
  7330. _this.isFullscreen = document.mozFullScreen;
  7331. }
  7332. else if (document.webkitIsFullScreen !== undefined) {
  7333. _this.isFullscreen = document.webkitIsFullScreen;
  7334. }
  7335. else if (document.msIsFullScreen !== undefined) {
  7336. _this.isFullscreen = document.msIsFullScreen;
  7337. }
  7338. // Pointer lock
  7339. if (_this.isFullscreen && _this._pointerLockRequested) {
  7340. canvas.requestPointerLock = canvas.requestPointerLock ||
  7341. canvas.msRequestPointerLock ||
  7342. canvas.mozRequestPointerLock ||
  7343. canvas.webkitRequestPointerLock;
  7344. if (canvas.requestPointerLock) {
  7345. canvas.requestPointerLock();
  7346. }
  7347. }
  7348. };
  7349. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7350. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7351. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7352. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7353. // Pointer lock
  7354. this._onPointerLockChange = function () {
  7355. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7356. document.webkitPointerLockElement === canvas ||
  7357. document.msPointerLockElement === canvas ||
  7358. document.pointerLockElement === canvas);
  7359. };
  7360. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7361. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7362. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7363. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7364. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7365. Engine.audioEngine = new BABYLON.AudioEngine();
  7366. }
  7367. //Load WebVR Devices
  7368. if (options.autoEnableWebVR) {
  7369. this.initWebVR();
  7370. }
  7371. //Detect if we are running on a faulty buggy OS.
  7372. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7373. //ua sniffing is the tool of the devil.
  7374. this._badOS = regexp.test(navigator.userAgent);
  7375. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7376. }
  7377. Object.defineProperty(Engine, "LastCreatedEngine", {
  7378. get: function () {
  7379. if (Engine.Instances.length === 0) {
  7380. return null;
  7381. }
  7382. return Engine.Instances[Engine.Instances.length - 1];
  7383. },
  7384. enumerable: true,
  7385. configurable: true
  7386. });
  7387. Object.defineProperty(Engine, "LastCreatedScene", {
  7388. get: function () {
  7389. var lastCreatedEngine = Engine.LastCreatedEngine;
  7390. if (!lastCreatedEngine) {
  7391. return null;
  7392. }
  7393. if (lastCreatedEngine.scenes.length === 0) {
  7394. return null;
  7395. }
  7396. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7397. },
  7398. enumerable: true,
  7399. configurable: true
  7400. });
  7401. /**
  7402. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7403. */
  7404. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7405. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7406. var engine = Engine.Instances[engineIndex];
  7407. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7408. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7409. }
  7410. }
  7411. };
  7412. Object.defineProperty(Engine, "NEVER", {
  7413. get: function () {
  7414. return Engine._NEVER;
  7415. },
  7416. enumerable: true,
  7417. configurable: true
  7418. });
  7419. Object.defineProperty(Engine, "ALWAYS", {
  7420. get: function () {
  7421. return Engine._ALWAYS;
  7422. },
  7423. enumerable: true,
  7424. configurable: true
  7425. });
  7426. Object.defineProperty(Engine, "LESS", {
  7427. get: function () {
  7428. return Engine._LESS;
  7429. },
  7430. enumerable: true,
  7431. configurable: true
  7432. });
  7433. Object.defineProperty(Engine, "EQUAL", {
  7434. get: function () {
  7435. return Engine._EQUAL;
  7436. },
  7437. enumerable: true,
  7438. configurable: true
  7439. });
  7440. Object.defineProperty(Engine, "LEQUAL", {
  7441. get: function () {
  7442. return Engine._LEQUAL;
  7443. },
  7444. enumerable: true,
  7445. configurable: true
  7446. });
  7447. Object.defineProperty(Engine, "GREATER", {
  7448. get: function () {
  7449. return Engine._GREATER;
  7450. },
  7451. enumerable: true,
  7452. configurable: true
  7453. });
  7454. Object.defineProperty(Engine, "GEQUAL", {
  7455. get: function () {
  7456. return Engine._GEQUAL;
  7457. },
  7458. enumerable: true,
  7459. configurable: true
  7460. });
  7461. Object.defineProperty(Engine, "NOTEQUAL", {
  7462. get: function () {
  7463. return Engine._NOTEQUAL;
  7464. },
  7465. enumerable: true,
  7466. configurable: true
  7467. });
  7468. Object.defineProperty(Engine, "KEEP", {
  7469. get: function () {
  7470. return Engine._KEEP;
  7471. },
  7472. enumerable: true,
  7473. configurable: true
  7474. });
  7475. Object.defineProperty(Engine, "REPLACE", {
  7476. get: function () {
  7477. return Engine._REPLACE;
  7478. },
  7479. enumerable: true,
  7480. configurable: true
  7481. });
  7482. Object.defineProperty(Engine, "INCR", {
  7483. get: function () {
  7484. return Engine._INCR;
  7485. },
  7486. enumerable: true,
  7487. configurable: true
  7488. });
  7489. Object.defineProperty(Engine, "DECR", {
  7490. get: function () {
  7491. return Engine._DECR;
  7492. },
  7493. enumerable: true,
  7494. configurable: true
  7495. });
  7496. Object.defineProperty(Engine, "INVERT", {
  7497. get: function () {
  7498. return Engine._INVERT;
  7499. },
  7500. enumerable: true,
  7501. configurable: true
  7502. });
  7503. Object.defineProperty(Engine, "INCR_WRAP", {
  7504. get: function () {
  7505. return Engine._INCR_WRAP;
  7506. },
  7507. enumerable: true,
  7508. configurable: true
  7509. });
  7510. Object.defineProperty(Engine, "DECR_WRAP", {
  7511. get: function () {
  7512. return Engine._DECR_WRAP;
  7513. },
  7514. enumerable: true,
  7515. configurable: true
  7516. });
  7517. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7518. get: function () {
  7519. return Engine._ALPHA_DISABLE;
  7520. },
  7521. enumerable: true,
  7522. configurable: true
  7523. });
  7524. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7525. get: function () {
  7526. return Engine._ALPHA_ONEONE;
  7527. },
  7528. enumerable: true,
  7529. configurable: true
  7530. });
  7531. Object.defineProperty(Engine, "ALPHA_ADD", {
  7532. get: function () {
  7533. return Engine._ALPHA_ADD;
  7534. },
  7535. enumerable: true,
  7536. configurable: true
  7537. });
  7538. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7539. get: function () {
  7540. return Engine._ALPHA_COMBINE;
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7546. get: function () {
  7547. return Engine._ALPHA_SUBTRACT;
  7548. },
  7549. enumerable: true,
  7550. configurable: true
  7551. });
  7552. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7553. get: function () {
  7554. return Engine._ALPHA_MULTIPLY;
  7555. },
  7556. enumerable: true,
  7557. configurable: true
  7558. });
  7559. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7560. get: function () {
  7561. return Engine._ALPHA_MAXIMIZED;
  7562. },
  7563. enumerable: true,
  7564. configurable: true
  7565. });
  7566. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7567. get: function () {
  7568. return Engine._ALPHA_PREMULTIPLIED;
  7569. },
  7570. enumerable: true,
  7571. configurable: true
  7572. });
  7573. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7574. get: function () {
  7575. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7576. },
  7577. enumerable: true,
  7578. configurable: true
  7579. });
  7580. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7581. get: function () {
  7582. return Engine._ALPHA_INTERPOLATE;
  7583. },
  7584. enumerable: true,
  7585. configurable: true
  7586. });
  7587. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7588. get: function () {
  7589. return Engine._ALPHA_SCREENMODE;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7595. get: function () {
  7596. return Engine._DELAYLOADSTATE_NONE;
  7597. },
  7598. enumerable: true,
  7599. configurable: true
  7600. });
  7601. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7602. get: function () {
  7603. return Engine._DELAYLOADSTATE_LOADED;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7609. get: function () {
  7610. return Engine._DELAYLOADSTATE_LOADING;
  7611. },
  7612. enumerable: true,
  7613. configurable: true
  7614. });
  7615. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7616. get: function () {
  7617. return Engine._DELAYLOADSTATE_NOTLOADED;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7623. get: function () {
  7624. return Engine._TEXTUREFORMAT_ALPHA;
  7625. },
  7626. enumerable: true,
  7627. configurable: true
  7628. });
  7629. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7630. get: function () {
  7631. return Engine._TEXTUREFORMAT_LUMINANCE;
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7637. get: function () {
  7638. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7639. },
  7640. enumerable: true,
  7641. configurable: true
  7642. });
  7643. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7644. get: function () {
  7645. return Engine._TEXTUREFORMAT_RGB;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7651. get: function () {
  7652. return Engine._TEXTUREFORMAT_RGBA;
  7653. },
  7654. enumerable: true,
  7655. configurable: true
  7656. });
  7657. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7658. get: function () {
  7659. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7665. get: function () {
  7666. return Engine._TEXTURETYPE_FLOAT;
  7667. },
  7668. enumerable: true,
  7669. configurable: true
  7670. });
  7671. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7672. get: function () {
  7673. return Engine._TEXTURETYPE_HALF_FLOAT;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(Engine, "Version", {
  7679. get: function () {
  7680. return "3.0-beta";
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7686. get: function () {
  7687. return this._texturesSupported;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7693. get: function () {
  7694. return this._textureFormatInUse;
  7695. },
  7696. enumerable: true,
  7697. configurable: true
  7698. });
  7699. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7700. // Empty texture
  7701. get: function () {
  7702. if (!this._emptyTexture) {
  7703. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7704. }
  7705. return this._emptyTexture;
  7706. },
  7707. enumerable: true,
  7708. configurable: true
  7709. });
  7710. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7711. get: function () {
  7712. if (!this._emptyCubeTexture) {
  7713. var faceData = new Uint8Array(4);
  7714. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7715. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7716. }
  7717. return this._emptyCubeTexture;
  7718. },
  7719. enumerable: true,
  7720. configurable: true
  7721. });
  7722. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7723. get: function () {
  7724. return this._webGLVersion;
  7725. },
  7726. enumerable: true,
  7727. configurable: true
  7728. });
  7729. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7730. /**
  7731. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7732. */
  7733. get: function () {
  7734. return this._isStencilEnable;
  7735. },
  7736. enumerable: true,
  7737. configurable: true
  7738. });
  7739. Engine.prototype._prepareWorkingCanvas = function () {
  7740. if (this._workingCanvas) {
  7741. return;
  7742. }
  7743. this._workingCanvas = document.createElement("canvas");
  7744. this._workingContext = this._workingCanvas.getContext("2d");
  7745. };
  7746. Engine.prototype.resetTextureCache = function () {
  7747. for (var index = 0; index < this._maxTextureChannels; index++) {
  7748. this._activeTexturesCache[index] = null;
  7749. }
  7750. };
  7751. Engine.prototype.getGlInfo = function () {
  7752. return {
  7753. vendor: this._glVendor,
  7754. renderer: this._glRenderer,
  7755. version: this._glVersion
  7756. };
  7757. };
  7758. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7759. if (useScreen === void 0) { useScreen = false; }
  7760. var viewport = camera.viewport;
  7761. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7762. };
  7763. Engine.prototype.getRenderWidth = function (useScreen) {
  7764. if (useScreen === void 0) { useScreen = false; }
  7765. if (!useScreen && this._currentRenderTarget) {
  7766. return this._currentRenderTarget._width;
  7767. }
  7768. return this._renderingCanvas.width;
  7769. };
  7770. Engine.prototype.getRenderHeight = function (useScreen) {
  7771. if (useScreen === void 0) { useScreen = false; }
  7772. if (!useScreen && this._currentRenderTarget) {
  7773. return this._currentRenderTarget._height;
  7774. }
  7775. return this._renderingCanvas.height;
  7776. };
  7777. Engine.prototype.getRenderingCanvas = function () {
  7778. return this._renderingCanvas;
  7779. };
  7780. Engine.prototype.getRenderingCanvasClientRect = function () {
  7781. return this._renderingCanvas.getBoundingClientRect();
  7782. };
  7783. Engine.prototype.setHardwareScalingLevel = function (level) {
  7784. this._hardwareScalingLevel = level;
  7785. this.resize();
  7786. };
  7787. Engine.prototype.getHardwareScalingLevel = function () {
  7788. return this._hardwareScalingLevel;
  7789. };
  7790. Engine.prototype.getLoadedTexturesCache = function () {
  7791. return this._loadedTexturesCache;
  7792. };
  7793. Engine.prototype.getCaps = function () {
  7794. return this._caps;
  7795. };
  7796. Object.defineProperty(Engine.prototype, "drawCalls", {
  7797. get: function () {
  7798. return this._drawCalls.current;
  7799. },
  7800. enumerable: true,
  7801. configurable: true
  7802. });
  7803. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7804. get: function () {
  7805. return this._drawCalls;
  7806. },
  7807. enumerable: true,
  7808. configurable: true
  7809. });
  7810. Engine.prototype.getDepthFunction = function () {
  7811. return this._depthCullingState.depthFunc;
  7812. };
  7813. Engine.prototype.setDepthFunction = function (depthFunc) {
  7814. this._depthCullingState.depthFunc = depthFunc;
  7815. };
  7816. Engine.prototype.setDepthFunctionToGreater = function () {
  7817. this._depthCullingState.depthFunc = this._gl.GREATER;
  7818. };
  7819. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7820. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7821. };
  7822. Engine.prototype.setDepthFunctionToLess = function () {
  7823. this._depthCullingState.depthFunc = this._gl.LESS;
  7824. };
  7825. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7826. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7827. };
  7828. Engine.prototype.getStencilBuffer = function () {
  7829. return this._stencilState.stencilTest;
  7830. };
  7831. Engine.prototype.setStencilBuffer = function (enable) {
  7832. this._stencilState.stencilTest = enable;
  7833. };
  7834. Engine.prototype.getStencilMask = function () {
  7835. return this._stencilState.stencilMask;
  7836. };
  7837. Engine.prototype.setStencilMask = function (mask) {
  7838. this._stencilState.stencilMask = mask;
  7839. };
  7840. Engine.prototype.getStencilFunction = function () {
  7841. return this._stencilState.stencilFunc;
  7842. };
  7843. Engine.prototype.getStencilFunctionReference = function () {
  7844. return this._stencilState.stencilFuncRef;
  7845. };
  7846. Engine.prototype.getStencilFunctionMask = function () {
  7847. return this._stencilState.stencilFuncMask;
  7848. };
  7849. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7850. this._stencilState.stencilFunc = stencilFunc;
  7851. };
  7852. Engine.prototype.setStencilFunctionReference = function (reference) {
  7853. this._stencilState.stencilFuncRef = reference;
  7854. };
  7855. Engine.prototype.setStencilFunctionMask = function (mask) {
  7856. this._stencilState.stencilFuncMask = mask;
  7857. };
  7858. Engine.prototype.getStencilOperationFail = function () {
  7859. return this._stencilState.stencilOpStencilFail;
  7860. };
  7861. Engine.prototype.getStencilOperationDepthFail = function () {
  7862. return this._stencilState.stencilOpDepthFail;
  7863. };
  7864. Engine.prototype.getStencilOperationPass = function () {
  7865. return this._stencilState.stencilOpStencilDepthPass;
  7866. };
  7867. Engine.prototype.setStencilOperationFail = function (operation) {
  7868. this._stencilState.stencilOpStencilFail = operation;
  7869. };
  7870. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7871. this._stencilState.stencilOpDepthFail = operation;
  7872. };
  7873. Engine.prototype.setStencilOperationPass = function (operation) {
  7874. this._stencilState.stencilOpStencilDepthPass = operation;
  7875. };
  7876. Engine.prototype.setDitheringState = function (value) {
  7877. if (value) {
  7878. this._gl.enable(this._gl.DITHER);
  7879. }
  7880. else {
  7881. this._gl.disable(this._gl.DITHER);
  7882. }
  7883. };
  7884. /**
  7885. * stop executing a render loop function and remove it from the execution array
  7886. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7887. */
  7888. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7889. if (!renderFunction) {
  7890. this._activeRenderLoops = [];
  7891. return;
  7892. }
  7893. var index = this._activeRenderLoops.indexOf(renderFunction);
  7894. if (index >= 0) {
  7895. this._activeRenderLoops.splice(index, 1);
  7896. }
  7897. };
  7898. Engine.prototype._renderLoop = function () {
  7899. var shouldRender = true;
  7900. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7901. shouldRender = false;
  7902. }
  7903. if (shouldRender) {
  7904. // Start new frame
  7905. this.beginFrame();
  7906. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7907. var renderFunction = this._activeRenderLoops[index];
  7908. renderFunction();
  7909. }
  7910. // Present
  7911. this.endFrame();
  7912. }
  7913. if (this._activeRenderLoops.length > 0) {
  7914. // Register new frame
  7915. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7916. }
  7917. else {
  7918. this._renderingQueueLaunched = false;
  7919. }
  7920. };
  7921. /**
  7922. * Register and execute a render loop. The engine can have more than one render function.
  7923. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7924. * @example
  7925. * engine.runRenderLoop(function () {
  7926. * scene.render()
  7927. * })
  7928. */
  7929. Engine.prototype.runRenderLoop = function (renderFunction) {
  7930. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7931. return;
  7932. }
  7933. this._activeRenderLoops.push(renderFunction);
  7934. if (!this._renderingQueueLaunched) {
  7935. this._renderingQueueLaunched = true;
  7936. this._bindedRenderFunction = this._renderLoop.bind(this);
  7937. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7938. }
  7939. };
  7940. /**
  7941. * Toggle full screen mode.
  7942. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7943. * @param {any} options - an options object to be sent to the requestFullscreen function
  7944. */
  7945. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7946. if (this.isFullscreen) {
  7947. BABYLON.Tools.ExitFullscreen();
  7948. }
  7949. else {
  7950. this._pointerLockRequested = requestPointerLock;
  7951. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7952. }
  7953. };
  7954. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7955. if (stencil === void 0) { stencil = false; }
  7956. this.applyStates();
  7957. var mode = 0;
  7958. if (backBuffer && color) {
  7959. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7960. mode |= this._gl.COLOR_BUFFER_BIT;
  7961. }
  7962. if (depth) {
  7963. this._gl.clearDepth(1.0);
  7964. mode |= this._gl.DEPTH_BUFFER_BIT;
  7965. }
  7966. if (stencil) {
  7967. this._gl.clearStencil(0);
  7968. mode |= this._gl.STENCIL_BUFFER_BIT;
  7969. }
  7970. this._gl.clear(mode);
  7971. };
  7972. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7973. var gl = this._gl;
  7974. // Save state
  7975. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7976. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7977. // Change state
  7978. gl.enable(gl.SCISSOR_TEST);
  7979. gl.scissor(x, y, width, height);
  7980. // Clear
  7981. this.clear(clearColor, true, true, true);
  7982. // Restore state
  7983. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7984. if (curScissor === true) {
  7985. gl.enable(gl.SCISSOR_TEST);
  7986. }
  7987. else {
  7988. gl.disable(gl.SCISSOR_TEST);
  7989. }
  7990. };
  7991. /**
  7992. * Set the WebGL's viewport
  7993. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7994. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7995. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7996. */
  7997. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7998. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7999. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8000. var x = viewport.x || 0;
  8001. var y = viewport.y || 0;
  8002. this._cachedViewport = viewport;
  8003. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8004. };
  8005. /**
  8006. * Directly set the WebGL Viewport
  8007. * The x, y, width & height are directly passed to the WebGL call
  8008. * @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.
  8009. */
  8010. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8011. var currentViewport = this._cachedViewport;
  8012. this._cachedViewport = null;
  8013. this._gl.viewport(x, y, width, height);
  8014. return currentViewport;
  8015. };
  8016. Engine.prototype.beginFrame = function () {
  8017. this._measureFps();
  8018. };
  8019. Engine.prototype.endFrame = function () {
  8020. //force a flush in case we are using a bad OS.
  8021. if (this._badOS) {
  8022. this.flushFramebuffer();
  8023. }
  8024. //submit frame to the vr device, if enabled
  8025. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8026. this._vrDisplayEnabled.submitFrame();
  8027. }
  8028. };
  8029. /**
  8030. * resize the view according to the canvas' size.
  8031. * @example
  8032. * window.addEventListener("resize", function () {
  8033. * engine.resize();
  8034. * });
  8035. */
  8036. Engine.prototype.resize = function () {
  8037. // We're not resizing the size of the canvas while in VR mode & presenting
  8038. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8039. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8040. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8041. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8042. }
  8043. };
  8044. /**
  8045. * force a specific size of the canvas
  8046. * @param {number} width - the new canvas' width
  8047. * @param {number} height - the new canvas' height
  8048. */
  8049. Engine.prototype.setSize = function (width, height) {
  8050. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8051. return;
  8052. }
  8053. this._renderingCanvas.width = width;
  8054. this._renderingCanvas.height = height;
  8055. for (var index = 0; index < this.scenes.length; index++) {
  8056. var scene = this.scenes[index];
  8057. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8058. var cam = scene.cameras[camIndex];
  8059. cam._currentRenderId = 0;
  8060. }
  8061. }
  8062. if (this.onResizeObservable.hasObservers) {
  8063. this.onResizeObservable.notifyObservers(this);
  8064. }
  8065. };
  8066. //WebVR functions
  8067. Engine.prototype.isVRDevicePresent = function (callback) {
  8068. this.getVRDevice(null, function (device) {
  8069. callback(device !== null);
  8070. });
  8071. };
  8072. Engine.prototype.getVRDevice = function (name, callback) {
  8073. if (!this.vrDisplaysPromise) {
  8074. callback(null);
  8075. return;
  8076. }
  8077. this.vrDisplaysPromise.then(function (devices) {
  8078. if (devices.length > 0) {
  8079. if (name) {
  8080. var found = devices.some(function (device) {
  8081. if (device.displayName === name) {
  8082. callback(device);
  8083. return true;
  8084. }
  8085. else {
  8086. return false;
  8087. }
  8088. });
  8089. if (!found) {
  8090. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8091. callback(devices[0]);
  8092. }
  8093. }
  8094. else {
  8095. //choose the first one
  8096. callback(devices[0]);
  8097. }
  8098. }
  8099. else {
  8100. BABYLON.Tools.Error("No WebVR devices found!");
  8101. callback(null);
  8102. }
  8103. });
  8104. };
  8105. Engine.prototype.initWebVR = function () {
  8106. if (!this.vrDisplaysPromise) {
  8107. this._getVRDisplays();
  8108. }
  8109. };
  8110. Engine.prototype.enableVR = function (vrDevice) {
  8111. this._vrDisplayEnabled = vrDevice;
  8112. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8113. };
  8114. Engine.prototype.disableVR = function () {
  8115. if (this._vrDisplayEnabled) {
  8116. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8117. }
  8118. };
  8119. Engine.prototype._getVRDisplays = function () {
  8120. var _this = this;
  8121. var getWebVRDevices = function (devices) {
  8122. var size = devices.length;
  8123. var i = 0;
  8124. _this._vrDisplays = devices.filter(function (device) {
  8125. return devices[i] instanceof VRDisplay;
  8126. });
  8127. return _this._vrDisplays;
  8128. };
  8129. //using a key due to typescript
  8130. if (navigator.getVRDisplays) {
  8131. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8132. }
  8133. };
  8134. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8135. this._currentRenderTarget = texture;
  8136. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8137. var gl = this._gl;
  8138. if (texture.isCube) {
  8139. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8140. }
  8141. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8142. this.wipeCaches();
  8143. };
  8144. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8145. if (this._currentFramebuffer !== framebuffer) {
  8146. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8147. this._currentFramebuffer = framebuffer;
  8148. }
  8149. };
  8150. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8151. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8152. this._currentRenderTarget = null;
  8153. // If MSAA, we need to bitblt back to main texture
  8154. var gl = this._gl;
  8155. if (texture._MSAAFramebuffer) {
  8156. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8157. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8158. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8159. }
  8160. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8161. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8162. gl.generateMipmap(gl.TEXTURE_2D);
  8163. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8164. }
  8165. if (onBeforeUnbind) {
  8166. if (texture._MSAAFramebuffer) {
  8167. // Bind the correct framebuffer
  8168. this.bindUnboundFramebuffer(texture._framebuffer);
  8169. }
  8170. onBeforeUnbind();
  8171. }
  8172. this.bindUnboundFramebuffer(null);
  8173. };
  8174. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8175. if (texture.generateMipMaps) {
  8176. var gl = this._gl;
  8177. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8178. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8179. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8180. }
  8181. };
  8182. Engine.prototype.flushFramebuffer = function () {
  8183. this._gl.flush();
  8184. };
  8185. Engine.prototype.restoreDefaultFramebuffer = function () {
  8186. this._currentRenderTarget = null;
  8187. this.bindUnboundFramebuffer(null);
  8188. this.setViewport(this._cachedViewport);
  8189. this.wipeCaches();
  8190. };
  8191. // UBOs
  8192. Engine.prototype.createUniformBuffer = function (elements) {
  8193. var ubo = this._gl.createBuffer();
  8194. this.bindUniformBuffer(ubo);
  8195. if (elements instanceof Float32Array) {
  8196. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8197. }
  8198. else {
  8199. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8200. }
  8201. this.bindUniformBuffer(null);
  8202. ubo.references = 1;
  8203. return ubo;
  8204. };
  8205. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8206. var ubo = this._gl.createBuffer();
  8207. this.bindUniformBuffer(ubo);
  8208. if (elements instanceof Float32Array) {
  8209. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8210. }
  8211. else {
  8212. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8213. }
  8214. this.bindUniformBuffer(null);
  8215. ubo.references = 1;
  8216. return ubo;
  8217. };
  8218. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8219. this.bindUniformBuffer(uniformBuffer);
  8220. if (offset === undefined) {
  8221. offset = 0;
  8222. }
  8223. if (count === undefined) {
  8224. if (elements instanceof Float32Array) {
  8225. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8226. }
  8227. else {
  8228. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8229. }
  8230. }
  8231. else {
  8232. if (elements instanceof Float32Array) {
  8233. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8234. }
  8235. else {
  8236. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8237. }
  8238. }
  8239. this.bindUniformBuffer(null);
  8240. };
  8241. // VBOs
  8242. Engine.prototype._resetVertexBufferBinding = function () {
  8243. this.bindArrayBuffer(null);
  8244. this._cachedVertexBuffers = null;
  8245. };
  8246. Engine.prototype.createVertexBuffer = function (vertices) {
  8247. var vbo = this._gl.createBuffer();
  8248. this.bindArrayBuffer(vbo);
  8249. if (vertices instanceof Float32Array) {
  8250. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8251. }
  8252. else {
  8253. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8254. }
  8255. this._resetVertexBufferBinding();
  8256. vbo.references = 1;
  8257. return vbo;
  8258. };
  8259. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8260. var vbo = this._gl.createBuffer();
  8261. this.bindArrayBuffer(vbo);
  8262. if (vertices instanceof Float32Array) {
  8263. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8264. }
  8265. else {
  8266. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8267. }
  8268. this._resetVertexBufferBinding();
  8269. vbo.references = 1;
  8270. return vbo;
  8271. };
  8272. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8273. this.bindArrayBuffer(vertexBuffer);
  8274. if (offset === undefined) {
  8275. offset = 0;
  8276. }
  8277. if (count === undefined) {
  8278. if (vertices instanceof Float32Array) {
  8279. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8280. }
  8281. else {
  8282. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8283. }
  8284. }
  8285. else {
  8286. if (vertices instanceof Float32Array) {
  8287. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8288. }
  8289. else {
  8290. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8291. }
  8292. }
  8293. this._resetVertexBufferBinding();
  8294. };
  8295. Engine.prototype._resetIndexBufferBinding = function () {
  8296. this.bindIndexBuffer(null);
  8297. this._cachedIndexBuffer = null;
  8298. };
  8299. Engine.prototype.createIndexBuffer = function (indices) {
  8300. var vbo = this._gl.createBuffer();
  8301. this.bindIndexBuffer(vbo);
  8302. // Check for 32 bits indices
  8303. var arrayBuffer;
  8304. var need32Bits = false;
  8305. if (indices instanceof Uint16Array) {
  8306. arrayBuffer = indices;
  8307. }
  8308. else {
  8309. //check 32 bit support
  8310. if (this._caps.uintIndices) {
  8311. if (indices instanceof Uint32Array) {
  8312. arrayBuffer = indices;
  8313. need32Bits = true;
  8314. }
  8315. else {
  8316. //number[] or Int32Array, check if 32 bit is necessary
  8317. for (var index = 0; index < indices.length; index++) {
  8318. if (indices[index] > 65535) {
  8319. need32Bits = true;
  8320. break;
  8321. }
  8322. }
  8323. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8324. }
  8325. }
  8326. else {
  8327. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8328. arrayBuffer = new Uint16Array(indices);
  8329. }
  8330. }
  8331. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8332. this._resetIndexBufferBinding();
  8333. vbo.references = 1;
  8334. vbo.is32Bits = need32Bits;
  8335. return vbo;
  8336. };
  8337. Engine.prototype.bindArrayBuffer = function (buffer) {
  8338. if (!this._vaoRecordInProgress) {
  8339. this._unBindVertexArrayObject();
  8340. }
  8341. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8342. };
  8343. Engine.prototype.bindUniformBuffer = function (buffer) {
  8344. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8345. };
  8346. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8347. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8348. };
  8349. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8350. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8351. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8352. };
  8353. ;
  8354. Engine.prototype.bindIndexBuffer = function (buffer) {
  8355. if (!this._vaoRecordInProgress) {
  8356. this._unBindVertexArrayObject();
  8357. }
  8358. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8359. };
  8360. Engine.prototype.bindBuffer = function (buffer, target) {
  8361. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8362. this._gl.bindBuffer(target, buffer);
  8363. this._currentBoundBuffer[target] = buffer;
  8364. }
  8365. };
  8366. Engine.prototype.updateArrayBuffer = function (data) {
  8367. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8368. };
  8369. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8370. var pointer = this._currentBufferPointers[indx];
  8371. var changed = false;
  8372. if (!pointer) {
  8373. changed = true;
  8374. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8375. }
  8376. else {
  8377. if (pointer.buffer !== buffer) {
  8378. pointer.buffer = buffer;
  8379. changed = true;
  8380. }
  8381. if (pointer.size !== size) {
  8382. pointer.size = size;
  8383. changed = true;
  8384. }
  8385. if (pointer.type !== type) {
  8386. pointer.type = type;
  8387. changed = true;
  8388. }
  8389. if (pointer.normalized !== normalized) {
  8390. pointer.normalized = normalized;
  8391. changed = true;
  8392. }
  8393. if (pointer.stride !== stride) {
  8394. pointer.stride = stride;
  8395. changed = true;
  8396. }
  8397. if (pointer.offset !== offset) {
  8398. pointer.offset = offset;
  8399. changed = true;
  8400. }
  8401. }
  8402. if (changed || this._vaoRecordInProgress) {
  8403. this.bindArrayBuffer(buffer);
  8404. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8405. }
  8406. };
  8407. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8408. if (indexBuffer == null) {
  8409. return;
  8410. }
  8411. if (this._cachedIndexBuffer !== indexBuffer) {
  8412. this._cachedIndexBuffer = indexBuffer;
  8413. this.bindIndexBuffer(indexBuffer);
  8414. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8415. }
  8416. };
  8417. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8418. var attributes = effect.getAttributesNames();
  8419. if (!this._vaoRecordInProgress) {
  8420. this._unBindVertexArrayObject();
  8421. }
  8422. this.unbindAllAttributes();
  8423. for (var index = 0; index < attributes.length; index++) {
  8424. var order = effect.getAttributeLocation(index);
  8425. if (order >= 0) {
  8426. var vertexBuffer = vertexBuffers[attributes[index]];
  8427. if (!vertexBuffer) {
  8428. continue;
  8429. }
  8430. this._gl.enableVertexAttribArray(order);
  8431. if (!this._vaoRecordInProgress) {
  8432. this._vertexAttribArraysEnabled[order] = true;
  8433. }
  8434. var buffer = vertexBuffer.getBuffer();
  8435. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8436. if (vertexBuffer.getIsInstanced()) {
  8437. this._gl.vertexAttribDivisor(order, 1);
  8438. if (!this._vaoRecordInProgress) {
  8439. this._currentInstanceLocations.push(order);
  8440. this._currentInstanceBuffers.push(buffer);
  8441. }
  8442. }
  8443. }
  8444. }
  8445. };
  8446. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8447. var vao = this._gl.createVertexArray();
  8448. this._vaoRecordInProgress = true;
  8449. this._gl.bindVertexArray(vao);
  8450. this._mustWipeVertexAttributes = true;
  8451. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8452. this.bindIndexBuffer(indexBuffer);
  8453. this._vaoRecordInProgress = false;
  8454. this._gl.bindVertexArray(null);
  8455. return vao;
  8456. };
  8457. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8458. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8459. this._cachedVertexArrayObject = vertexArrayObject;
  8460. this._gl.bindVertexArray(vertexArrayObject);
  8461. this._cachedVertexBuffers = null;
  8462. this._cachedIndexBuffer = null;
  8463. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8464. this._mustWipeVertexAttributes = true;
  8465. }
  8466. };
  8467. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8468. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8469. this._cachedVertexBuffers = vertexBuffer;
  8470. this._cachedEffectForVertexBuffers = effect;
  8471. var attributesCount = effect.getAttributesCount();
  8472. this._unBindVertexArrayObject();
  8473. this.unbindAllAttributes();
  8474. var offset = 0;
  8475. for (var index = 0; index < attributesCount; index++) {
  8476. if (index < vertexDeclaration.length) {
  8477. var order = effect.getAttributeLocation(index);
  8478. if (order >= 0) {
  8479. this._gl.enableVertexAttribArray(order);
  8480. this._vertexAttribArraysEnabled[order] = true;
  8481. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8482. }
  8483. offset += vertexDeclaration[index] * 4;
  8484. }
  8485. }
  8486. }
  8487. this._bindIndexBufferWithCache(indexBuffer);
  8488. };
  8489. Engine.prototype._unBindVertexArrayObject = function () {
  8490. if (!this._cachedVertexArrayObject) {
  8491. return;
  8492. }
  8493. this._cachedVertexArrayObject = null;
  8494. this._gl.bindVertexArray(null);
  8495. };
  8496. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8497. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8498. this._cachedVertexBuffers = vertexBuffers;
  8499. this._cachedEffectForVertexBuffers = effect;
  8500. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8501. }
  8502. this._bindIndexBufferWithCache(indexBuffer);
  8503. };
  8504. Engine.prototype.unbindInstanceAttributes = function () {
  8505. var boundBuffer;
  8506. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8507. var instancesBuffer = this._currentInstanceBuffers[i];
  8508. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8509. boundBuffer = instancesBuffer;
  8510. this.bindArrayBuffer(instancesBuffer);
  8511. }
  8512. var offsetLocation = this._currentInstanceLocations[i];
  8513. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8514. }
  8515. this._currentInstanceBuffers.length = 0;
  8516. this._currentInstanceLocations.length = 0;
  8517. };
  8518. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8519. this._gl.deleteVertexArray(vao);
  8520. };
  8521. Engine.prototype._releaseBuffer = function (buffer) {
  8522. buffer.references--;
  8523. if (buffer.references === 0) {
  8524. this._gl.deleteBuffer(buffer);
  8525. return true;
  8526. }
  8527. return false;
  8528. };
  8529. Engine.prototype.createInstancesBuffer = function (capacity) {
  8530. var buffer = this._gl.createBuffer();
  8531. buffer.capacity = capacity;
  8532. this.bindArrayBuffer(buffer);
  8533. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8534. return buffer;
  8535. };
  8536. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8537. this._gl.deleteBuffer(buffer);
  8538. };
  8539. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8540. this.bindArrayBuffer(instancesBuffer);
  8541. if (data) {
  8542. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8543. }
  8544. if (offsetLocations[0].index !== undefined) {
  8545. var stride = 0;
  8546. for (var i = 0; i < offsetLocations.length; i++) {
  8547. var ai = offsetLocations[i];
  8548. stride += ai.attributeSize * 4;
  8549. }
  8550. for (var i = 0; i < offsetLocations.length; i++) {
  8551. var ai = offsetLocations[i];
  8552. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8553. this._gl.enableVertexAttribArray(ai.index);
  8554. this._vertexAttribArraysEnabled[ai.index] = true;
  8555. }
  8556. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8557. this._gl.vertexAttribDivisor(ai.index, 1);
  8558. this._currentInstanceLocations.push(ai.index);
  8559. this._currentInstanceBuffers.push(instancesBuffer);
  8560. }
  8561. }
  8562. else {
  8563. for (var index = 0; index < 4; index++) {
  8564. var offsetLocation = offsetLocations[index];
  8565. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8566. this._gl.enableVertexAttribArray(offsetLocation);
  8567. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8568. }
  8569. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8570. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8571. this._currentInstanceLocations.push(offsetLocation);
  8572. this._currentInstanceBuffers.push(instancesBuffer);
  8573. }
  8574. }
  8575. };
  8576. Engine.prototype.applyStates = function () {
  8577. this._depthCullingState.apply(this._gl);
  8578. this._stencilState.apply(this._gl);
  8579. this._alphaState.apply(this._gl);
  8580. };
  8581. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8582. // Apply states
  8583. this.applyStates();
  8584. this._drawCalls.addCount(1, false);
  8585. // Render
  8586. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8587. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8588. if (instancesCount) {
  8589. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8590. return;
  8591. }
  8592. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8593. };
  8594. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8595. // Apply states
  8596. this.applyStates();
  8597. this._drawCalls.addCount(1, false);
  8598. if (instancesCount) {
  8599. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8600. return;
  8601. }
  8602. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8603. };
  8604. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8605. // Apply states
  8606. this.applyStates();
  8607. this._drawCalls.addCount(1, false);
  8608. if (instancesCount) {
  8609. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8610. return;
  8611. }
  8612. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8613. };
  8614. // Shaders
  8615. Engine.prototype._releaseEffect = function (effect) {
  8616. if (this._compiledEffects[effect._key]) {
  8617. delete this._compiledEffects[effect._key];
  8618. if (effect.getProgram()) {
  8619. this._gl.deleteProgram(effect.getProgram());
  8620. }
  8621. }
  8622. };
  8623. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8624. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8625. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8626. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8627. if (this._compiledEffects[name]) {
  8628. return this._compiledEffects[name];
  8629. }
  8630. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8631. effect._key = name;
  8632. this._compiledEffects[name] = effect;
  8633. return effect;
  8634. };
  8635. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8636. if (uniformsNames === void 0) { uniformsNames = []; }
  8637. if (samplers === void 0) { samplers = []; }
  8638. if (defines === void 0) { defines = ""; }
  8639. return this.createEffect({
  8640. vertex: "particles",
  8641. fragmentElement: fragmentName
  8642. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8643. };
  8644. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8645. context = context || this._gl;
  8646. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8647. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8648. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8649. var shaderProgram = context.createProgram();
  8650. context.attachShader(shaderProgram, vertexShader);
  8651. context.attachShader(shaderProgram, fragmentShader);
  8652. context.linkProgram(shaderProgram);
  8653. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8654. if (!linked) {
  8655. var error = context.getProgramInfoLog(shaderProgram);
  8656. if (error) {
  8657. throw new Error(error);
  8658. }
  8659. }
  8660. context.deleteShader(vertexShader);
  8661. context.deleteShader(fragmentShader);
  8662. return shaderProgram;
  8663. };
  8664. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8665. var results = [];
  8666. for (var index = 0; index < uniformsNames.length; index++) {
  8667. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8668. }
  8669. return results;
  8670. };
  8671. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8672. var results = [];
  8673. for (var index = 0; index < attributesNames.length; index++) {
  8674. try {
  8675. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8676. }
  8677. catch (e) {
  8678. results.push(-1);
  8679. }
  8680. }
  8681. return results;
  8682. };
  8683. Engine.prototype.enableEffect = function (effect) {
  8684. // Use program
  8685. this.setProgram(effect.getProgram());
  8686. this._currentEffect = effect;
  8687. if (effect.onBind) {
  8688. effect.onBind(effect);
  8689. }
  8690. };
  8691. Engine.prototype.setIntArray = function (uniform, array) {
  8692. if (!uniform)
  8693. return;
  8694. this._gl.uniform1iv(uniform, array);
  8695. };
  8696. Engine.prototype.setIntArray2 = function (uniform, array) {
  8697. if (!uniform || array.length % 2 !== 0)
  8698. return;
  8699. this._gl.uniform2iv(uniform, array);
  8700. };
  8701. Engine.prototype.setIntArray3 = function (uniform, array) {
  8702. if (!uniform || array.length % 3 !== 0)
  8703. return;
  8704. this._gl.uniform3iv(uniform, array);
  8705. };
  8706. Engine.prototype.setIntArray4 = function (uniform, array) {
  8707. if (!uniform || array.length % 4 !== 0)
  8708. return;
  8709. this._gl.uniform4iv(uniform, array);
  8710. };
  8711. Engine.prototype.setFloatArray = function (uniform, array) {
  8712. if (!uniform)
  8713. return;
  8714. this._gl.uniform1fv(uniform, array);
  8715. };
  8716. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8717. if (!uniform || array.length % 2 !== 0)
  8718. return;
  8719. this._gl.uniform2fv(uniform, array);
  8720. };
  8721. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8722. if (!uniform || array.length % 3 !== 0)
  8723. return;
  8724. this._gl.uniform3fv(uniform, array);
  8725. };
  8726. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8727. if (!uniform || array.length % 4 !== 0)
  8728. return;
  8729. this._gl.uniform4fv(uniform, array);
  8730. };
  8731. Engine.prototype.setArray = function (uniform, array) {
  8732. if (!uniform)
  8733. return;
  8734. this._gl.uniform1fv(uniform, array);
  8735. };
  8736. Engine.prototype.setArray2 = function (uniform, array) {
  8737. if (!uniform || array.length % 2 !== 0)
  8738. return;
  8739. this._gl.uniform2fv(uniform, array);
  8740. };
  8741. Engine.prototype.setArray3 = function (uniform, array) {
  8742. if (!uniform || array.length % 3 !== 0)
  8743. return;
  8744. this._gl.uniform3fv(uniform, array);
  8745. };
  8746. Engine.prototype.setArray4 = function (uniform, array) {
  8747. if (!uniform || array.length % 4 !== 0)
  8748. return;
  8749. this._gl.uniform4fv(uniform, array);
  8750. };
  8751. Engine.prototype.setMatrices = function (uniform, matrices) {
  8752. if (!uniform)
  8753. return;
  8754. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8755. };
  8756. Engine.prototype.setMatrix = function (uniform, matrix) {
  8757. if (!uniform)
  8758. return;
  8759. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8760. };
  8761. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8762. if (!uniform)
  8763. return;
  8764. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8765. };
  8766. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8767. if (!uniform)
  8768. return;
  8769. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8770. };
  8771. Engine.prototype.setFloat = function (uniform, value) {
  8772. if (!uniform)
  8773. return;
  8774. this._gl.uniform1f(uniform, value);
  8775. };
  8776. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8777. if (!uniform)
  8778. return;
  8779. this._gl.uniform2f(uniform, x, y);
  8780. };
  8781. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8782. if (!uniform)
  8783. return;
  8784. this._gl.uniform3f(uniform, x, y, z);
  8785. };
  8786. Engine.prototype.setBool = function (uniform, bool) {
  8787. if (!uniform)
  8788. return;
  8789. this._gl.uniform1i(uniform, bool);
  8790. };
  8791. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8792. if (!uniform)
  8793. return;
  8794. this._gl.uniform4f(uniform, x, y, z, w);
  8795. };
  8796. Engine.prototype.setColor3 = function (uniform, color3) {
  8797. if (!uniform)
  8798. return;
  8799. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8800. };
  8801. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8802. if (!uniform)
  8803. return;
  8804. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8805. };
  8806. // States
  8807. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8808. if (zOffset === void 0) { zOffset = 0; }
  8809. if (reverseSide === void 0) { reverseSide = false; }
  8810. // Culling
  8811. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8812. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8813. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8814. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8815. if (culling) {
  8816. this._depthCullingState.cullFace = cullFace;
  8817. this._depthCullingState.cull = true;
  8818. }
  8819. else {
  8820. this._depthCullingState.cull = false;
  8821. }
  8822. }
  8823. // Z offset
  8824. this._depthCullingState.zOffset = zOffset;
  8825. };
  8826. Engine.prototype.setDepthBuffer = function (enable) {
  8827. this._depthCullingState.depthTest = enable;
  8828. };
  8829. Engine.prototype.getDepthWrite = function () {
  8830. return this._depthCullingState.depthMask;
  8831. };
  8832. Engine.prototype.setDepthWrite = function (enable) {
  8833. this._depthCullingState.depthMask = enable;
  8834. };
  8835. Engine.prototype.setColorWrite = function (enable) {
  8836. this._gl.colorMask(enable, enable, enable, enable);
  8837. };
  8838. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8839. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8840. };
  8841. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8842. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8843. if (this._alphaMode === mode) {
  8844. return;
  8845. }
  8846. switch (mode) {
  8847. case Engine.ALPHA_DISABLE:
  8848. this._alphaState.alphaBlend = false;
  8849. break;
  8850. case Engine.ALPHA_PREMULTIPLIED:
  8851. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8852. this._alphaState.alphaBlend = true;
  8853. break;
  8854. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8855. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8856. this._alphaState.alphaBlend = true;
  8857. break;
  8858. case Engine.ALPHA_COMBINE:
  8859. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8860. this._alphaState.alphaBlend = true;
  8861. break;
  8862. case Engine.ALPHA_ONEONE:
  8863. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8864. this._alphaState.alphaBlend = true;
  8865. break;
  8866. case Engine.ALPHA_ADD:
  8867. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8868. this._alphaState.alphaBlend = true;
  8869. break;
  8870. case Engine.ALPHA_SUBTRACT:
  8871. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8872. this._alphaState.alphaBlend = true;
  8873. break;
  8874. case Engine.ALPHA_MULTIPLY:
  8875. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8876. this._alphaState.alphaBlend = true;
  8877. break;
  8878. case Engine.ALPHA_MAXIMIZED:
  8879. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8880. this._alphaState.alphaBlend = true;
  8881. break;
  8882. case Engine.ALPHA_INTERPOLATE:
  8883. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8884. this._alphaState.alphaBlend = true;
  8885. break;
  8886. case Engine.ALPHA_SCREENMODE:
  8887. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8888. this._alphaState.alphaBlend = true;
  8889. break;
  8890. }
  8891. if (!noDepthWriteChange) {
  8892. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8893. }
  8894. this._alphaMode = mode;
  8895. };
  8896. Engine.prototype.getAlphaMode = function () {
  8897. return this._alphaMode;
  8898. };
  8899. Engine.prototype.setAlphaTesting = function (enable) {
  8900. this._alphaTest = enable;
  8901. };
  8902. Engine.prototype.getAlphaTesting = function () {
  8903. return !!this._alphaTest;
  8904. };
  8905. // Textures
  8906. Engine.prototype.wipeCaches = function (bruteForce) {
  8907. if (this.preventCacheWipeBetweenFrames) {
  8908. return;
  8909. }
  8910. this.resetTextureCache();
  8911. this._currentEffect = null;
  8912. // 6/8/2017: deltakosh: Should not be required anymore.
  8913. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  8914. if (bruteForce) {
  8915. this._stencilState.reset();
  8916. this._depthCullingState.reset();
  8917. this.setDepthFunctionToLessOrEqual();
  8918. this._alphaState.reset();
  8919. }
  8920. this._cachedVertexBuffers = null;
  8921. this._cachedIndexBuffer = null;
  8922. this._cachedEffectForVertexBuffers = null;
  8923. this._unBindVertexArrayObject();
  8924. this.bindIndexBuffer(null);
  8925. this.bindArrayBuffer(null);
  8926. };
  8927. /**
  8928. * Set the compressed texture format to use, based on the formats you have, and the formats
  8929. * supported by the hardware / browser.
  8930. *
  8931. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8932. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8933. * to API arguments needed to compressed textures. This puts the burden on the container
  8934. * generator to house the arcane code for determining these for current & future formats.
  8935. *
  8936. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8937. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8938. *
  8939. * Note: The result of this call is not taken into account when a texture is base64.
  8940. *
  8941. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8942. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8943. *
  8944. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  8945. * @returns The extension selected.
  8946. */
  8947. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8948. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8949. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8950. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8951. return this._textureFormatInUse = this._texturesSupported[i];
  8952. }
  8953. }
  8954. }
  8955. // actively set format to nothing, to allow this to be called more than once
  8956. // and possibly fail the 2nd time
  8957. return this._textureFormatInUse = null;
  8958. };
  8959. /**
  8960. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  8961. * @param {string} urlArg- This contains one of the following:
  8962. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  8963. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  8964. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  8965. *
  8966. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  8967. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  8968. * @param {Scene} scene- Needed for loading to the correct scene.
  8969. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  8970. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  8971. * @param {callback} onError- Optional callback to be called upon failure.
  8972. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  8973. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  8974. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  8975. *
  8976. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  8977. */
  8978. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  8979. var _this = this;
  8980. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8981. if (onLoad === void 0) { onLoad = null; }
  8982. if (onError === void 0) { onError = null; }
  8983. if (buffer === void 0) { buffer = null; }
  8984. var texture = fallBack ? fallBack : this._gl.createTexture();
  8985. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  8986. var fromData = url.substr(0, 5) === "data:";
  8987. var isBase64 = fromData && url.indexOf("base64") !== -1;
  8988. // establish the file extension, if possible
  8989. var lastDot = url.lastIndexOf('.');
  8990. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  8991. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8992. if (isDDS) {
  8993. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  8994. }
  8995. var isTGA = (extension === ".tga");
  8996. // determine if a ktx file should be substituted
  8997. var isKTX = false;
  8998. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  8999. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9000. isKTX = true;
  9001. }
  9002. scene._addPendingData(texture);
  9003. texture.url = url;
  9004. texture.noMipmap = noMipmap;
  9005. texture.references = 1;
  9006. texture.samplingMode = samplingMode;
  9007. texture.onLoadedCallbacks = [];
  9008. if (onLoad) {
  9009. texture.onLoadedCallbacks.push(onLoad);
  9010. }
  9011. if (!fallBack)
  9012. this._loadedTexturesCache.push(texture);
  9013. var onerror = function () {
  9014. scene._removePendingData(texture);
  9015. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9016. if (isKTX) {
  9017. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9018. }
  9019. else if (onError) {
  9020. onError();
  9021. }
  9022. };
  9023. var callback;
  9024. // processing for non-image formats
  9025. if (isKTX || isTGA || isDDS) {
  9026. if (isKTX) {
  9027. callback = function (data) {
  9028. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9029. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9030. ktx.uploadLevels(_this._gl, !noMipmap);
  9031. }, samplingMode);
  9032. };
  9033. }
  9034. else if (isTGA) {
  9035. callback = function (arrayBuffer) {
  9036. var data = new Uint8Array(arrayBuffer);
  9037. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9038. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9039. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9040. }, samplingMode);
  9041. };
  9042. }
  9043. else if (isDDS) {
  9044. callback = function (data) {
  9045. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9046. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9047. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9048. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9049. }, samplingMode);
  9050. };
  9051. }
  9052. if (!buffer) {
  9053. BABYLON.Tools.LoadFile(url, function (data) {
  9054. callback(data);
  9055. }, null, scene.database, true, onerror);
  9056. }
  9057. else {
  9058. callback(buffer);
  9059. }
  9060. // image format processing
  9061. }
  9062. else {
  9063. var onload = function (img) {
  9064. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9065. var isPot = (img.width === potWidth && img.height === potHeight);
  9066. if (!isPot) {
  9067. _this._prepareWorkingCanvas();
  9068. _this._workingCanvas.width = potWidth;
  9069. _this._workingCanvas.height = potHeight;
  9070. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9071. _this._workingContext.imageSmoothingEnabled = false;
  9072. _this._workingContext.mozImageSmoothingEnabled = false;
  9073. _this._workingContext.oImageSmoothingEnabled = false;
  9074. _this._workingContext.webkitImageSmoothingEnabled = false;
  9075. _this._workingContext.msImageSmoothingEnabled = false;
  9076. }
  9077. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9078. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9079. _this._workingContext.imageSmoothingEnabled = true;
  9080. _this._workingContext.mozImageSmoothingEnabled = true;
  9081. _this._workingContext.oImageSmoothingEnabled = true;
  9082. _this._workingContext.webkitImageSmoothingEnabled = true;
  9083. _this._workingContext.msImageSmoothingEnabled = true;
  9084. }
  9085. }
  9086. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9087. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9088. }, samplingMode);
  9089. };
  9090. if (!fromData || isBase64)
  9091. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9092. else if (buffer instanceof Array || typeof buffer === "string")
  9093. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9094. else
  9095. onload(buffer);
  9096. }
  9097. return texture;
  9098. };
  9099. Engine.prototype._getInternalFormat = function (format) {
  9100. var internalFormat = this._gl.RGBA;
  9101. switch (format) {
  9102. case Engine.TEXTUREFORMAT_ALPHA:
  9103. internalFormat = this._gl.ALPHA;
  9104. break;
  9105. case Engine.TEXTUREFORMAT_LUMINANCE:
  9106. internalFormat = this._gl.LUMINANCE;
  9107. break;
  9108. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9109. internalFormat = this._gl.LUMINANCE_ALPHA;
  9110. break;
  9111. case Engine.TEXTUREFORMAT_RGB:
  9112. internalFormat = this._gl.RGB;
  9113. break;
  9114. case Engine.TEXTUREFORMAT_RGBA:
  9115. internalFormat = this._gl.RGBA;
  9116. break;
  9117. }
  9118. return internalFormat;
  9119. };
  9120. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9121. if (compression === void 0) { compression = null; }
  9122. var internalFormat = this._getInternalFormat(format);
  9123. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9124. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9125. if (texture._width % 4 !== 0) {
  9126. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9127. }
  9128. if (compression) {
  9129. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9130. }
  9131. else {
  9132. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9133. }
  9134. if (texture.generateMipMaps) {
  9135. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9136. }
  9137. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9138. this.resetTextureCache();
  9139. texture.isReady = true;
  9140. };
  9141. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9142. if (compression === void 0) { compression = null; }
  9143. var texture = this._gl.createTexture();
  9144. texture._baseWidth = width;
  9145. texture._baseHeight = height;
  9146. texture._width = width;
  9147. texture._height = height;
  9148. texture.references = 1;
  9149. this.updateRawTexture(texture, data, format, invertY, compression);
  9150. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9151. // Filters
  9152. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9153. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9154. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9155. if (generateMipMaps) {
  9156. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9157. }
  9158. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9159. texture.samplingMode = samplingMode;
  9160. this._loadedTexturesCache.push(texture);
  9161. return texture;
  9162. };
  9163. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9164. var texture = this._gl.createTexture();
  9165. texture._baseWidth = width;
  9166. texture._baseHeight = height;
  9167. if (generateMipMaps) {
  9168. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9169. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9170. }
  9171. this.resetTextureCache();
  9172. texture._width = width;
  9173. texture._height = height;
  9174. texture.isReady = false;
  9175. texture.generateMipMaps = generateMipMaps;
  9176. texture.references = 1;
  9177. texture.samplingMode = samplingMode;
  9178. this.updateTextureSamplingMode(samplingMode, texture);
  9179. this._loadedTexturesCache.push(texture);
  9180. return texture;
  9181. };
  9182. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9183. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9184. if (texture.isCube) {
  9185. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9186. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9187. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9188. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9189. }
  9190. else {
  9191. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9193. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9194. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9195. }
  9196. texture.samplingMode = samplingMode;
  9197. };
  9198. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9199. if (premulAlpha === void 0) { premulAlpha = false; }
  9200. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9201. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9202. if (premulAlpha) {
  9203. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9204. }
  9205. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9206. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9207. if (texture.generateMipMaps) {
  9208. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9209. }
  9210. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9211. if (premulAlpha) {
  9212. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9213. }
  9214. this.resetTextureCache();
  9215. texture.isReady = true;
  9216. };
  9217. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9218. if (texture._isDisabled) {
  9219. return;
  9220. }
  9221. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9222. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9223. try {
  9224. // Testing video texture support
  9225. if (this._videoTextureSupported === undefined) {
  9226. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9227. if (this._gl.getError() !== 0) {
  9228. this._videoTextureSupported = false;
  9229. }
  9230. else {
  9231. this._videoTextureSupported = true;
  9232. }
  9233. }
  9234. // Copy video through the current working canvas if video texture is not supported
  9235. if (!this._videoTextureSupported) {
  9236. if (!texture._workingCanvas) {
  9237. texture._workingCanvas = document.createElement("canvas");
  9238. texture._workingContext = texture._workingCanvas.getContext("2d");
  9239. texture._workingCanvas.width = texture._width;
  9240. texture._workingCanvas.height = texture._height;
  9241. }
  9242. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9243. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9244. }
  9245. else {
  9246. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9247. }
  9248. if (texture.generateMipMaps) {
  9249. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9250. }
  9251. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9252. this.resetTextureCache();
  9253. texture.isReady = true;
  9254. }
  9255. catch (ex) {
  9256. // Something unexpected
  9257. // Let's disable the texture
  9258. texture._isDisabled = true;
  9259. }
  9260. };
  9261. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9262. // old version had a "generateMipMaps" arg instead of options.
  9263. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9264. // in the same way, generateDepthBuffer is defaulted to true
  9265. var generateMipMaps = false;
  9266. var generateDepthBuffer = true;
  9267. var generateStencilBuffer = false;
  9268. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9269. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9270. if (options !== undefined) {
  9271. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9272. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9273. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9274. type = options.type === undefined ? type : options.type;
  9275. if (options.samplingMode !== undefined) {
  9276. samplingMode = options.samplingMode;
  9277. }
  9278. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9279. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9280. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9281. }
  9282. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9283. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9284. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9285. }
  9286. }
  9287. var gl = this._gl;
  9288. var texture = gl.createTexture();
  9289. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9290. var width = size.width || size;
  9291. var height = size.height || size;
  9292. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9293. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9294. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9295. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9296. }
  9297. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9301. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9302. // Create the framebuffer
  9303. var framebuffer = gl.createFramebuffer();
  9304. this.bindUnboundFramebuffer(framebuffer);
  9305. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9306. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9307. if (generateMipMaps) {
  9308. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9309. }
  9310. // Unbind
  9311. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9312. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9313. this.bindUnboundFramebuffer(null);
  9314. texture._framebuffer = framebuffer;
  9315. texture._baseWidth = width;
  9316. texture._baseHeight = height;
  9317. texture._width = width;
  9318. texture._height = height;
  9319. texture.isReady = true;
  9320. texture.samples = 1;
  9321. texture.generateMipMaps = generateMipMaps;
  9322. texture.references = 1;
  9323. texture.samplingMode = samplingMode;
  9324. texture.type = type;
  9325. texture._generateDepthBuffer = generateDepthBuffer;
  9326. texture._generateStencilBuffer = generateStencilBuffer;
  9327. this.resetTextureCache();
  9328. this._loadedTexturesCache.push(texture);
  9329. return texture;
  9330. };
  9331. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9332. var generateMipMaps = false;
  9333. var generateDepthBuffer = true;
  9334. var generateStencilBuffer = false;
  9335. var generateDepthTexture = false;
  9336. var textureCount = 1;
  9337. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9338. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9339. var types = [], samplingModes = [];
  9340. if (options !== undefined) {
  9341. generateMipMaps = options.generateMipMaps;
  9342. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9343. generateStencilBuffer = options.generateStencilBuffer;
  9344. generateDepthTexture = options.generateDepthTexture;
  9345. textureCount = options.textureCount || 1;
  9346. if (options.types) {
  9347. types = options.types;
  9348. }
  9349. if (options.samplingModes) {
  9350. samplingModes = options.samplingModes;
  9351. }
  9352. }
  9353. var gl = this._gl;
  9354. // Create the framebuffer
  9355. var framebuffer = gl.createFramebuffer();
  9356. this.bindUnboundFramebuffer(framebuffer);
  9357. var colorRenderbuffer = gl.createRenderbuffer();
  9358. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9359. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, width, height);
  9360. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  9361. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9362. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.RENDERBUFFER, colorRenderbuffer);
  9363. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, colorRenderbuffer);
  9364. var width = size.width || size;
  9365. var height = size.height || size;
  9366. var textures = [];
  9367. var attachments = [];
  9368. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9369. for (var i = 0; i < textureCount; i++) {
  9370. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9371. var type = types[i] || defaultType;
  9372. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9373. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9374. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9375. }
  9376. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9377. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9378. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9379. }
  9380. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9381. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9382. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9383. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9384. }
  9385. var texture = gl.createTexture();
  9386. var attachment = gl["COLOR_ATTACHMENT" + i];
  9387. textures.push(texture);
  9388. attachments.push(attachment);
  9389. gl.activeTexture(gl["TEXTURE" + i]);
  9390. gl.bindTexture(gl.TEXTURE_2D, texture);
  9391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9395. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9396. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9397. if (generateMipMaps) {
  9398. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9399. }
  9400. // Unbind
  9401. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9402. texture._framebuffer = framebuffer;
  9403. texture._depthStencilBuffer = depthStencilBuffer;
  9404. texture._baseWidth = width;
  9405. texture._baseHeight = height;
  9406. texture._width = width;
  9407. texture._height = height;
  9408. texture.isReady = true;
  9409. texture.samples = 1;
  9410. texture.generateMipMaps = generateMipMaps;
  9411. texture.references = 1;
  9412. texture.samplingMode = samplingMode;
  9413. texture.type = type;
  9414. texture._generateDepthBuffer = generateDepthBuffer;
  9415. texture._generateStencilBuffer = generateStencilBuffer;
  9416. this._loadedTexturesCache.push(texture);
  9417. }
  9418. if (generateDepthTexture) {
  9419. // Depth texture
  9420. var depthTexture = gl.createTexture();
  9421. gl.activeTexture(gl.TEXTURE0);
  9422. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9426. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9427. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9428. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9429. depthTexture._framebuffer = framebuffer;
  9430. depthTexture._baseWidth = width;
  9431. depthTexture._baseHeight = height;
  9432. depthTexture._width = width;
  9433. depthTexture._height = height;
  9434. depthTexture.isReady = true;
  9435. depthTexture.samples = 1;
  9436. depthTexture.generateMipMaps = generateMipMaps;
  9437. depthTexture.references = 1;
  9438. depthTexture.samplingMode = gl.NEAREST;
  9439. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9440. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9441. textures.push(depthTexture);
  9442. this._loadedTexturesCache.push(depthTexture);
  9443. }
  9444. gl.drawBuffers(attachments);
  9445. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9446. this.bindUnboundFramebuffer(null);
  9447. this.resetTextureCache();
  9448. return textures;
  9449. };
  9450. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9451. if (samples === void 0) { samples = 1; }
  9452. var depthStencilBuffer = null;
  9453. var gl = this._gl;
  9454. // Create the depth/stencil buffer
  9455. if (generateStencilBuffer) {
  9456. depthStencilBuffer = gl.createRenderbuffer();
  9457. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9458. if (samples > 1) {
  9459. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9460. }
  9461. else {
  9462. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9463. }
  9464. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9465. }
  9466. else if (generateDepthBuffer) {
  9467. depthStencilBuffer = gl.createRenderbuffer();
  9468. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9469. if (samples > 1) {
  9470. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9471. }
  9472. else {
  9473. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9474. }
  9475. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9476. }
  9477. return depthStencilBuffer;
  9478. };
  9479. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9480. if (this.webGLVersion < 2) {
  9481. return 1;
  9482. }
  9483. if (texture.samples === samples) {
  9484. return samples;
  9485. }
  9486. var gl = this._gl;
  9487. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9488. // Dispose previous render buffers
  9489. if (texture._depthStencilBuffer) {
  9490. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9491. }
  9492. if (texture._MSAAFramebuffer) {
  9493. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9494. }
  9495. if (texture._MSAARenderBuffer) {
  9496. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9497. }
  9498. if (samples > 1) {
  9499. texture._MSAAFramebuffer = gl.createFramebuffer();
  9500. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9501. var colorRenderbuffer = gl.createRenderbuffer();
  9502. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9503. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9504. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9505. texture._MSAARenderBuffer = colorRenderbuffer;
  9506. }
  9507. else {
  9508. this.bindUnboundFramebuffer(texture._framebuffer);
  9509. }
  9510. texture.samples = samples;
  9511. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9512. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9513. this.bindUnboundFramebuffer(null);
  9514. return samples;
  9515. };
  9516. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9517. var gl = this._gl;
  9518. var texture = gl.createTexture();
  9519. var generateMipMaps = true;
  9520. var generateDepthBuffer = true;
  9521. var generateStencilBuffer = false;
  9522. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9523. if (options !== undefined) {
  9524. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9525. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9526. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9527. if (options.samplingMode !== undefined) {
  9528. samplingMode = options.samplingMode;
  9529. }
  9530. }
  9531. texture.isCube = true;
  9532. texture.references = 1;
  9533. texture.generateMipMaps = generateMipMaps;
  9534. texture.references = 1;
  9535. texture.samples = 1;
  9536. texture.samplingMode = samplingMode;
  9537. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9538. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9539. for (var face = 0; face < 6; face++) {
  9540. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9541. }
  9542. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9543. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9546. // Create the framebuffer
  9547. var framebuffer = gl.createFramebuffer();
  9548. this.bindUnboundFramebuffer(framebuffer);
  9549. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9550. // Mipmaps
  9551. if (texture.generateMipMaps) {
  9552. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9553. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9554. }
  9555. // Unbind
  9556. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9557. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9558. this.bindUnboundFramebuffer(null);
  9559. texture._framebuffer = framebuffer;
  9560. texture._width = size;
  9561. texture._height = size;
  9562. texture.isReady = true;
  9563. this.resetTextureCache();
  9564. this._loadedTexturesCache.push(texture);
  9565. return texture;
  9566. };
  9567. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9568. var _this = this;
  9569. if (onLoad === void 0) { onLoad = null; }
  9570. if (onError === void 0) { onError = null; }
  9571. var gl = this._gl;
  9572. var texture = gl.createTexture();
  9573. texture.isCube = true;
  9574. texture.url = rootUrl;
  9575. texture.references = 1;
  9576. texture.onLoadedCallbacks = [];
  9577. var isKTX = false;
  9578. var lastDot = rootUrl.lastIndexOf('.');
  9579. var extension = rootUrl.substring(lastDot).toLowerCase();
  9580. if (this._textureFormatInUse) {
  9581. extension = this._textureFormatInUse;
  9582. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9583. isKTX = true;
  9584. }
  9585. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9586. if (isDDS) {
  9587. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9588. }
  9589. if (isKTX) {
  9590. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9591. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9592. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9593. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9594. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9595. ktx.uploadLevels(_this._gl, !noMipmap);
  9596. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9597. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9600. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9601. _this.resetTextureCache();
  9602. texture._width = ktx.pixelWidth;
  9603. texture._height = ktx.pixelHeight;
  9604. texture.isReady = true;
  9605. }, null, null, true, onError);
  9606. }
  9607. else if (isDDS) {
  9608. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9609. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9610. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9611. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9612. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9613. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9614. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9615. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9616. }
  9617. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9618. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9619. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9620. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9621. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9622. _this.resetTextureCache();
  9623. texture._width = info.width;
  9624. texture._height = info.height;
  9625. texture.isReady = true;
  9626. }, null, null, true, onError);
  9627. }
  9628. else {
  9629. cascadeLoad(rootUrl, scene, function (imgs) {
  9630. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9631. var height = width;
  9632. _this._prepareWorkingCanvas();
  9633. _this._workingCanvas.width = width;
  9634. _this._workingCanvas.height = height;
  9635. var faces = [
  9636. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9637. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9638. ];
  9639. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9640. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9641. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9642. for (var index = 0; index < faces.length; index++) {
  9643. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9644. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9645. }
  9646. if (!noMipmap) {
  9647. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9648. }
  9649. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9650. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9651. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9652. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9653. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9654. _this.resetTextureCache();
  9655. texture._width = width;
  9656. texture._height = height;
  9657. texture.isReady = true;
  9658. texture.onLoadedCallbacks.forEach(function (callback) {
  9659. callback();
  9660. });
  9661. if (onLoad) {
  9662. onLoad();
  9663. }
  9664. }, files, onError);
  9665. }
  9666. this._loadedTexturesCache.push(texture);
  9667. return texture;
  9668. };
  9669. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9670. texture._width = width;
  9671. texture._height = height;
  9672. texture._size = width * height;
  9673. texture._baseWidth = width;
  9674. texture._baseHeight = height;
  9675. };
  9676. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9677. if (compression === void 0) { compression = null; }
  9678. if (level === void 0) { level = 0; }
  9679. var gl = this._gl;
  9680. var textureType = this._getWebGLTextureType(type);
  9681. var internalFormat = this._getInternalFormat(format);
  9682. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9683. var needConversion = false;
  9684. if (internalFormat === gl.RGB) {
  9685. internalFormat = gl.RGBA;
  9686. needConversion = true;
  9687. }
  9688. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9689. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9690. if (texture._width % 4 !== 0) {
  9691. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9692. }
  9693. var facesIndex = [
  9694. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9695. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9696. ];
  9697. // Data are known to be in +X +Y +Z -X -Y -Z
  9698. for (var index = 0; index < facesIndex.length; index++) {
  9699. var faceData = data[index];
  9700. if (compression) {
  9701. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9702. }
  9703. else {
  9704. if (needConversion) {
  9705. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9706. }
  9707. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9708. }
  9709. }
  9710. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9711. if (isPot && texture.generateMipMaps && level === 0) {
  9712. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9713. }
  9714. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9715. this.resetTextureCache();
  9716. texture.isReady = true;
  9717. };
  9718. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9719. if (compression === void 0) { compression = null; }
  9720. var gl = this._gl;
  9721. var texture = gl.createTexture();
  9722. texture.isCube = true;
  9723. texture.references = 1;
  9724. var textureType = this._getWebGLTextureType(type);
  9725. var internalFormat = this._getInternalFormat(format);
  9726. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9727. var needConversion = false;
  9728. if (internalFormat === gl.RGB) {
  9729. internalFormat = gl.RGBA;
  9730. needConversion = true;
  9731. }
  9732. var width = size;
  9733. var height = width;
  9734. texture._width = width;
  9735. texture._height = height;
  9736. // Double check on POT to generate Mips.
  9737. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9738. if (!isPot) {
  9739. generateMipMaps = false;
  9740. }
  9741. texture.generateMipMaps = generateMipMaps;
  9742. // Upload data if needed. The texture won t be ready until then.
  9743. if (data) {
  9744. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9745. }
  9746. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9747. // Filters
  9748. if (data && generateMipMaps) {
  9749. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9750. }
  9751. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9752. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9753. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9754. }
  9755. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9758. }
  9759. else {
  9760. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9763. }
  9764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9765. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9766. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9767. this._loadedTexturesCache.push(texture);
  9768. return texture;
  9769. };
  9770. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9771. var _this = this;
  9772. if (onLoad === void 0) { onLoad = null; }
  9773. if (onError === void 0) { onError = null; }
  9774. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9775. if (invertY === void 0) { invertY = false; }
  9776. var gl = this._gl;
  9777. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9778. scene._addPendingData(texture);
  9779. texture.url = url;
  9780. var onerror = function () {
  9781. scene._removePendingData(texture);
  9782. if (onError) {
  9783. onError();
  9784. }
  9785. };
  9786. var internalCallback = function (data) {
  9787. var rgbeDataArrays = callback(data);
  9788. var facesIndex = [
  9789. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9790. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9791. ];
  9792. var width = texture._width;
  9793. var height = texture._height;
  9794. if (mipmmapGenerator) {
  9795. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9796. // I ll remove ASAP.
  9797. var textureType = _this._getWebGLTextureType(type);
  9798. var internalFormat = _this._getInternalFormat(format);
  9799. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9800. var needConversion = false;
  9801. if (internalFormat === gl.RGB) {
  9802. internalFormat = gl.RGBA;
  9803. needConversion = true;
  9804. }
  9805. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9806. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9807. var arrayTemp = [];
  9808. // Data are known to be in +X +Y +Z -X -Y -Z
  9809. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9810. arrayTemp.push(rgbeDataArrays[0]); // +X
  9811. arrayTemp.push(rgbeDataArrays[3]); // -X
  9812. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9813. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9814. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9815. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9816. var mipData = mipmmapGenerator(arrayTemp);
  9817. // mipData is order in +X -X +Y -Y +Z -Z
  9818. var mipFaces = [0, 2, 4, 1, 3, 5];
  9819. for (var level = 0; level < mipData.length; level++) {
  9820. var mipSize = width >> level;
  9821. for (var mipIndex in mipFaces) {
  9822. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9823. if (needConversion) {
  9824. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9825. }
  9826. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9827. }
  9828. }
  9829. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9830. }
  9831. else {
  9832. texture.generateMipMaps = !noMipmap;
  9833. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9834. }
  9835. texture.isReady = true;
  9836. _this.resetTextureCache();
  9837. scene._removePendingData(texture);
  9838. if (onLoad) {
  9839. onLoad();
  9840. }
  9841. };
  9842. BABYLON.Tools.LoadFile(url, function (data) {
  9843. internalCallback(data);
  9844. }, onerror, scene.database, true);
  9845. return texture;
  9846. };
  9847. ;
  9848. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9849. // Create new RGBA data container.
  9850. var rgbaData;
  9851. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9852. rgbaData = new Float32Array(width * height * 4);
  9853. }
  9854. else {
  9855. rgbaData = new Uint32Array(width * height * 4);
  9856. }
  9857. // Convert each pixel.
  9858. for (var x = 0; x < width; x++) {
  9859. for (var y = 0; y < height; y++) {
  9860. var index = (y * width + x) * 3;
  9861. var newIndex = (y * width + x) * 4;
  9862. // Map Old Value to new value.
  9863. rgbaData[newIndex + 0] = rgbData[index + 0];
  9864. rgbaData[newIndex + 1] = rgbData[index + 1];
  9865. rgbaData[newIndex + 2] = rgbData[index + 2];
  9866. // Add fully opaque alpha channel.
  9867. rgbaData[newIndex + 3] = 1;
  9868. }
  9869. }
  9870. return rgbaData;
  9871. };
  9872. Engine.prototype._releaseTexture = function (texture) {
  9873. var gl = this._gl;
  9874. if (texture._framebuffer) {
  9875. gl.deleteFramebuffer(texture._framebuffer);
  9876. }
  9877. if (texture._depthStencilBuffer) {
  9878. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9879. }
  9880. if (texture._MSAAFramebuffer) {
  9881. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9882. }
  9883. if (texture._MSAARenderBuffer) {
  9884. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9885. }
  9886. gl.deleteTexture(texture);
  9887. // Unbind channels
  9888. this.unbindAllTextures();
  9889. var index = this._loadedTexturesCache.indexOf(texture);
  9890. if (index !== -1) {
  9891. this._loadedTexturesCache.splice(index, 1);
  9892. }
  9893. };
  9894. Engine.prototype.setProgram = function (program) {
  9895. if (this._currentProgram !== program) {
  9896. this._gl.useProgram(program);
  9897. this._currentProgram = program;
  9898. }
  9899. };
  9900. Engine.prototype.bindSamplers = function (effect) {
  9901. this.setProgram(effect.getProgram());
  9902. var samplers = effect.getSamplers();
  9903. for (var index = 0; index < samplers.length; index++) {
  9904. var uniform = effect.getUniform(samplers[index]);
  9905. this._gl.uniform1i(uniform, index);
  9906. }
  9907. this._currentEffect = null;
  9908. };
  9909. Engine.prototype.activateTexture = function (texture) {
  9910. if (this._activeTexture !== texture) {
  9911. this._gl.activeTexture(texture);
  9912. this._activeTexture = texture;
  9913. }
  9914. };
  9915. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9916. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9917. this._gl.bindTexture(target, texture);
  9918. this._activeTexturesCache[this._activeTexture] = texture;
  9919. }
  9920. };
  9921. Engine.prototype._bindTexture = function (channel, texture) {
  9922. if (channel < 0) {
  9923. return;
  9924. }
  9925. this.activateTexture(this._gl.TEXTURE0 + channel);
  9926. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9927. };
  9928. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9929. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9930. };
  9931. Engine.prototype.unbindAllTextures = function () {
  9932. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9933. this.activateTexture(this._gl["TEXTURE" + channel]);
  9934. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9935. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9936. }
  9937. };
  9938. Engine.prototype.setTexture = function (channel, uniform, texture) {
  9939. if (channel < 0) {
  9940. return;
  9941. }
  9942. this._gl.uniform1i(uniform, channel);
  9943. this._setTexture(channel, texture);
  9944. };
  9945. Engine.prototype._setTexture = function (channel, texture) {
  9946. // Not ready?
  9947. if (!texture) {
  9948. if (this._activeTexturesCache[channel] != null) {
  9949. this.activateTexture(this._gl["TEXTURE" + channel]);
  9950. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9951. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9952. }
  9953. return;
  9954. }
  9955. // Video
  9956. var alreadyActivated = false;
  9957. if (texture.video) {
  9958. this.activateTexture(this._gl["TEXTURE" + channel]);
  9959. alreadyActivated = true;
  9960. texture.update();
  9961. }
  9962. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  9963. texture.delayLoad();
  9964. return;
  9965. }
  9966. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  9967. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  9968. if (this._activeTexturesCache[channel] === internalTexture) {
  9969. return;
  9970. }
  9971. if (!alreadyActivated) {
  9972. this.activateTexture(this._gl["TEXTURE" + channel]);
  9973. }
  9974. if (internalTexture.isCube) {
  9975. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  9976. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  9977. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  9978. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  9979. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  9980. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  9981. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  9982. }
  9983. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  9984. }
  9985. else {
  9986. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  9987. if (internalTexture._cachedWrapU !== texture.wrapU) {
  9988. internalTexture._cachedWrapU = texture.wrapU;
  9989. switch (texture.wrapU) {
  9990. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9991. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  9992. break;
  9993. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9994. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  9995. break;
  9996. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9997. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  9998. break;
  9999. }
  10000. }
  10001. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10002. internalTexture._cachedWrapV = texture.wrapV;
  10003. switch (texture.wrapV) {
  10004. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10005. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10006. break;
  10007. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10008. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10009. break;
  10010. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10011. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10012. break;
  10013. }
  10014. }
  10015. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10016. }
  10017. };
  10018. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10019. if (channel < 0) {
  10020. return;
  10021. }
  10022. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10023. this._textureUnits = new Int32Array(textures.length);
  10024. }
  10025. for (var i = 0; i < textures.length; i++) {
  10026. this._textureUnits[i] = channel + i;
  10027. }
  10028. this._gl.uniform1iv(uniform, this._textureUnits);
  10029. for (var index = 0; index < textures.length; index++) {
  10030. this._setTexture(channel + index, textures[index]);
  10031. }
  10032. };
  10033. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10034. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10035. var value = texture.anisotropicFilteringLevel;
  10036. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10037. value = 1;
  10038. }
  10039. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10040. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10041. texture._cachedAnisotropicFilteringLevel = value;
  10042. }
  10043. };
  10044. Engine.prototype.readPixels = function (x, y, width, height) {
  10045. var data = new Uint8Array(height * width * 4);
  10046. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10047. return data;
  10048. };
  10049. /**
  10050. * Add an externaly attached data from its key.
  10051. * This method call will fail and return false, if such key already exists.
  10052. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10053. * @param key the unique key that identifies the data
  10054. * @param data the data object to associate to the key for this Engine instance
  10055. * @return true if no such key were already present and the data was added successfully, false otherwise
  10056. */
  10057. Engine.prototype.addExternalData = function (key, data) {
  10058. if (!this._externalData) {
  10059. this._externalData = new BABYLON.StringDictionary();
  10060. }
  10061. return this._externalData.add(key, data);
  10062. };
  10063. /**
  10064. * Get an externaly attached data from its key
  10065. * @param key the unique key that identifies the data
  10066. * @return the associated data, if present (can be null), or undefined if not present
  10067. */
  10068. Engine.prototype.getExternalData = function (key) {
  10069. if (!this._externalData) {
  10070. this._externalData = new BABYLON.StringDictionary();
  10071. }
  10072. return this._externalData.get(key);
  10073. };
  10074. /**
  10075. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10076. * @param key the unique key that identifies the data
  10077. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10078. * @return the associated data, can be null if the factory returned null.
  10079. */
  10080. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10081. if (!this._externalData) {
  10082. this._externalData = new BABYLON.StringDictionary();
  10083. }
  10084. return this._externalData.getOrAddWithFactory(key, factory);
  10085. };
  10086. /**
  10087. * Remove an externaly attached data from the Engine instance
  10088. * @param key the unique key that identifies the data
  10089. * @return true if the data was successfully removed, false if it doesn't exist
  10090. */
  10091. Engine.prototype.removeExternalData = function (key) {
  10092. if (!this._externalData) {
  10093. this._externalData = new BABYLON.StringDictionary();
  10094. }
  10095. return this._externalData.remove(key);
  10096. };
  10097. Engine.prototype.releaseInternalTexture = function (texture) {
  10098. if (!texture) {
  10099. return;
  10100. }
  10101. texture.references--;
  10102. // Final reference ?
  10103. if (texture.references === 0) {
  10104. var texturesCache = this.getLoadedTexturesCache();
  10105. var index = texturesCache.indexOf(texture);
  10106. if (index > -1) {
  10107. texturesCache.splice(index, 1);
  10108. }
  10109. this._releaseTexture(texture);
  10110. }
  10111. };
  10112. Engine.prototype.unbindAllAttributes = function () {
  10113. if (this._mustWipeVertexAttributes) {
  10114. this._mustWipeVertexAttributes = false;
  10115. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10116. this._gl.disableVertexAttribArray(i);
  10117. this._vertexAttribArraysEnabled[i] = false;
  10118. this._currentBufferPointers[i] = null;
  10119. }
  10120. return;
  10121. }
  10122. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10123. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10124. continue;
  10125. }
  10126. this._gl.disableVertexAttribArray(i);
  10127. this._vertexAttribArraysEnabled[i] = false;
  10128. this._currentBufferPointers[i] = null;
  10129. }
  10130. };
  10131. Engine.prototype.releaseEffects = function () {
  10132. for (var name in this._compiledEffects) {
  10133. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10134. }
  10135. this._compiledEffects = {};
  10136. };
  10137. // Dispose
  10138. Engine.prototype.dispose = function () {
  10139. this.hideLoadingUI();
  10140. this.stopRenderLoop();
  10141. // Empty texture
  10142. if (this._emptyTexture) {
  10143. this._releaseTexture(this._emptyTexture);
  10144. this._emptyTexture = null;
  10145. }
  10146. if (this._emptyCubeTexture) {
  10147. this._releaseTexture(this._emptyCubeTexture);
  10148. this._emptyCubeTexture = null;
  10149. }
  10150. // Release scenes
  10151. while (this.scenes.length) {
  10152. this.scenes[0].dispose();
  10153. }
  10154. // Release audio engine
  10155. if (Engine.audioEngine) {
  10156. Engine.audioEngine.dispose();
  10157. }
  10158. // Release effects
  10159. this.releaseEffects();
  10160. // Unbind
  10161. this.unbindAllAttributes();
  10162. this._gl = null;
  10163. //WebVR
  10164. this.disableVR();
  10165. // Events
  10166. window.removeEventListener("blur", this._onBlur);
  10167. window.removeEventListener("focus", this._onFocus);
  10168. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10169. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10170. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10171. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10172. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10173. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10174. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10175. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10176. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10177. // Remove from Instances
  10178. var index = Engine.Instances.indexOf(this);
  10179. if (index >= 0) {
  10180. Engine.Instances.splice(index, 1);
  10181. }
  10182. };
  10183. // Loading screen
  10184. Engine.prototype.displayLoadingUI = function () {
  10185. var loadingScreen = this.loadingScreen;
  10186. if (loadingScreen) {
  10187. loadingScreen.displayLoadingUI();
  10188. }
  10189. };
  10190. Engine.prototype.hideLoadingUI = function () {
  10191. var loadingScreen = this.loadingScreen;
  10192. if (loadingScreen) {
  10193. loadingScreen.hideLoadingUI();
  10194. }
  10195. };
  10196. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10197. get: function () {
  10198. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10199. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10200. return this._loadingScreen;
  10201. },
  10202. set: function (loadingScreen) {
  10203. this._loadingScreen = loadingScreen;
  10204. },
  10205. enumerable: true,
  10206. configurable: true
  10207. });
  10208. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10209. set: function (text) {
  10210. this.loadingScreen.loadingUIText = text;
  10211. },
  10212. enumerable: true,
  10213. configurable: true
  10214. });
  10215. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10216. set: function (color) {
  10217. this.loadingScreen.loadingUIBackgroundColor = color;
  10218. },
  10219. enumerable: true,
  10220. configurable: true
  10221. });
  10222. Engine.prototype.attachContextLostEvent = function (callback) {
  10223. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10224. };
  10225. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10226. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10227. };
  10228. Engine.prototype.getVertexShaderSource = function (program) {
  10229. var shaders = this._gl.getAttachedShaders(program);
  10230. return this._gl.getShaderSource(shaders[0]);
  10231. };
  10232. Engine.prototype.getFragmentShaderSource = function (program) {
  10233. var shaders = this._gl.getAttachedShaders(program);
  10234. return this._gl.getShaderSource(shaders[1]);
  10235. };
  10236. // FPS
  10237. Engine.prototype.getFps = function () {
  10238. return this.fps;
  10239. };
  10240. Engine.prototype.getDeltaTime = function () {
  10241. return this.deltaTime;
  10242. };
  10243. Engine.prototype._measureFps = function () {
  10244. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10245. var length = this.previousFramesDuration.length;
  10246. if (length >= 2) {
  10247. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10248. }
  10249. if (length >= this.fpsRange) {
  10250. if (length > this.fpsRange) {
  10251. this.previousFramesDuration.splice(0, 1);
  10252. length = this.previousFramesDuration.length;
  10253. }
  10254. var sum = 0;
  10255. for (var id = 0; id < length - 1; id++) {
  10256. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10257. }
  10258. this.fps = 1000.0 / (sum / (length - 1));
  10259. }
  10260. };
  10261. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10262. if (this._webGLVersion > 1) {
  10263. return this._caps.colorBufferFloat;
  10264. }
  10265. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10266. };
  10267. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10268. if (this._webGLVersion > 1) {
  10269. return this._caps.colorBufferFloat;
  10270. }
  10271. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10272. };
  10273. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10274. Engine.prototype._canRenderToFramebuffer = function (type) {
  10275. var gl = this._gl;
  10276. //clear existing errors
  10277. while (gl.getError() !== gl.NO_ERROR) { }
  10278. var successful = true;
  10279. var texture = gl.createTexture();
  10280. gl.bindTexture(gl.TEXTURE_2D, texture);
  10281. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10284. var fb = gl.createFramebuffer();
  10285. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10286. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10287. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10288. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10289. successful = successful && (gl.getError() === gl.NO_ERROR);
  10290. //try render by clearing frame buffer's color buffer
  10291. if (successful) {
  10292. gl.clear(gl.COLOR_BUFFER_BIT);
  10293. successful = successful && (gl.getError() === gl.NO_ERROR);
  10294. }
  10295. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10296. if (successful) {
  10297. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10298. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10299. var readFormat = gl.RGBA;
  10300. var readType = gl.UNSIGNED_BYTE;
  10301. var buffer = new Uint8Array(4);
  10302. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10303. successful = successful && (gl.getError() === gl.NO_ERROR);
  10304. }
  10305. //clean up
  10306. gl.deleteTexture(texture);
  10307. gl.deleteFramebuffer(fb);
  10308. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10309. //clear accumulated errors
  10310. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10311. return successful;
  10312. };
  10313. Engine.prototype._getWebGLTextureType = function (type) {
  10314. if (type === Engine.TEXTURETYPE_FLOAT) {
  10315. return this._gl.FLOAT;
  10316. }
  10317. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10318. // Add Half Float Constant.
  10319. return Engine.HALF_FLOAT_OES;
  10320. }
  10321. return this._gl.UNSIGNED_BYTE;
  10322. };
  10323. ;
  10324. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10325. if (this._webGLVersion === 1) {
  10326. return this._gl.RGBA;
  10327. }
  10328. if (type === Engine.TEXTURETYPE_FLOAT) {
  10329. return Engine.RGBA32F;
  10330. }
  10331. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10332. return Engine.RGBA16F;
  10333. }
  10334. return this._gl.RGBA;
  10335. };
  10336. ;
  10337. // Statics
  10338. Engine.isSupported = function () {
  10339. try {
  10340. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10341. if (navigator.isCocoonJS) {
  10342. return true;
  10343. }
  10344. var tempcanvas = document.createElement("canvas");
  10345. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10346. return gl != null && !!window.WebGLRenderingContext;
  10347. }
  10348. catch (e) {
  10349. return false;
  10350. }
  10351. };
  10352. return Engine;
  10353. }());
  10354. Engine.Instances = new Array();
  10355. // Const statics
  10356. Engine._ALPHA_DISABLE = 0;
  10357. Engine._ALPHA_ADD = 1;
  10358. Engine._ALPHA_COMBINE = 2;
  10359. Engine._ALPHA_SUBTRACT = 3;
  10360. Engine._ALPHA_MULTIPLY = 4;
  10361. Engine._ALPHA_MAXIMIZED = 5;
  10362. Engine._ALPHA_ONEONE = 6;
  10363. Engine._ALPHA_PREMULTIPLIED = 7;
  10364. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10365. Engine._ALPHA_INTERPOLATE = 9;
  10366. Engine._ALPHA_SCREENMODE = 10;
  10367. Engine._DELAYLOADSTATE_NONE = 0;
  10368. Engine._DELAYLOADSTATE_LOADED = 1;
  10369. Engine._DELAYLOADSTATE_LOADING = 2;
  10370. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10371. Engine._TEXTUREFORMAT_ALPHA = 0;
  10372. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10373. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10374. Engine._TEXTUREFORMAT_RGB = 4;
  10375. Engine._TEXTUREFORMAT_RGBA = 5;
  10376. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10377. Engine._TEXTURETYPE_FLOAT = 1;
  10378. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10379. // Depht or Stencil test Constants.
  10380. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10381. 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.
  10382. 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.
  10383. 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.
  10384. 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.
  10385. 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.
  10386. 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.
  10387. 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.
  10388. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10389. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10390. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10391. // Stencil Actions Constants.
  10392. Engine._KEEP = 0x1E00;
  10393. Engine._REPLACE = 0x1E01;
  10394. Engine._INCR = 0x1E02;
  10395. Engine._DECR = 0x1E03;
  10396. Engine._INVERT = 0x150A;
  10397. Engine._INCR_WRAP = 0x8507;
  10398. Engine._DECR_WRAP = 0x8508;
  10399. // Updatable statics so stick with vars here
  10400. Engine.CollisionsEpsilon = 0.001;
  10401. Engine.CodeRepository = "src/";
  10402. Engine.ShadersRepository = "src/Shaders/";
  10403. BABYLON.Engine = Engine;
  10404. })(BABYLON || (BABYLON = {}));
  10405. //# sourceMappingURL=babylon.engine.js.map
  10406. /// <reference path="Tools\babylon.decorators.ts" />
  10407. var BABYLON;
  10408. (function (BABYLON) {
  10409. /**
  10410. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10411. */
  10412. var Node = (function () {
  10413. /**
  10414. * @constructor
  10415. * @param {string} name - the name and id to be given to this node
  10416. * @param {BABYLON.Scene} the scene this node will be added to
  10417. */
  10418. function Node(name, scene) {
  10419. this.state = "";
  10420. this.metadata = null;
  10421. this.doNotSerialize = false;
  10422. this.animations = new Array();
  10423. this._ranges = {};
  10424. this._childrenFlag = -1;
  10425. this._isEnabled = true;
  10426. this._isReady = true;
  10427. this._currentRenderId = -1;
  10428. this._parentRenderId = -1;
  10429. /**
  10430. * An event triggered when the mesh is disposed.
  10431. * @type {BABYLON.Observable}
  10432. */
  10433. this.onDisposeObservable = new BABYLON.Observable();
  10434. this.name = name;
  10435. this.id = name;
  10436. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10437. this._initCache();
  10438. }
  10439. Object.defineProperty(Node.prototype, "parent", {
  10440. get: function () {
  10441. return this._parentNode;
  10442. },
  10443. set: function (parent) {
  10444. if (this._parentNode === parent) {
  10445. return;
  10446. }
  10447. if (this._parentNode) {
  10448. var index = this._parentNode._children.indexOf(this);
  10449. if (index !== -1) {
  10450. this._parentNode._children.splice(index, 1);
  10451. }
  10452. }
  10453. this._parentNode = parent;
  10454. if (this._parentNode) {
  10455. if (!this._parentNode._children) {
  10456. this._parentNode._children = new Array();
  10457. }
  10458. this._parentNode._children.push(this);
  10459. }
  10460. },
  10461. enumerable: true,
  10462. configurable: true
  10463. });
  10464. Node.prototype.getClassName = function () {
  10465. return "Node";
  10466. };
  10467. Object.defineProperty(Node.prototype, "onDispose", {
  10468. set: function (callback) {
  10469. if (this._onDisposeObserver) {
  10470. this.onDisposeObservable.remove(this._onDisposeObserver);
  10471. }
  10472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10473. },
  10474. enumerable: true,
  10475. configurable: true
  10476. });
  10477. Node.prototype.getScene = function () {
  10478. return this._scene;
  10479. };
  10480. Node.prototype.getEngine = function () {
  10481. return this._scene.getEngine();
  10482. };
  10483. // override it in derived class
  10484. Node.prototype.getWorldMatrix = function () {
  10485. return BABYLON.Matrix.Identity();
  10486. };
  10487. // override it in derived class if you add new variables to the cache
  10488. // and call the parent class method
  10489. Node.prototype._initCache = function () {
  10490. this._cache = {};
  10491. this._cache.parent = undefined;
  10492. };
  10493. Node.prototype.updateCache = function (force) {
  10494. if (!force && this.isSynchronized())
  10495. return;
  10496. this._cache.parent = this.parent;
  10497. this._updateCache();
  10498. };
  10499. // override it in derived class if you add new variables to the cache
  10500. // and call the parent class method if !ignoreParentClass
  10501. Node.prototype._updateCache = function (ignoreParentClass) {
  10502. };
  10503. // override it in derived class if you add new variables to the cache
  10504. Node.prototype._isSynchronized = function () {
  10505. return true;
  10506. };
  10507. Node.prototype._markSyncedWithParent = function () {
  10508. this._parentRenderId = this.parent._currentRenderId;
  10509. };
  10510. Node.prototype.isSynchronizedWithParent = function () {
  10511. if (!this.parent) {
  10512. return true;
  10513. }
  10514. if (this._parentRenderId !== this.parent._currentRenderId) {
  10515. return false;
  10516. }
  10517. return this.parent.isSynchronized();
  10518. };
  10519. Node.prototype.isSynchronized = function (updateCache) {
  10520. var check = this.hasNewParent();
  10521. check = check || !this.isSynchronizedWithParent();
  10522. check = check || !this._isSynchronized();
  10523. if (updateCache)
  10524. this.updateCache(true);
  10525. return !check;
  10526. };
  10527. Node.prototype.hasNewParent = function (update) {
  10528. if (this._cache.parent === this.parent)
  10529. return false;
  10530. if (update)
  10531. this._cache.parent = this.parent;
  10532. return true;
  10533. };
  10534. /**
  10535. * Is this node ready to be used/rendered
  10536. * @return {boolean} is it ready
  10537. */
  10538. Node.prototype.isReady = function () {
  10539. return this._isReady;
  10540. };
  10541. /**
  10542. * Is this node enabled.
  10543. * If the node has a parent and is enabled, the parent will be inspected as well.
  10544. * @return {boolean} whether this node (and its parent) is enabled.
  10545. * @see setEnabled
  10546. */
  10547. Node.prototype.isEnabled = function () {
  10548. if (!this._isEnabled) {
  10549. return false;
  10550. }
  10551. if (this.parent) {
  10552. return this.parent.isEnabled();
  10553. }
  10554. return true;
  10555. };
  10556. /**
  10557. * Set the enabled state of this node.
  10558. * @param {boolean} value - the new enabled state
  10559. * @see isEnabled
  10560. */
  10561. Node.prototype.setEnabled = function (value) {
  10562. this._isEnabled = value;
  10563. };
  10564. /**
  10565. * Is this node a descendant of the given node.
  10566. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10567. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10568. * @see parent
  10569. */
  10570. Node.prototype.isDescendantOf = function (ancestor) {
  10571. if (this.parent) {
  10572. if (this.parent === ancestor) {
  10573. return true;
  10574. }
  10575. return this.parent.isDescendantOf(ancestor);
  10576. }
  10577. return false;
  10578. };
  10579. /**
  10580. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10581. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10582. * @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.
  10583. * @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.
  10584. */
  10585. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10586. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10587. if (!this._children) {
  10588. return;
  10589. }
  10590. for (var index = 0; index < this._children.length; index++) {
  10591. var item = this._children[index];
  10592. if (!predicate || predicate(item)) {
  10593. results.push(item);
  10594. }
  10595. if (!directDescendantsOnly) {
  10596. item._getDescendants(results, false, predicate);
  10597. }
  10598. }
  10599. };
  10600. /**
  10601. * Will return all nodes that have this node as ascendant.
  10602. * @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.
  10603. * @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.
  10604. * @return {BABYLON.Node[]} all children nodes of all types.
  10605. */
  10606. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10607. var results = [];
  10608. this._getDescendants(results, directDescendantsOnly, predicate);
  10609. return results;
  10610. };
  10611. /**
  10612. * Get all child-meshes of this node.
  10613. */
  10614. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10615. var results = [];
  10616. this._getDescendants(results, directDecendantsOnly, function (node) {
  10617. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10618. });
  10619. return results;
  10620. };
  10621. /**
  10622. * Get all direct children of this node.
  10623. */
  10624. Node.prototype.getChildren = function (predicate) {
  10625. return this.getDescendants(true, predicate);
  10626. };
  10627. Node.prototype._setReady = function (state) {
  10628. if (state === this._isReady) {
  10629. return;
  10630. }
  10631. if (!state) {
  10632. this._isReady = false;
  10633. return;
  10634. }
  10635. this._isReady = true;
  10636. if (this.onReady) {
  10637. this.onReady(this);
  10638. }
  10639. };
  10640. Node.prototype.getAnimationByName = function (name) {
  10641. for (var i = 0; i < this.animations.length; i++) {
  10642. var animation = this.animations[i];
  10643. if (animation.name === name) {
  10644. return animation;
  10645. }
  10646. }
  10647. return null;
  10648. };
  10649. Node.prototype.createAnimationRange = function (name, from, to) {
  10650. // check name not already in use
  10651. if (!this._ranges[name]) {
  10652. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10653. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10654. if (this.animations[i]) {
  10655. this.animations[i].createRange(name, from, to);
  10656. }
  10657. }
  10658. }
  10659. };
  10660. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10661. if (deleteFrames === void 0) { deleteFrames = true; }
  10662. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10663. if (this.animations[i]) {
  10664. this.animations[i].deleteRange(name, deleteFrames);
  10665. }
  10666. }
  10667. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10668. };
  10669. Node.prototype.getAnimationRange = function (name) {
  10670. return this._ranges[name];
  10671. };
  10672. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10673. var range = this.getAnimationRange(name);
  10674. if (!range) {
  10675. return null;
  10676. }
  10677. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10678. };
  10679. Node.prototype.serializeAnimationRanges = function () {
  10680. var serializationRanges = [];
  10681. for (var name in this._ranges) {
  10682. var range = {};
  10683. range.name = name;
  10684. range.from = this._ranges[name].from;
  10685. range.to = this._ranges[name].to;
  10686. serializationRanges.push(range);
  10687. }
  10688. return serializationRanges;
  10689. };
  10690. Node.prototype.dispose = function () {
  10691. this.parent = null;
  10692. // Callback
  10693. this.onDisposeObservable.notifyObservers(this);
  10694. this.onDisposeObservable.clear();
  10695. };
  10696. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10697. if (parsedNode.ranges) {
  10698. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10699. var data = parsedNode.ranges[index];
  10700. node.createAnimationRange(data.name, data.from, data.to);
  10701. }
  10702. }
  10703. };
  10704. return Node;
  10705. }());
  10706. __decorate([
  10707. BABYLON.serialize()
  10708. ], Node.prototype, "name", void 0);
  10709. __decorate([
  10710. BABYLON.serialize()
  10711. ], Node.prototype, "id", void 0);
  10712. __decorate([
  10713. BABYLON.serialize()
  10714. ], Node.prototype, "uniqueId", void 0);
  10715. __decorate([
  10716. BABYLON.serialize()
  10717. ], Node.prototype, "state", void 0);
  10718. __decorate([
  10719. BABYLON.serialize()
  10720. ], Node.prototype, "metadata", void 0);
  10721. BABYLON.Node = Node;
  10722. })(BABYLON || (BABYLON = {}));
  10723. //# sourceMappingURL=babylon.node.js.map
  10724. var BABYLON;
  10725. (function (BABYLON) {
  10726. var BoundingSphere = (function () {
  10727. function BoundingSphere(minimum, maximum) {
  10728. this.minimum = minimum;
  10729. this.maximum = maximum;
  10730. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10731. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10732. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10733. this.radius = distance * 0.5;
  10734. this.centerWorld = BABYLON.Vector3.Zero();
  10735. this._update(BABYLON.Matrix.Identity());
  10736. }
  10737. // Methods
  10738. BoundingSphere.prototype._update = function (world) {
  10739. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10740. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10741. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10742. };
  10743. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10744. for (var i = 0; i < 6; i++) {
  10745. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10746. return false;
  10747. }
  10748. return true;
  10749. };
  10750. BoundingSphere.prototype.intersectsPoint = function (point) {
  10751. var x = this.centerWorld.x - point.x;
  10752. var y = this.centerWorld.y - point.y;
  10753. var z = this.centerWorld.z - point.z;
  10754. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10755. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10756. return false;
  10757. return true;
  10758. };
  10759. // Statics
  10760. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10761. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10762. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10763. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10764. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10765. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10766. return false;
  10767. return true;
  10768. };
  10769. return BoundingSphere;
  10770. }());
  10771. BABYLON.BoundingSphere = BoundingSphere;
  10772. })(BABYLON || (BABYLON = {}));
  10773. //# sourceMappingURL=babylon.boundingSphere.js.map
  10774. var BABYLON;
  10775. (function (BABYLON) {
  10776. var BoundingBox = (function () {
  10777. function BoundingBox(minimum, maximum) {
  10778. this.minimum = minimum;
  10779. this.maximum = maximum;
  10780. this.vectors = new Array();
  10781. this.vectorsWorld = new Array();
  10782. // Bounding vectors
  10783. this.vectors.push(this.minimum.clone());
  10784. this.vectors.push(this.maximum.clone());
  10785. this.vectors.push(this.minimum.clone());
  10786. this.vectors[2].x = this.maximum.x;
  10787. this.vectors.push(this.minimum.clone());
  10788. this.vectors[3].y = this.maximum.y;
  10789. this.vectors.push(this.minimum.clone());
  10790. this.vectors[4].z = this.maximum.z;
  10791. this.vectors.push(this.maximum.clone());
  10792. this.vectors[5].z = this.minimum.z;
  10793. this.vectors.push(this.maximum.clone());
  10794. this.vectors[6].x = this.minimum.x;
  10795. this.vectors.push(this.maximum.clone());
  10796. this.vectors[7].y = this.minimum.y;
  10797. // OBB
  10798. this.center = this.maximum.add(this.minimum).scale(0.5);
  10799. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10800. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10801. // World
  10802. for (var index = 0; index < this.vectors.length; index++) {
  10803. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10804. }
  10805. this.minimumWorld = BABYLON.Vector3.Zero();
  10806. this.maximumWorld = BABYLON.Vector3.Zero();
  10807. this.centerWorld = BABYLON.Vector3.Zero();
  10808. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10809. this._update(BABYLON.Matrix.Identity());
  10810. }
  10811. // Methods
  10812. BoundingBox.prototype.getWorldMatrix = function () {
  10813. return this._worldMatrix;
  10814. };
  10815. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10816. this._worldMatrix.copyFrom(matrix);
  10817. return this;
  10818. };
  10819. BoundingBox.prototype._update = function (world) {
  10820. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10821. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10822. for (var index = 0; index < this.vectors.length; index++) {
  10823. var v = this.vectorsWorld[index];
  10824. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10825. if (v.x < this.minimumWorld.x)
  10826. this.minimumWorld.x = v.x;
  10827. if (v.y < this.minimumWorld.y)
  10828. this.minimumWorld.y = v.y;
  10829. if (v.z < this.minimumWorld.z)
  10830. this.minimumWorld.z = v.z;
  10831. if (v.x > this.maximumWorld.x)
  10832. this.maximumWorld.x = v.x;
  10833. if (v.y > this.maximumWorld.y)
  10834. this.maximumWorld.y = v.y;
  10835. if (v.z > this.maximumWorld.z)
  10836. this.maximumWorld.z = v.z;
  10837. }
  10838. // Extend
  10839. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10840. this.extendSizeWorld.scaleInPlace(0.5);
  10841. // OBB
  10842. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10843. this.centerWorld.scaleInPlace(0.5);
  10844. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10845. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10846. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10847. this._worldMatrix = world;
  10848. };
  10849. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10850. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10851. };
  10852. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10853. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10854. };
  10855. BoundingBox.prototype.intersectsPoint = function (point) {
  10856. var delta = -BABYLON.Epsilon;
  10857. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10858. return false;
  10859. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10860. return false;
  10861. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10862. return false;
  10863. return true;
  10864. };
  10865. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10866. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10867. };
  10868. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10869. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10870. return false;
  10871. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10872. return false;
  10873. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10874. return false;
  10875. return true;
  10876. };
  10877. // Statics
  10878. BoundingBox.Intersects = function (box0, box1) {
  10879. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10880. return false;
  10881. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10882. return false;
  10883. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10884. return false;
  10885. return true;
  10886. };
  10887. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10888. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10889. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10890. return (num <= (sphereRadius * sphereRadius));
  10891. };
  10892. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10893. for (var p = 0; p < 6; p++) {
  10894. for (var i = 0; i < 8; i++) {
  10895. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10896. return false;
  10897. }
  10898. }
  10899. }
  10900. return true;
  10901. };
  10902. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10903. for (var p = 0; p < 6; p++) {
  10904. var inCount = 8;
  10905. for (var i = 0; i < 8; i++) {
  10906. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10907. --inCount;
  10908. }
  10909. else {
  10910. break;
  10911. }
  10912. }
  10913. if (inCount === 0)
  10914. return false;
  10915. }
  10916. return true;
  10917. };
  10918. return BoundingBox;
  10919. }());
  10920. BABYLON.BoundingBox = BoundingBox;
  10921. })(BABYLON || (BABYLON = {}));
  10922. //# sourceMappingURL=babylon.boundingBox.js.map
  10923. var BABYLON;
  10924. (function (BABYLON) {
  10925. var computeBoxExtents = function (axis, box) {
  10926. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10927. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10928. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10929. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10930. var r = r0 + r1 + r2;
  10931. return {
  10932. min: p - r,
  10933. max: p + r
  10934. };
  10935. };
  10936. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10937. var axisOverlap = function (axis, box0, box1) {
  10938. var result0 = computeBoxExtents(axis, box0);
  10939. var result1 = computeBoxExtents(axis, box1);
  10940. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10941. };
  10942. var BoundingInfo = (function () {
  10943. function BoundingInfo(minimum, maximum) {
  10944. this.minimum = minimum;
  10945. this.maximum = maximum;
  10946. this._isLocked = false;
  10947. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10948. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10949. }
  10950. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10951. get: function () {
  10952. return this._isLocked;
  10953. },
  10954. set: function (value) {
  10955. this._isLocked = value;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. // Methods
  10961. BoundingInfo.prototype.update = function (world) {
  10962. if (this._isLocked) {
  10963. return;
  10964. }
  10965. this.boundingBox._update(world);
  10966. this.boundingSphere._update(world);
  10967. };
  10968. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10969. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10970. return false;
  10971. return this.boundingBox.isInFrustum(frustumPlanes);
  10972. };
  10973. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10974. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10975. };
  10976. BoundingInfo.prototype._checkCollision = function (collider) {
  10977. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10978. };
  10979. BoundingInfo.prototype.intersectsPoint = function (point) {
  10980. if (!this.boundingSphere.centerWorld) {
  10981. return false;
  10982. }
  10983. if (!this.boundingSphere.intersectsPoint(point)) {
  10984. return false;
  10985. }
  10986. if (!this.boundingBox.intersectsPoint(point)) {
  10987. return false;
  10988. }
  10989. return true;
  10990. };
  10991. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10992. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10993. return false;
  10994. }
  10995. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10996. return false;
  10997. }
  10998. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10999. return false;
  11000. }
  11001. if (!precise) {
  11002. return true;
  11003. }
  11004. var box0 = this.boundingBox;
  11005. var box1 = boundingInfo.boundingBox;
  11006. if (!axisOverlap(box0.directions[0], box0, box1))
  11007. return false;
  11008. if (!axisOverlap(box0.directions[1], box0, box1))
  11009. return false;
  11010. if (!axisOverlap(box0.directions[2], box0, box1))
  11011. return false;
  11012. if (!axisOverlap(box1.directions[0], box0, box1))
  11013. return false;
  11014. if (!axisOverlap(box1.directions[1], box0, box1))
  11015. return false;
  11016. if (!axisOverlap(box1.directions[2], box0, box1))
  11017. return false;
  11018. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11019. return false;
  11020. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11021. return false;
  11022. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11023. return false;
  11024. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11025. return false;
  11026. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11027. return false;
  11028. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11029. return false;
  11030. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11031. return false;
  11032. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11033. return false;
  11034. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11035. return false;
  11036. return true;
  11037. };
  11038. return BoundingInfo;
  11039. }());
  11040. BABYLON.BoundingInfo = BoundingInfo;
  11041. })(BABYLON || (BABYLON = {}));
  11042. //# sourceMappingURL=babylon.boundingInfo.js.map
  11043. var BABYLON;
  11044. (function (BABYLON) {
  11045. var AbstractMesh = (function (_super) {
  11046. __extends(AbstractMesh, _super);
  11047. // Constructor
  11048. function AbstractMesh(name, scene) {
  11049. var _this = _super.call(this, name, scene) || this;
  11050. _this._facetNb = 0; // facet number
  11051. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11052. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11053. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11054. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11055. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11056. _this._subDiv = {
  11057. max: 1,
  11058. X: 1,
  11059. Y: 1,
  11060. Z: 1
  11061. };
  11062. // Events
  11063. /**
  11064. * An event triggered when this mesh collides with another one
  11065. * @type {BABYLON.Observable}
  11066. */
  11067. _this.onCollideObservable = new BABYLON.Observable();
  11068. /**
  11069. * An event triggered when the collision's position changes
  11070. * @type {BABYLON.Observable}
  11071. */
  11072. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11073. /**
  11074. * An event triggered after the world matrix is updated
  11075. * @type {BABYLON.Observable}
  11076. */
  11077. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11078. // Properties
  11079. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11080. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11081. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11082. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11083. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11084. _this.visibility = 1.0;
  11085. _this.alphaIndex = Number.MAX_VALUE;
  11086. _this.infiniteDistance = false;
  11087. _this.isVisible = true;
  11088. _this.isPickable = true;
  11089. _this.showBoundingBox = false;
  11090. _this.showSubMeshesBoundingBox = false;
  11091. _this.isBlocker = false;
  11092. _this.renderingGroupId = 0;
  11093. _this._receiveShadows = false;
  11094. _this.renderOutline = false;
  11095. _this.outlineColor = BABYLON.Color3.Red();
  11096. _this.outlineWidth = 0.02;
  11097. _this.renderOverlay = false;
  11098. _this.overlayColor = BABYLON.Color3.Red();
  11099. _this.overlayAlpha = 0.5;
  11100. _this._hasVertexAlpha = false;
  11101. _this._useVertexColors = true;
  11102. _this._computeBonesUsingShaders = true;
  11103. _this._numBoneInfluencers = 4;
  11104. _this._applyFog = true;
  11105. _this.scalingDeterminant = 1;
  11106. _this.useOctreeForRenderingSelection = true;
  11107. _this.useOctreeForPicking = true;
  11108. _this.useOctreeForCollisions = true;
  11109. _this.layerMask = 0x0FFFFFFF;
  11110. /**
  11111. * True if the mesh must be rendered in any case.
  11112. */
  11113. _this.alwaysSelectAsActiveMesh = false;
  11114. // Collisions
  11115. _this._checkCollisions = false;
  11116. _this._collisionMask = -1;
  11117. _this._collisionGroup = -1;
  11118. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11119. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11120. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11121. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11122. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11123. // Edges
  11124. _this.edgesWidth = 1;
  11125. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11126. // Cache
  11127. _this._localWorld = BABYLON.Matrix.Zero();
  11128. _this._worldMatrix = BABYLON.Matrix.Zero();
  11129. _this._absolutePosition = BABYLON.Vector3.Zero();
  11130. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11131. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11132. _this._isDirty = false;
  11133. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11134. _this._isDisposed = false;
  11135. _this._renderId = 0;
  11136. _this._intersectionsInProgress = new Array();
  11137. _this._isWorldMatrixFrozen = false;
  11138. _this._unIndexed = false;
  11139. _this._lightSources = new Array();
  11140. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11141. if (collidedMesh === void 0) { collidedMesh = null; }
  11142. //TODO move this to the collision coordinator!
  11143. if (_this.getScene().workerCollisions)
  11144. newPosition.multiplyInPlace(_this._collider.radius);
  11145. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11146. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11147. _this.position.addInPlace(_this._diffPositionForCollisions);
  11148. }
  11149. if (collidedMesh) {
  11150. _this.onCollideObservable.notifyObservers(collidedMesh);
  11151. }
  11152. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11153. };
  11154. _this.getScene().addMesh(_this);
  11155. _this._resyncLightSources();
  11156. return _this;
  11157. }
  11158. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11159. get: function () {
  11160. return AbstractMesh._BILLBOARDMODE_NONE;
  11161. },
  11162. enumerable: true,
  11163. configurable: true
  11164. });
  11165. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11166. get: function () {
  11167. return AbstractMesh._BILLBOARDMODE_X;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11173. get: function () {
  11174. return AbstractMesh._BILLBOARDMODE_Y;
  11175. },
  11176. enumerable: true,
  11177. configurable: true
  11178. });
  11179. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11180. get: function () {
  11181. return AbstractMesh._BILLBOARDMODE_Z;
  11182. },
  11183. enumerable: true,
  11184. configurable: true
  11185. });
  11186. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11187. get: function () {
  11188. return AbstractMesh._BILLBOARDMODE_ALL;
  11189. },
  11190. enumerable: true,
  11191. configurable: true
  11192. });
  11193. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11194. /**
  11195. * Read-only : the number of facets in the mesh
  11196. */
  11197. get: function () {
  11198. return this._facetNb;
  11199. },
  11200. enumerable: true,
  11201. configurable: true
  11202. });
  11203. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11204. /**
  11205. * The number (integer) of subdivisions per axis in the partioning space
  11206. */
  11207. get: function () {
  11208. return this._partitioningSubdivisions;
  11209. },
  11210. set: function (nb) {
  11211. this._partitioningSubdivisions = nb;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11217. /**
  11218. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11219. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11220. */
  11221. get: function () {
  11222. return this._partitioningBBoxRatio;
  11223. },
  11224. set: function (ratio) {
  11225. this._partitioningBBoxRatio = ratio;
  11226. },
  11227. enumerable: true,
  11228. configurable: true
  11229. });
  11230. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11231. /**
  11232. * Read-only boolean : is the feature facetData enabled ?
  11233. */
  11234. get: function () {
  11235. return this._facetDataEnabled;
  11236. },
  11237. enumerable: true,
  11238. configurable: true
  11239. });
  11240. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11241. set: function (callback) {
  11242. if (this._onCollideObserver) {
  11243. this.onCollideObservable.remove(this._onCollideObserver);
  11244. }
  11245. this._onCollideObserver = this.onCollideObservable.add(callback);
  11246. },
  11247. enumerable: true,
  11248. configurable: true
  11249. });
  11250. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11251. set: function (callback) {
  11252. if (this._onCollisionPositionChangeObserver) {
  11253. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11254. }
  11255. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11256. },
  11257. enumerable: true,
  11258. configurable: true
  11259. });
  11260. Object.defineProperty(AbstractMesh.prototype, "material", {
  11261. get: function () {
  11262. return this._material;
  11263. },
  11264. set: function (value) {
  11265. if (this._material === value) {
  11266. return;
  11267. }
  11268. this._material = value;
  11269. if (!this.subMeshes) {
  11270. return;
  11271. }
  11272. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11273. var subMesh = _a[_i];
  11274. subMesh.setEffect(null);
  11275. }
  11276. },
  11277. enumerable: true,
  11278. configurable: true
  11279. });
  11280. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11281. get: function () {
  11282. return this._receiveShadows;
  11283. },
  11284. set: function (value) {
  11285. if (this._receiveShadows === value) {
  11286. return;
  11287. }
  11288. this._receiveShadows = value;
  11289. this._markSubMeshesAsLightDirty();
  11290. },
  11291. enumerable: true,
  11292. configurable: true
  11293. });
  11294. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11295. get: function () {
  11296. return this._hasVertexAlpha;
  11297. },
  11298. set: function (value) {
  11299. if (this._hasVertexAlpha === value) {
  11300. return;
  11301. }
  11302. this._hasVertexAlpha = value;
  11303. this._markSubMeshesAsAttributesDirty();
  11304. },
  11305. enumerable: true,
  11306. configurable: true
  11307. });
  11308. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11309. get: function () {
  11310. return this._useVertexColors;
  11311. },
  11312. set: function (value) {
  11313. if (this._useVertexColors === value) {
  11314. return;
  11315. }
  11316. this._useVertexColors = value;
  11317. this._markSubMeshesAsAttributesDirty();
  11318. },
  11319. enumerable: true,
  11320. configurable: true
  11321. });
  11322. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11323. get: function () {
  11324. return this._computeBonesUsingShaders;
  11325. },
  11326. set: function (value) {
  11327. if (this._computeBonesUsingShaders === value) {
  11328. return;
  11329. }
  11330. this._computeBonesUsingShaders = value;
  11331. this._markSubMeshesAsAttributesDirty();
  11332. },
  11333. enumerable: true,
  11334. configurable: true
  11335. });
  11336. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11337. get: function () {
  11338. return this._numBoneInfluencers;
  11339. },
  11340. set: function (value) {
  11341. if (this._numBoneInfluencers === value) {
  11342. return;
  11343. }
  11344. this._numBoneInfluencers = value;
  11345. this._markSubMeshesAsAttributesDirty();
  11346. },
  11347. enumerable: true,
  11348. configurable: true
  11349. });
  11350. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11351. get: function () {
  11352. return this._applyFog;
  11353. },
  11354. set: function (value) {
  11355. if (this._applyFog === value) {
  11356. return;
  11357. }
  11358. this._applyFog = value;
  11359. this._markSubMeshesAsMiscDirty();
  11360. },
  11361. enumerable: true,
  11362. configurable: true
  11363. });
  11364. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11365. get: function () {
  11366. return this._collisionMask;
  11367. },
  11368. set: function (mask) {
  11369. this._collisionMask = !isNaN(mask) ? mask : -1;
  11370. },
  11371. enumerable: true,
  11372. configurable: true
  11373. });
  11374. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11375. get: function () {
  11376. return this._collisionGroup;
  11377. },
  11378. set: function (mask) {
  11379. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11380. },
  11381. enumerable: true,
  11382. configurable: true
  11383. });
  11384. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11385. get: function () {
  11386. return null;
  11387. },
  11388. enumerable: true,
  11389. configurable: true
  11390. });
  11391. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11392. get: function () {
  11393. return this._skeleton;
  11394. },
  11395. set: function (value) {
  11396. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11397. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11398. }
  11399. if (value && value.needInitialSkinMatrix) {
  11400. value._registerMeshWithPoseMatrix(this);
  11401. }
  11402. this._skeleton = value;
  11403. if (!this._skeleton) {
  11404. this._bonesTransformMatrices = null;
  11405. }
  11406. this._markSubMeshesAsAttributesDirty();
  11407. },
  11408. enumerable: true,
  11409. configurable: true
  11410. });
  11411. /**
  11412. * Returns the string "AbstractMesh"
  11413. */
  11414. AbstractMesh.prototype.getClassName = function () {
  11415. return "AbstractMesh";
  11416. };
  11417. /**
  11418. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11419. */
  11420. AbstractMesh.prototype.toString = function (fullDetails) {
  11421. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11422. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11423. if (this._skeleton) {
  11424. ret += ", skeleton: " + this._skeleton.name;
  11425. }
  11426. if (fullDetails) {
  11427. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11428. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11429. }
  11430. return ret;
  11431. };
  11432. AbstractMesh.prototype._resyncLightSources = function () {
  11433. this._lightSources.length = 0;
  11434. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11435. var light = _a[_i];
  11436. if (!light.isEnabled()) {
  11437. continue;
  11438. }
  11439. if (light.canAffectMesh(this)) {
  11440. this._lightSources.push(light);
  11441. }
  11442. }
  11443. this._markSubMeshesAsLightDirty();
  11444. };
  11445. AbstractMesh.prototype._resyncLighSource = function (light) {
  11446. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11447. var index = this._lightSources.indexOf(light);
  11448. if (index === -1) {
  11449. if (!isIn) {
  11450. return;
  11451. }
  11452. this._lightSources.push(light);
  11453. }
  11454. else {
  11455. if (isIn) {
  11456. return;
  11457. }
  11458. this._lightSources.splice(index, 1);
  11459. }
  11460. this._markSubMeshesAsLightDirty();
  11461. };
  11462. AbstractMesh.prototype._removeLightSource = function (light) {
  11463. var index = this._lightSources.indexOf(light);
  11464. if (index === -1) {
  11465. return;
  11466. }
  11467. this._lightSources.splice(index, 1);
  11468. };
  11469. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11470. if (!this.subMeshes) {
  11471. return;
  11472. }
  11473. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11474. var subMesh = _a[_i];
  11475. if (subMesh._materialDefines) {
  11476. func(subMesh._materialDefines);
  11477. }
  11478. }
  11479. };
  11480. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11481. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11482. };
  11483. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11484. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11485. };
  11486. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11487. if (!this.subMeshes) {
  11488. return;
  11489. }
  11490. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11491. var subMesh = _a[_i];
  11492. var material = subMesh.getMaterial();
  11493. if (material) {
  11494. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11495. }
  11496. }
  11497. };
  11498. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11499. /**
  11500. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11501. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11502. * Default : (0.0, 0.0, 0.0)
  11503. */
  11504. get: function () {
  11505. return this._rotation;
  11506. },
  11507. set: function (newRotation) {
  11508. this._rotation = newRotation;
  11509. },
  11510. enumerable: true,
  11511. configurable: true
  11512. });
  11513. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11514. /**
  11515. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11516. * Default : (1.0, 1.0, 1.0)
  11517. */
  11518. get: function () {
  11519. return this._scaling;
  11520. },
  11521. set: function (newScaling) {
  11522. this._scaling = newScaling;
  11523. if (this.physicsImpostor) {
  11524. this.physicsImpostor.forceUpdate();
  11525. }
  11526. },
  11527. enumerable: true,
  11528. configurable: true
  11529. });
  11530. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11531. /**
  11532. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11533. * It's null by default.
  11534. * 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)
  11535. */
  11536. get: function () {
  11537. return this._rotationQuaternion;
  11538. },
  11539. set: function (quaternion) {
  11540. this._rotationQuaternion = quaternion;
  11541. //reset the rotation vector.
  11542. if (quaternion && this.rotation.length()) {
  11543. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11544. }
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. // Methods
  11550. /**
  11551. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11552. * Returns the AbstractMesh.
  11553. */
  11554. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11555. this._poseMatrix.copyFrom(matrix);
  11556. return this;
  11557. };
  11558. /**
  11559. * Returns the mesh Pose matrix.
  11560. * Returned object : Matrix
  11561. */
  11562. AbstractMesh.prototype.getPoseMatrix = function () {
  11563. return this._poseMatrix;
  11564. };
  11565. /**
  11566. * Disables the mesh edger rendering mode.
  11567. * Returns the AbstractMesh.
  11568. */
  11569. AbstractMesh.prototype.disableEdgesRendering = function () {
  11570. if (this._edgesRenderer !== undefined) {
  11571. this._edgesRenderer.dispose();
  11572. this._edgesRenderer = undefined;
  11573. }
  11574. return this;
  11575. };
  11576. /**
  11577. * Enables the edge rendering mode on the mesh.
  11578. * This mode makes the mesh edges visible.
  11579. * Returns the AbstractMesh.
  11580. */
  11581. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11582. if (epsilon === void 0) { epsilon = 0.95; }
  11583. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11584. this.disableEdgesRendering();
  11585. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11586. return this;
  11587. };
  11588. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11589. /**
  11590. * Returns true if the mesh is blocked. Used by the class Mesh.
  11591. * Returns the boolean `false` by default.
  11592. */
  11593. get: function () {
  11594. return false;
  11595. },
  11596. enumerable: true,
  11597. configurable: true
  11598. });
  11599. /**
  11600. * Returns the mesh itself by default, used by the class Mesh.
  11601. * Returned type : AbstractMesh
  11602. */
  11603. AbstractMesh.prototype.getLOD = function (camera) {
  11604. return this;
  11605. };
  11606. /**
  11607. * Returns 0 by default, used by the class Mesh.
  11608. * Returns an integer.
  11609. */
  11610. AbstractMesh.prototype.getTotalVertices = function () {
  11611. return 0;
  11612. };
  11613. /**
  11614. * Returns null by default, used by the class Mesh.
  11615. * Returned type : integer array
  11616. */
  11617. AbstractMesh.prototype.getIndices = function () {
  11618. return null;
  11619. };
  11620. /**
  11621. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11622. * Returned type : float array or Float32Array
  11623. */
  11624. AbstractMesh.prototype.getVerticesData = function (kind) {
  11625. return null;
  11626. };
  11627. /**
  11628. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11629. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11630. * The `data` are either a numeric array either a Float32Array.
  11631. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11632. * 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).
  11633. * Note that a new underlying VertexBuffer object is created each call.
  11634. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11635. *
  11636. * Possible `kind` values :
  11637. * - BABYLON.VertexBuffer.PositionKind
  11638. * - BABYLON.VertexBuffer.UVKind
  11639. * - BABYLON.VertexBuffer.UV2Kind
  11640. * - BABYLON.VertexBuffer.UV3Kind
  11641. * - BABYLON.VertexBuffer.UV4Kind
  11642. * - BABYLON.VertexBuffer.UV5Kind
  11643. * - BABYLON.VertexBuffer.UV6Kind
  11644. * - BABYLON.VertexBuffer.ColorKind
  11645. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11646. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11647. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11648. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11649. *
  11650. * Returns the Mesh.
  11651. */
  11652. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11653. return null;
  11654. };
  11655. /**
  11656. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11657. * If the mesh has no geometry, it is simply returned as it is.
  11658. * The `data` are either a numeric array either a Float32Array.
  11659. * No new underlying VertexBuffer object is created.
  11660. * 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.
  11661. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11662. *
  11663. * Possible `kind` values :
  11664. * - BABYLON.VertexBuffer.PositionKind
  11665. * - BABYLON.VertexBuffer.UVKind
  11666. * - BABYLON.VertexBuffer.UV2Kind
  11667. * - BABYLON.VertexBuffer.UV3Kind
  11668. * - BABYLON.VertexBuffer.UV4Kind
  11669. * - BABYLON.VertexBuffer.UV5Kind
  11670. * - BABYLON.VertexBuffer.UV6Kind
  11671. * - BABYLON.VertexBuffer.ColorKind
  11672. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11673. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11674. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11675. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11676. *
  11677. * Returns the Mesh.
  11678. */
  11679. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11680. return null;
  11681. };
  11682. /**
  11683. * Sets the mesh indices.
  11684. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11685. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11686. * This method creates a new index buffer each call.
  11687. * Returns the Mesh.
  11688. */
  11689. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11690. return null;
  11691. };
  11692. /** Returns false by default, used by the class Mesh.
  11693. * Returns a boolean
  11694. */
  11695. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11696. return false;
  11697. };
  11698. /**
  11699. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11700. * Returns a BoundingInfo
  11701. */
  11702. AbstractMesh.prototype.getBoundingInfo = function () {
  11703. if (this._masterMesh) {
  11704. return this._masterMesh.getBoundingInfo();
  11705. }
  11706. if (!this._boundingInfo) {
  11707. this._updateBoundingInfo();
  11708. }
  11709. return this._boundingInfo;
  11710. };
  11711. /**
  11712. * Sets a mesh new object BoundingInfo.
  11713. * Returns the AbstractMesh.
  11714. */
  11715. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11716. this._boundingInfo = boundingInfo;
  11717. return this;
  11718. };
  11719. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11720. get: function () {
  11721. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. AbstractMesh.prototype._preActivate = function () {
  11727. };
  11728. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11729. };
  11730. AbstractMesh.prototype._activate = function (renderId) {
  11731. this._renderId = renderId;
  11732. };
  11733. /**
  11734. * Returns the last update of the World matrix
  11735. * Returns a Matrix.
  11736. */
  11737. AbstractMesh.prototype.getWorldMatrix = function () {
  11738. if (this._masterMesh) {
  11739. return this._masterMesh.getWorldMatrix();
  11740. }
  11741. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11742. this.computeWorldMatrix();
  11743. }
  11744. return this._worldMatrix;
  11745. };
  11746. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11747. /**
  11748. * Returns directly the last state of the mesh World matrix.
  11749. * A Matrix is returned.
  11750. */
  11751. get: function () {
  11752. return this._worldMatrix;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11758. /**
  11759. * Returns the current mesh absolute position.
  11760. * Retuns a Vector3.
  11761. */
  11762. get: function () {
  11763. return this._absolutePosition;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. /**
  11769. * Prevents the World matrix to be computed any longer.
  11770. * Returns the AbstractMesh.
  11771. */
  11772. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11773. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11774. this.computeWorldMatrix(true);
  11775. this._isWorldMatrixFrozen = true;
  11776. return this;
  11777. };
  11778. /**
  11779. * Allows back the World matrix computation.
  11780. * Returns the AbstractMesh.
  11781. */
  11782. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11783. this._isWorldMatrixFrozen = false;
  11784. this.computeWorldMatrix(true);
  11785. return this;
  11786. };
  11787. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11788. /**
  11789. * True if the World matrix has been frozen.
  11790. * Returns a boolean.
  11791. */
  11792. get: function () {
  11793. return this._isWorldMatrixFrozen;
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. /**
  11799. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11800. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11801. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11802. * The passed axis is also normalized.
  11803. * Returns the AbstractMesh.
  11804. */
  11805. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11806. axis.normalize();
  11807. if (!this.rotationQuaternion) {
  11808. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11809. this.rotation = BABYLON.Vector3.Zero();
  11810. }
  11811. var rotationQuaternion;
  11812. if (!space || space === BABYLON.Space.LOCAL) {
  11813. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11814. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11815. }
  11816. else {
  11817. if (this.parent) {
  11818. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11819. invertParentWorldMatrix.invert();
  11820. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11821. }
  11822. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11823. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11824. }
  11825. return this;
  11826. };
  11827. /**
  11828. * Translates the mesh along the axis vector for the passed distance in the given space.
  11829. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11830. * Returns the AbstractMesh.
  11831. */
  11832. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11833. var displacementVector = axis.scale(distance);
  11834. if (!space || space === BABYLON.Space.LOCAL) {
  11835. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11836. this.setPositionWithLocalVector(tempV3);
  11837. }
  11838. else {
  11839. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11840. }
  11841. return this;
  11842. };
  11843. /**
  11844. * Adds a rotation step to the mesh current rotation.
  11845. * x, y, z are Euler angles expressed in radians.
  11846. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11847. * This means this rotation is made in the mesh local space only.
  11848. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11849. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11850. * ```javascript
  11851. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11852. * ```
  11853. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11854. * 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.
  11855. * Returns the AbstractMesh.
  11856. */
  11857. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11858. var rotationQuaternion;
  11859. if (this.rotationQuaternion) {
  11860. rotationQuaternion = this.rotationQuaternion;
  11861. }
  11862. else {
  11863. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11864. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11865. }
  11866. var accumulation = BABYLON.Tmp.Quaternion[0];
  11867. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11868. rotationQuaternion.multiplyInPlace(accumulation);
  11869. if (!this.rotationQuaternion) {
  11870. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11871. }
  11872. return this;
  11873. };
  11874. /**
  11875. * Retuns the mesh absolute position in the World.
  11876. * Returns a Vector3.
  11877. */
  11878. AbstractMesh.prototype.getAbsolutePosition = function () {
  11879. this.computeWorldMatrix();
  11880. return this._absolutePosition;
  11881. };
  11882. /**
  11883. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11884. * Returns the AbstractMesh.
  11885. */
  11886. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11887. if (!absolutePosition) {
  11888. return;
  11889. }
  11890. var absolutePositionX;
  11891. var absolutePositionY;
  11892. var absolutePositionZ;
  11893. if (absolutePosition.x === undefined) {
  11894. if (arguments.length < 3) {
  11895. return;
  11896. }
  11897. absolutePositionX = arguments[0];
  11898. absolutePositionY = arguments[1];
  11899. absolutePositionZ = arguments[2];
  11900. }
  11901. else {
  11902. absolutePositionX = absolutePosition.x;
  11903. absolutePositionY = absolutePosition.y;
  11904. absolutePositionZ = absolutePosition.z;
  11905. }
  11906. if (this.parent) {
  11907. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11908. invertParentWorldMatrix.invert();
  11909. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11910. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11911. }
  11912. else {
  11913. this.position.x = absolutePositionX;
  11914. this.position.y = absolutePositionY;
  11915. this.position.z = absolutePositionZ;
  11916. }
  11917. return this;
  11918. };
  11919. // ================================== Point of View Movement =================================
  11920. /**
  11921. * Perform relative position change from the point of view of behind the front of the mesh.
  11922. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11923. * Supports definition of mesh facing forward or backward.
  11924. * @param {number} amountRight
  11925. * @param {number} amountUp
  11926. * @param {number} amountForward
  11927. *
  11928. * Returns the AbstractMesh.
  11929. */
  11930. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11931. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11932. return this;
  11933. };
  11934. /**
  11935. * Calculate relative position change from the point of view of behind the front of the mesh.
  11936. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11937. * Supports definition of mesh facing forward or backward.
  11938. * @param {number} amountRight
  11939. * @param {number} amountUp
  11940. * @param {number} amountForward
  11941. *
  11942. * Returns a new Vector3.
  11943. */
  11944. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11945. var rotMatrix = new BABYLON.Matrix();
  11946. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11947. rotQuaternion.toRotationMatrix(rotMatrix);
  11948. var translationDelta = BABYLON.Vector3.Zero();
  11949. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11950. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11951. return translationDelta;
  11952. };
  11953. // ================================== Point of View Rotation =================================
  11954. /**
  11955. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11956. * Supports definition of mesh facing forward or backward.
  11957. * @param {number} flipBack
  11958. * @param {number} twirlClockwise
  11959. * @param {number} tiltRight
  11960. *
  11961. * Returns the AbstractMesh.
  11962. */
  11963. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11964. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11965. return this;
  11966. };
  11967. /**
  11968. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11969. * Supports definition of mesh facing forward or backward.
  11970. * @param {number} flipBack
  11971. * @param {number} twirlClockwise
  11972. * @param {number} tiltRight
  11973. *
  11974. * Returns a new Vector3.
  11975. */
  11976. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11977. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11978. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11979. };
  11980. /**
  11981. * Sets a new pivot matrix to the mesh.
  11982. * Returns the AbstractMesh.
  11983. */
  11984. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11985. this._pivotMatrix = matrix;
  11986. this._cache.pivotMatrixUpdated = true;
  11987. return this;
  11988. };
  11989. /**
  11990. * Returns the mesh pivot matrix.
  11991. * Default : Identity.
  11992. * A Matrix is returned.
  11993. */
  11994. AbstractMesh.prototype.getPivotMatrix = function () {
  11995. return this._pivotMatrix;
  11996. };
  11997. AbstractMesh.prototype._isSynchronized = function () {
  11998. if (this._isDirty) {
  11999. return false;
  12000. }
  12001. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12002. return false;
  12003. if (this._cache.pivotMatrixUpdated) {
  12004. return false;
  12005. }
  12006. if (this.infiniteDistance) {
  12007. return false;
  12008. }
  12009. if (!this._cache.position.equals(this.position))
  12010. return false;
  12011. if (this.rotationQuaternion) {
  12012. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12013. return false;
  12014. }
  12015. if (!this._cache.rotation.equals(this.rotation))
  12016. return false;
  12017. if (!this._cache.scaling.equals(this.scaling))
  12018. return false;
  12019. return true;
  12020. };
  12021. AbstractMesh.prototype._initCache = function () {
  12022. _super.prototype._initCache.call(this);
  12023. this._cache.localMatrixUpdated = false;
  12024. this._cache.position = BABYLON.Vector3.Zero();
  12025. this._cache.scaling = BABYLON.Vector3.Zero();
  12026. this._cache.rotation = BABYLON.Vector3.Zero();
  12027. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12028. this._cache.billboardMode = -1;
  12029. };
  12030. AbstractMesh.prototype.markAsDirty = function (property) {
  12031. if (property === "rotation") {
  12032. this.rotationQuaternion = null;
  12033. }
  12034. this._currentRenderId = Number.MAX_VALUE;
  12035. this._isDirty = true;
  12036. return this;
  12037. };
  12038. /**
  12039. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12040. * Returns the AbstractMesh.
  12041. */
  12042. AbstractMesh.prototype._updateBoundingInfo = function () {
  12043. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12044. this._boundingInfo.update(this.worldMatrixFromCache);
  12045. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12046. return this;
  12047. };
  12048. /**
  12049. * Update a mesh's children BoundingInfo objects only.
  12050. * Returns the AbstractMesh.
  12051. */
  12052. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12053. if (!this.subMeshes) {
  12054. return;
  12055. }
  12056. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12057. var subMesh = this.subMeshes[subIndex];
  12058. if (!subMesh.IsGlobal) {
  12059. subMesh.updateBoundingInfo(matrix);
  12060. }
  12061. }
  12062. return this;
  12063. };
  12064. /**
  12065. * Computes the mesh World matrix and returns it.
  12066. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12067. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12068. * If the parameter `force`is set to `true`, the actual computation is done.
  12069. * Returns the mesh World Matrix.
  12070. */
  12071. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12072. if (this._isWorldMatrixFrozen) {
  12073. return this._worldMatrix;
  12074. }
  12075. if (!force && this.isSynchronized(true)) {
  12076. this._currentRenderId = this.getScene().getRenderId();
  12077. return this._worldMatrix;
  12078. }
  12079. this._cache.position.copyFrom(this.position);
  12080. this._cache.scaling.copyFrom(this.scaling);
  12081. this._cache.pivotMatrixUpdated = false;
  12082. this._cache.billboardMode = this.billboardMode;
  12083. this._currentRenderId = this.getScene().getRenderId();
  12084. this._isDirty = false;
  12085. // Scaling
  12086. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12087. // Rotation
  12088. //rotate, if quaternion is set and rotation was used
  12089. if (this.rotationQuaternion) {
  12090. var len = this.rotation.length();
  12091. if (len) {
  12092. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12093. this.rotation.copyFromFloats(0, 0, 0);
  12094. }
  12095. }
  12096. if (this.rotationQuaternion) {
  12097. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12098. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12099. }
  12100. else {
  12101. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12102. this._cache.rotation.copyFrom(this.rotation);
  12103. }
  12104. // Translation
  12105. if (this.infiniteDistance && !this.parent) {
  12106. var camera = this.getScene().activeCamera;
  12107. if (camera) {
  12108. var cameraWorldMatrix = camera.getWorldMatrix();
  12109. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12110. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12111. }
  12112. }
  12113. else {
  12114. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12115. }
  12116. // Composing transformations
  12117. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12118. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12119. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12120. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12121. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12122. // Need to decompose each rotation here
  12123. var currentPosition = BABYLON.Tmp.Vector3[3];
  12124. if (this.parent && this.parent.getWorldMatrix) {
  12125. if (this._meshToBoneReferal) {
  12126. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12127. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12128. }
  12129. else {
  12130. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12131. }
  12132. }
  12133. else {
  12134. currentPosition.copyFrom(this.position);
  12135. }
  12136. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12137. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12138. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12139. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12140. }
  12141. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12142. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12143. }
  12144. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12145. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12146. }
  12147. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12148. }
  12149. else {
  12150. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12151. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12152. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12153. }
  12154. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12155. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12156. }
  12157. // Local world
  12158. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12159. // Parent
  12160. if (this.parent && this.parent.getWorldMatrix) {
  12161. this._markSyncedWithParent();
  12162. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12163. if (this._meshToBoneReferal) {
  12164. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12165. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12166. }
  12167. else {
  12168. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12169. }
  12170. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12171. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12172. this._worldMatrix.copyFrom(this._localWorld);
  12173. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12174. }
  12175. else {
  12176. if (this._meshToBoneReferal) {
  12177. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12178. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12179. }
  12180. else {
  12181. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12182. }
  12183. }
  12184. }
  12185. else {
  12186. this._worldMatrix.copyFrom(this._localWorld);
  12187. }
  12188. // Bounding info
  12189. this._updateBoundingInfo();
  12190. // Absolute position
  12191. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12192. // Callbacks
  12193. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12194. if (!this._poseMatrix) {
  12195. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12196. }
  12197. return this._worldMatrix;
  12198. };
  12199. /**
  12200. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12201. * @param func: callback function to add
  12202. *
  12203. * Returns the AbstractMesh.
  12204. */
  12205. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12206. this.onAfterWorldMatrixUpdateObservable.add(func);
  12207. return this;
  12208. };
  12209. /**
  12210. * Removes a registered callback function.
  12211. * Returns the AbstractMesh.
  12212. */
  12213. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12214. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12215. return this;
  12216. };
  12217. /**
  12218. * Sets the mesh position in its local space.
  12219. * Returns the AbstractMesh.
  12220. */
  12221. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12222. this.computeWorldMatrix();
  12223. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12224. return this;
  12225. };
  12226. /**
  12227. * Returns the mesh position in the local space from the current World matrix values.
  12228. * Returns a new Vector3.
  12229. */
  12230. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12231. this.computeWorldMatrix();
  12232. var invLocalWorldMatrix = this._localWorld.clone();
  12233. invLocalWorldMatrix.invert();
  12234. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12235. };
  12236. /**
  12237. * Translates the mesh along the passed Vector3 in its local space.
  12238. * Returns the AbstractMesh.
  12239. */
  12240. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12241. this.computeWorldMatrix(true);
  12242. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12243. return this;
  12244. };
  12245. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12246. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12247. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12248. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12249. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12250. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12251. /// <returns>Mesh oriented towards targetMesh</returns>
  12252. if (yawCor === void 0) { yawCor = 0; }
  12253. if (pitchCor === void 0) { pitchCor = 0; }
  12254. if (rollCor === void 0) { rollCor = 0; }
  12255. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12256. var dv = AbstractMesh._lookAtVectorCache;
  12257. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12258. targetPoint.subtractToRef(pos, dv);
  12259. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12260. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12261. var pitch = Math.atan2(dv.y, len);
  12262. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12263. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12264. return this;
  12265. };
  12266. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12267. this._meshToBoneReferal = affectedMesh;
  12268. this.parent = bone;
  12269. if (bone.getWorldMatrix().determinant() < 0) {
  12270. this.scalingDeterminant *= -1;
  12271. }
  12272. return this;
  12273. };
  12274. AbstractMesh.prototype.detachFromBone = function () {
  12275. if (this.parent.getWorldMatrix().determinant() < 0) {
  12276. this.scalingDeterminant *= -1;
  12277. }
  12278. this._meshToBoneReferal = null;
  12279. this.parent = null;
  12280. return this;
  12281. };
  12282. /**
  12283. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12284. * A mesh is in the frustum if its bounding box intersects the frustum.
  12285. * Boolean returned.
  12286. */
  12287. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12288. return this._boundingInfo.isInFrustum(frustumPlanes);
  12289. };
  12290. /**
  12291. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12292. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12293. * Boolean returned.
  12294. */
  12295. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12296. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12297. ;
  12298. };
  12299. /**
  12300. * True if the mesh intersects another mesh or a SolidParticle object.
  12301. * 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)
  12302. * Returns a boolean.
  12303. */
  12304. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12305. if (!this._boundingInfo || !mesh._boundingInfo) {
  12306. return false;
  12307. }
  12308. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12309. };
  12310. /**
  12311. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12312. * Returns a boolean.
  12313. */
  12314. AbstractMesh.prototype.intersectsPoint = function (point) {
  12315. if (!this._boundingInfo) {
  12316. return false;
  12317. }
  12318. return this._boundingInfo.intersectsPoint(point);
  12319. };
  12320. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12321. return this.physicsImpostor;
  12322. };
  12323. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12324. if (!camera) {
  12325. camera = this.getScene().activeCamera;
  12326. }
  12327. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12328. };
  12329. /**
  12330. * Returns the distance from the mesh to the active camera.
  12331. * Returns a float.
  12332. */
  12333. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12334. if (!camera) {
  12335. camera = this.getScene().activeCamera;
  12336. }
  12337. return this.absolutePosition.subtract(camera.position).length();
  12338. };
  12339. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12340. if (!this.physicsImpostor) {
  12341. return;
  12342. }
  12343. this.physicsImpostor.applyImpulse(force, contactPoint);
  12344. return this;
  12345. };
  12346. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12347. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12348. return;
  12349. }
  12350. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12351. mainPivot: pivot1,
  12352. connectedPivot: pivot2,
  12353. nativeParams: options
  12354. });
  12355. return this;
  12356. };
  12357. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12358. // Collisions
  12359. /**
  12360. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12361. * Default `false`.
  12362. */
  12363. get: function () {
  12364. return this._checkCollisions;
  12365. },
  12366. set: function (collisionEnabled) {
  12367. this._checkCollisions = collisionEnabled;
  12368. if (this.getScene().workerCollisions) {
  12369. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12370. }
  12371. },
  12372. enumerable: true,
  12373. configurable: true
  12374. });
  12375. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12376. var globalPosition = this.getAbsolutePosition();
  12377. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12378. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12379. if (!this._collider) {
  12380. this._collider = new BABYLON.Collider();
  12381. }
  12382. this._collider.radius = this.ellipsoid;
  12383. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12384. return this;
  12385. };
  12386. // Submeshes octree
  12387. /**
  12388. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12389. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12390. * Returns an Octree of submeshes.
  12391. */
  12392. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12393. if (maxCapacity === void 0) { maxCapacity = 64; }
  12394. if (maxDepth === void 0) { maxDepth = 2; }
  12395. if (!this._submeshesOctree) {
  12396. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12397. }
  12398. this.computeWorldMatrix(true);
  12399. // Update octree
  12400. var bbox = this.getBoundingInfo().boundingBox;
  12401. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12402. return this._submeshesOctree;
  12403. };
  12404. // Collisions
  12405. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12406. this._generatePointsArray();
  12407. // Transformation
  12408. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12409. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12410. subMesh._lastColliderWorldVertices = [];
  12411. subMesh._trianglePlanes = [];
  12412. var start = subMesh.verticesStart;
  12413. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12414. for (var i = start; i < end; i++) {
  12415. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12416. }
  12417. }
  12418. // Collide
  12419. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12420. if (collider.collisionFound) {
  12421. collider.collidedMesh = this;
  12422. }
  12423. return this;
  12424. };
  12425. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12426. var subMeshes;
  12427. var len;
  12428. // Octrees
  12429. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12430. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12431. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12432. len = intersections.length;
  12433. subMeshes = intersections.data;
  12434. }
  12435. else {
  12436. subMeshes = this.subMeshes;
  12437. len = subMeshes.length;
  12438. }
  12439. for (var index = 0; index < len; index++) {
  12440. var subMesh = subMeshes[index];
  12441. // Bounding test
  12442. if (len > 1 && !subMesh._checkCollision(collider))
  12443. continue;
  12444. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12445. }
  12446. return this;
  12447. };
  12448. AbstractMesh.prototype._checkCollision = function (collider) {
  12449. // Bounding box test
  12450. if (!this._boundingInfo._checkCollision(collider))
  12451. return this;
  12452. // Transformation matrix
  12453. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12454. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12455. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12456. return this;
  12457. };
  12458. // Picking
  12459. AbstractMesh.prototype._generatePointsArray = function () {
  12460. return false;
  12461. };
  12462. /**
  12463. * Checks if the passed Ray intersects with the mesh.
  12464. * Returns an object PickingInfo.
  12465. */
  12466. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12467. var pickingInfo = new BABYLON.PickingInfo();
  12468. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12469. return pickingInfo;
  12470. }
  12471. if (!this._generatePointsArray()) {
  12472. return pickingInfo;
  12473. }
  12474. var intersectInfo = null;
  12475. // Octrees
  12476. var subMeshes;
  12477. var len;
  12478. if (this._submeshesOctree && this.useOctreeForPicking) {
  12479. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12480. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12481. len = intersections.length;
  12482. subMeshes = intersections.data;
  12483. }
  12484. else {
  12485. subMeshes = this.subMeshes;
  12486. len = subMeshes.length;
  12487. }
  12488. for (var index = 0; index < len; index++) {
  12489. var subMesh = subMeshes[index];
  12490. // Bounding test
  12491. if (len > 1 && !subMesh.canIntersects(ray))
  12492. continue;
  12493. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12494. if (currentIntersectInfo) {
  12495. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12496. intersectInfo = currentIntersectInfo;
  12497. intersectInfo.subMeshId = index;
  12498. if (fastCheck) {
  12499. break;
  12500. }
  12501. }
  12502. }
  12503. }
  12504. if (intersectInfo) {
  12505. // Get picked point
  12506. var world = this.getWorldMatrix();
  12507. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12508. var direction = ray.direction.clone();
  12509. direction = direction.scale(intersectInfo.distance);
  12510. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12511. var pickedPoint = worldOrigin.add(worldDirection);
  12512. // Return result
  12513. pickingInfo.hit = true;
  12514. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12515. pickingInfo.pickedPoint = pickedPoint;
  12516. pickingInfo.pickedMesh = this;
  12517. pickingInfo.bu = intersectInfo.bu;
  12518. pickingInfo.bv = intersectInfo.bv;
  12519. pickingInfo.faceId = intersectInfo.faceId;
  12520. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12521. return pickingInfo;
  12522. }
  12523. return pickingInfo;
  12524. };
  12525. /**
  12526. * Clones the mesh, used by the class Mesh.
  12527. * Just returns `null` for an AbstractMesh.
  12528. */
  12529. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12530. return null;
  12531. };
  12532. /**
  12533. * Disposes all the mesh submeshes.
  12534. * Returns the AbstractMesh.
  12535. */
  12536. AbstractMesh.prototype.releaseSubMeshes = function () {
  12537. if (this.subMeshes) {
  12538. while (this.subMeshes.length) {
  12539. this.subMeshes[0].dispose();
  12540. }
  12541. }
  12542. else {
  12543. this.subMeshes = new Array();
  12544. }
  12545. return this;
  12546. };
  12547. /**
  12548. * Disposes the AbstractMesh.
  12549. * Some internal references are kept for further use.
  12550. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12551. * Returns nothing.
  12552. */
  12553. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12554. var _this = this;
  12555. var index;
  12556. // Action manager
  12557. if (this.actionManager) {
  12558. this.actionManager.dispose();
  12559. this.actionManager = null;
  12560. }
  12561. // Skeleton
  12562. this.skeleton = null;
  12563. // Animations
  12564. this.getScene().stopAnimation(this);
  12565. // Physics
  12566. if (this.physicsImpostor) {
  12567. this.physicsImpostor.dispose();
  12568. }
  12569. // Intersections in progress
  12570. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12571. var other = this._intersectionsInProgress[index];
  12572. var pos = other._intersectionsInProgress.indexOf(this);
  12573. other._intersectionsInProgress.splice(pos, 1);
  12574. }
  12575. this._intersectionsInProgress = [];
  12576. // Lights
  12577. var lights = this.getScene().lights;
  12578. lights.forEach(function (light) {
  12579. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12580. if (meshIndex !== -1) {
  12581. light.includedOnlyMeshes.splice(meshIndex, 1);
  12582. }
  12583. meshIndex = light.excludedMeshes.indexOf(_this);
  12584. if (meshIndex !== -1) {
  12585. light.excludedMeshes.splice(meshIndex, 1);
  12586. }
  12587. // Shadow generators
  12588. var generator = light.getShadowGenerator();
  12589. if (generator) {
  12590. var shadowMap = generator.getShadowMap();
  12591. meshIndex = shadowMap.renderList.indexOf(_this);
  12592. if (meshIndex !== -1) {
  12593. shadowMap.renderList.splice(meshIndex, 1);
  12594. }
  12595. }
  12596. });
  12597. // Edges
  12598. if (this._edgesRenderer) {
  12599. this._edgesRenderer.dispose();
  12600. this._edgesRenderer = null;
  12601. }
  12602. // SubMeshes
  12603. if (this.getClassName() !== "InstancedMesh") {
  12604. this.releaseSubMeshes();
  12605. }
  12606. // Octree
  12607. var sceneOctree = this.getScene().selectionOctree;
  12608. if (sceneOctree) {
  12609. var index = sceneOctree.dynamicContent.indexOf(this);
  12610. if (index !== -1) {
  12611. sceneOctree.dynamicContent.splice(index, 1);
  12612. }
  12613. }
  12614. // Engine
  12615. this.getScene().getEngine().wipeCaches();
  12616. // Remove from scene
  12617. this.getScene().removeMesh(this);
  12618. if (!doNotRecurse) {
  12619. // Particles
  12620. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12621. if (this.getScene().particleSystems[index].emitter === this) {
  12622. this.getScene().particleSystems[index].dispose();
  12623. index--;
  12624. }
  12625. }
  12626. // Children
  12627. var objects = this.getDescendants(true);
  12628. for (index = 0; index < objects.length; index++) {
  12629. objects[index].dispose();
  12630. }
  12631. }
  12632. else {
  12633. var childMeshes = this.getChildMeshes(true);
  12634. for (index = 0; index < childMeshes.length; index++) {
  12635. var child = childMeshes[index];
  12636. child.parent = null;
  12637. child.computeWorldMatrix(true);
  12638. }
  12639. }
  12640. // facet data
  12641. if (this._facetDataEnabled) {
  12642. this.disableFacetData();
  12643. }
  12644. this.onAfterWorldMatrixUpdateObservable.clear();
  12645. this.onCollideObservable.clear();
  12646. this.onCollisionPositionChangeObservable.clear();
  12647. this._isDisposed = true;
  12648. _super.prototype.dispose.call(this);
  12649. };
  12650. /**
  12651. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12652. * This Vector3 is expressed in the World space.
  12653. */
  12654. AbstractMesh.prototype.getDirection = function (localAxis) {
  12655. var result = BABYLON.Vector3.Zero();
  12656. this.getDirectionToRef(localAxis, result);
  12657. return result;
  12658. };
  12659. /**
  12660. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12661. * localAxis is expressed in the mesh local space.
  12662. * result is computed in the Wordl space from the mesh World matrix.
  12663. * Returns the AbstractMesh.
  12664. */
  12665. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12666. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12667. return this;
  12668. };
  12669. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12670. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12671. if (this.getScene().getRenderId() == 0) {
  12672. this.computeWorldMatrix(true);
  12673. }
  12674. var wm = this.getWorldMatrix();
  12675. if (space == BABYLON.Space.WORLD) {
  12676. var tmat = BABYLON.Tmp.Matrix[0];
  12677. wm.invertToRef(tmat);
  12678. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12679. }
  12680. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12681. this._pivotMatrix.m[12] = -point.x;
  12682. this._pivotMatrix.m[13] = -point.y;
  12683. this._pivotMatrix.m[14] = -point.z;
  12684. this._cache.pivotMatrixUpdated = true;
  12685. return this;
  12686. };
  12687. /**
  12688. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12689. */
  12690. AbstractMesh.prototype.getPivotPoint = function () {
  12691. var point = BABYLON.Vector3.Zero();
  12692. this.getPivotPointToRef(point);
  12693. return point;
  12694. };
  12695. /**
  12696. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12697. * Returns the AbstractMesh.
  12698. */
  12699. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12700. result.x = -this._pivotMatrix.m[12];
  12701. result.y = -this._pivotMatrix.m[13];
  12702. result.z = -this._pivotMatrix.m[14];
  12703. return this;
  12704. };
  12705. /**
  12706. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12707. */
  12708. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12709. var point = BABYLON.Vector3.Zero();
  12710. this.getAbsolutePivotPointToRef(point);
  12711. return point;
  12712. };
  12713. /**
  12714. * Defines the passed mesh as the parent of the current mesh.
  12715. * Returns the AbstractMesh.
  12716. */
  12717. AbstractMesh.prototype.setParent = function (mesh) {
  12718. var child = this;
  12719. var parent = mesh;
  12720. if (mesh == null) {
  12721. var rotation = BABYLON.Tmp.Quaternion[0];
  12722. var position = BABYLON.Tmp.Vector3[0];
  12723. var scale = BABYLON.Tmp.Vector3[1];
  12724. child.getWorldMatrix().decompose(scale, rotation, position);
  12725. if (child.rotationQuaternion) {
  12726. child.rotationQuaternion.copyFrom(rotation);
  12727. }
  12728. else {
  12729. rotation.toEulerAnglesToRef(child.rotation);
  12730. }
  12731. child.position.x = position.x;
  12732. child.position.y = position.y;
  12733. child.position.z = position.z;
  12734. }
  12735. else {
  12736. var rotation = BABYLON.Tmp.Quaternion[0];
  12737. var position = BABYLON.Tmp.Vector3[0];
  12738. var scale = BABYLON.Tmp.Vector3[1];
  12739. var m1 = BABYLON.Tmp.Matrix[0];
  12740. var m2 = BABYLON.Tmp.Matrix[1];
  12741. parent.getWorldMatrix().decompose(scale, rotation, position);
  12742. rotation.toRotationMatrix(m1);
  12743. m2.setTranslation(position);
  12744. m2.multiplyToRef(m1, m1);
  12745. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12746. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12747. m.decompose(scale, rotation, position);
  12748. if (child.rotationQuaternion) {
  12749. child.rotationQuaternion.copyFrom(rotation);
  12750. }
  12751. else {
  12752. rotation.toEulerAnglesToRef(child.rotation);
  12753. }
  12754. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12755. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12756. m.decompose(scale, rotation, position);
  12757. child.position.x = position.x;
  12758. child.position.y = position.y;
  12759. child.position.z = position.z;
  12760. }
  12761. child.parent = parent;
  12762. return this;
  12763. };
  12764. /**
  12765. * Adds the passed mesh as a child to the current mesh.
  12766. * Returns the AbstractMesh.
  12767. */
  12768. AbstractMesh.prototype.addChild = function (mesh) {
  12769. mesh.setParent(this);
  12770. return this;
  12771. };
  12772. /**
  12773. * Removes the passed mesh from the current mesh children list.
  12774. * Returns the AbstractMesh.
  12775. */
  12776. AbstractMesh.prototype.removeChild = function (mesh) {
  12777. mesh.setParent(null);
  12778. return this;
  12779. };
  12780. /**
  12781. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12782. * Returns the AbstractMesh.
  12783. */
  12784. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12785. result.x = this._pivotMatrix.m[12];
  12786. result.y = this._pivotMatrix.m[13];
  12787. result.z = this._pivotMatrix.m[14];
  12788. this.getPivotPointToRef(result);
  12789. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12790. return this;
  12791. };
  12792. // Facet data
  12793. /**
  12794. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12795. * Returns the AbstractMesh.
  12796. */
  12797. AbstractMesh.prototype._initFacetData = function () {
  12798. if (!this._facetNormals) {
  12799. this._facetNormals = new Array();
  12800. }
  12801. if (!this._facetPositions) {
  12802. this._facetPositions = new Array();
  12803. }
  12804. if (!this._facetPartitioning) {
  12805. this._facetPartitioning = new Array();
  12806. }
  12807. this._facetNb = this.getIndices().length / 3;
  12808. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12809. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12810. for (var f = 0; f < this._facetNb; f++) {
  12811. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12812. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12813. }
  12814. this._facetDataEnabled = true;
  12815. return this;
  12816. };
  12817. /**
  12818. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12819. * This method can be called within the render loop.
  12820. * 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.
  12821. * Returns the AbstractMesh.
  12822. */
  12823. AbstractMesh.prototype.updateFacetData = function () {
  12824. if (!this._facetDataEnabled) {
  12825. this._initFacetData();
  12826. }
  12827. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12828. var indices = this.getIndices();
  12829. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12830. var bInfo = this.getBoundingInfo();
  12831. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12832. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12833. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12834. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12835. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12836. this._subDiv.max = this._partitioningSubdivisions;
  12837. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12838. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12839. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12840. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12841. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12842. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12843. // set the parameters for ComputeNormals()
  12844. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12845. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12846. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12847. this._facetParameters.bInfo = bInfo;
  12848. this._facetParameters.bbSize = this._bbSize;
  12849. this._facetParameters.subDiv = this._subDiv;
  12850. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12851. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12852. return this;
  12853. };
  12854. /**
  12855. * Returns the facetLocalNormals array.
  12856. * The normals are expressed in the mesh local space.
  12857. */
  12858. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12859. if (!this._facetNormals) {
  12860. this.updateFacetData();
  12861. }
  12862. return this._facetNormals;
  12863. };
  12864. /**
  12865. * Returns the facetLocalPositions array.
  12866. * The facet positions are expressed in the mesh local space.
  12867. */
  12868. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12869. if (!this._facetPositions) {
  12870. this.updateFacetData();
  12871. }
  12872. return this._facetPositions;
  12873. };
  12874. /**
  12875. * Returns the facetLocalPartioning array.
  12876. */
  12877. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12878. if (!this._facetPartitioning) {
  12879. this.updateFacetData();
  12880. }
  12881. return this._facetPartitioning;
  12882. };
  12883. /**
  12884. * Returns the i-th facet position in the world system.
  12885. * This method allocates a new Vector3 per call.
  12886. */
  12887. AbstractMesh.prototype.getFacetPosition = function (i) {
  12888. var pos = BABYLON.Vector3.Zero();
  12889. this.getFacetPositionToRef(i, pos);
  12890. return pos;
  12891. };
  12892. /**
  12893. * Sets the reference Vector3 with the i-th facet position in the world system.
  12894. * Returns the AbstractMesh.
  12895. */
  12896. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12897. var localPos = (this.getFacetLocalPositions())[i];
  12898. var world = this.getWorldMatrix();
  12899. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12900. return this;
  12901. };
  12902. /**
  12903. * Returns the i-th facet normal in the world system.
  12904. * This method allocates a new Vector3 per call.
  12905. */
  12906. AbstractMesh.prototype.getFacetNormal = function (i) {
  12907. var norm = BABYLON.Vector3.Zero();
  12908. this.getFacetNormalToRef(i, norm);
  12909. return norm;
  12910. };
  12911. /**
  12912. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12913. * Returns the AbstractMesh.
  12914. */
  12915. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12916. var localNorm = (this.getFacetLocalNormals())[i];
  12917. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12918. return this;
  12919. };
  12920. /**
  12921. * 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).
  12922. */
  12923. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12924. var bInfo = this.getBoundingInfo();
  12925. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12926. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12927. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12928. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12929. return null;
  12930. }
  12931. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12932. };
  12933. /**
  12934. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12935. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12936. * 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.
  12937. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12938. * 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.
  12939. */
  12940. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12941. if (checkFace === void 0) { checkFace = false; }
  12942. if (facing === void 0) { facing = true; }
  12943. var world = this.getWorldMatrix();
  12944. var invMat = BABYLON.Tmp.Matrix[5];
  12945. world.invertToRef(invMat);
  12946. var invVect = BABYLON.Tmp.Vector3[8];
  12947. var closest = null;
  12948. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12949. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12950. if (projected) {
  12951. // tranform the local computed projected vector to world coordinates
  12952. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12953. }
  12954. return closest;
  12955. };
  12956. /**
  12957. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12958. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12959. * 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.
  12960. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12961. * 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.
  12962. */
  12963. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12964. if (checkFace === void 0) { checkFace = false; }
  12965. if (facing === void 0) { facing = true; }
  12966. var closest = null;
  12967. var tmpx = 0.0;
  12968. var tmpy = 0.0;
  12969. var tmpz = 0.0;
  12970. var d = 0.0; // tmp dot facet normal * facet position
  12971. var t0 = 0.0;
  12972. var projx = 0.0;
  12973. var projy = 0.0;
  12974. var projz = 0.0;
  12975. // Get all the facets in the same partitioning block than (x, y, z)
  12976. var facetPositions = this.getFacetLocalPositions();
  12977. var facetNormals = this.getFacetLocalNormals();
  12978. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12979. if (!facetsInBlock) {
  12980. return null;
  12981. }
  12982. // Get the closest facet to (x, y, z)
  12983. var shortest = Number.MAX_VALUE; // init distance vars
  12984. var tmpDistance = shortest;
  12985. var fib; // current facet in the block
  12986. var norm; // current facet normal
  12987. var p0; // current facet barycenter position
  12988. // loop on all the facets in the current partitioning block
  12989. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12990. fib = facetsInBlock[idx];
  12991. norm = facetNormals[fib];
  12992. p0 = facetPositions[fib];
  12993. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12994. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12995. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12996. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12997. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12998. projx = x + norm.x * t0;
  12999. projy = y + norm.y * t0;
  13000. projz = z + norm.z * t0;
  13001. tmpx = projx - x;
  13002. tmpy = projy - y;
  13003. tmpz = projz - z;
  13004. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13005. if (tmpDistance < shortest) {
  13006. shortest = tmpDistance;
  13007. closest = fib;
  13008. if (projected) {
  13009. projected.x = projx;
  13010. projected.y = projy;
  13011. projected.z = projz;
  13012. }
  13013. }
  13014. }
  13015. }
  13016. return closest;
  13017. };
  13018. /**
  13019. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13020. */
  13021. AbstractMesh.prototype.getFacetDataParameters = function () {
  13022. return this._facetParameters;
  13023. };
  13024. /**
  13025. * Disables the feature FacetData and frees the related memory.
  13026. * Returns the AbstractMesh.
  13027. */
  13028. AbstractMesh.prototype.disableFacetData = function () {
  13029. if (this._facetDataEnabled) {
  13030. this._facetDataEnabled = false;
  13031. this._facetPositions = null;
  13032. this._facetNormals = null;
  13033. this._facetPartitioning = null;
  13034. this._facetParameters = null;
  13035. }
  13036. return this;
  13037. };
  13038. /**
  13039. * Creates new normals data for the mesh.
  13040. * @param updatable.
  13041. */
  13042. AbstractMesh.prototype.createNormals = function (updatable) {
  13043. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13044. var indices = this.getIndices();
  13045. var normals;
  13046. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13047. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13048. }
  13049. else {
  13050. normals = [];
  13051. }
  13052. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13053. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13054. };
  13055. return AbstractMesh;
  13056. }(BABYLON.Node));
  13057. // Statics
  13058. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13059. AbstractMesh._BILLBOARDMODE_X = 1;
  13060. AbstractMesh._BILLBOARDMODE_Y = 2;
  13061. AbstractMesh._BILLBOARDMODE_Z = 4;
  13062. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13063. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13064. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13065. BABYLON.AbstractMesh = AbstractMesh;
  13066. })(BABYLON || (BABYLON = {}));
  13067. //# sourceMappingURL=babylon.abstractMesh.js.map
  13068. var BABYLON;
  13069. (function (BABYLON) {
  13070. var Light = (function (_super) {
  13071. __extends(Light, _super);
  13072. /**
  13073. * Creates a Light object in the scene.
  13074. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13075. */
  13076. function Light(name, scene) {
  13077. var _this = _super.call(this, name, scene) || this;
  13078. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13079. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13080. _this.intensity = 1.0;
  13081. _this.range = Number.MAX_VALUE;
  13082. /**
  13083. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13084. * of light.
  13085. */
  13086. _this._photometricScale = 1.0;
  13087. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13088. _this._radius = 0.00001;
  13089. _this.renderPriority = 0;
  13090. /**
  13091. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13092. * the current shadow generator.
  13093. */
  13094. _this.shadowEnabled = true;
  13095. _this._excludeWithLayerMask = 0;
  13096. _this._includeOnlyWithLayerMask = 0;
  13097. _this._lightmapMode = 0;
  13098. _this._excludedMeshesIds = new Array();
  13099. _this._includedOnlyMeshesIds = new Array();
  13100. _this.getScene().addLight(_this);
  13101. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13102. _this._buildUniformLayout();
  13103. _this.includedOnlyMeshes = new Array();
  13104. _this.excludedMeshes = new Array();
  13105. _this._resyncMeshes();
  13106. return _this;
  13107. }
  13108. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13109. /**
  13110. * If every light affecting the material is in this lightmapMode,
  13111. * material.lightmapTexture adds or multiplies
  13112. * (depends on material.useLightmapAsShadowmap)
  13113. * after every other light calculations.
  13114. */
  13115. get: function () {
  13116. return Light._LIGHTMAP_DEFAULT;
  13117. },
  13118. enumerable: true,
  13119. configurable: true
  13120. });
  13121. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13122. /**
  13123. * material.lightmapTexture as only diffuse lighting from this light
  13124. * adds pnly specular lighting from this light
  13125. * adds dynamic shadows
  13126. */
  13127. get: function () {
  13128. return Light._LIGHTMAP_SPECULAR;
  13129. },
  13130. enumerable: true,
  13131. configurable: true
  13132. });
  13133. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13134. /**
  13135. * material.lightmapTexture as only lighting
  13136. * no light calculation from this light
  13137. * only adds dynamic shadows from this light
  13138. */
  13139. get: function () {
  13140. return Light._LIGHTMAP_SHADOWSONLY;
  13141. },
  13142. enumerable: true,
  13143. configurable: true
  13144. });
  13145. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13146. /**
  13147. * Each light type uses the default quantity according to its type:
  13148. * point/spot lights use luminous intensity
  13149. * directional lights use illuminance
  13150. */
  13151. get: function () {
  13152. return Light._INTENSITYMODE_AUTOMATIC;
  13153. },
  13154. enumerable: true,
  13155. configurable: true
  13156. });
  13157. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13158. /**
  13159. * lumen (lm)
  13160. */
  13161. get: function () {
  13162. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13163. },
  13164. enumerable: true,
  13165. configurable: true
  13166. });
  13167. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13168. /**
  13169. * candela (lm/sr)
  13170. */
  13171. get: function () {
  13172. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13173. },
  13174. enumerable: true,
  13175. configurable: true
  13176. });
  13177. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13178. /**
  13179. * lux (lm/m^2)
  13180. */
  13181. get: function () {
  13182. return Light._INTENSITYMODE_ILLUMINANCE;
  13183. },
  13184. enumerable: true,
  13185. configurable: true
  13186. });
  13187. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13188. /**
  13189. * nit (cd/m^2)
  13190. */
  13191. get: function () {
  13192. return Light._INTENSITYMODE_LUMINANCE;
  13193. },
  13194. enumerable: true,
  13195. configurable: true
  13196. });
  13197. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13198. /**
  13199. * Light type const id of the point light.
  13200. */
  13201. get: function () {
  13202. return Light._LIGHTTYPEID_POINTLIGHT;
  13203. },
  13204. enumerable: true,
  13205. configurable: true
  13206. });
  13207. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13208. /**
  13209. * Light type const id of the directional light.
  13210. */
  13211. get: function () {
  13212. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13213. },
  13214. enumerable: true,
  13215. configurable: true
  13216. });
  13217. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13218. /**
  13219. * Light type const id of the spot light.
  13220. */
  13221. get: function () {
  13222. return Light._LIGHTTYPEID_SPOTLIGHT;
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13228. /**
  13229. * Light type const id of the hemispheric light.
  13230. */
  13231. get: function () {
  13232. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13233. },
  13234. enumerable: true,
  13235. configurable: true
  13236. });
  13237. Object.defineProperty(Light.prototype, "intensityMode", {
  13238. /**
  13239. * Gets the photometric scale used to interpret the intensity.
  13240. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13241. */
  13242. get: function () {
  13243. return this._intensityMode;
  13244. },
  13245. /**
  13246. * Sets the photometric scale used to interpret the intensity.
  13247. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13248. */
  13249. set: function (value) {
  13250. this._intensityMode = value;
  13251. this._computePhotometricScale();
  13252. },
  13253. enumerable: true,
  13254. configurable: true
  13255. });
  13256. ;
  13257. ;
  13258. Object.defineProperty(Light.prototype, "radius", {
  13259. /**
  13260. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13261. */
  13262. get: function () {
  13263. return this._radius;
  13264. },
  13265. /**
  13266. * sets the light radius used by PBR Materials to simulate soft area lights.
  13267. */
  13268. set: function (value) {
  13269. this._radius = value;
  13270. this._computePhotometricScale();
  13271. },
  13272. enumerable: true,
  13273. configurable: true
  13274. });
  13275. ;
  13276. ;
  13277. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13278. get: function () {
  13279. return this._includedOnlyMeshes;
  13280. },
  13281. set: function (value) {
  13282. this._includedOnlyMeshes = value;
  13283. this._hookArrayForIncludedOnly(value);
  13284. },
  13285. enumerable: true,
  13286. configurable: true
  13287. });
  13288. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13289. get: function () {
  13290. return this._excludedMeshes;
  13291. },
  13292. set: function (value) {
  13293. this._excludedMeshes = value;
  13294. this._hookArrayForExcluded(value);
  13295. },
  13296. enumerable: true,
  13297. configurable: true
  13298. });
  13299. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13300. get: function () {
  13301. return this._excludeWithLayerMask;
  13302. },
  13303. set: function (value) {
  13304. this._excludeWithLayerMask = value;
  13305. this._resyncMeshes();
  13306. },
  13307. enumerable: true,
  13308. configurable: true
  13309. });
  13310. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13311. get: function () {
  13312. return this._includeOnlyWithLayerMask;
  13313. },
  13314. set: function (value) {
  13315. this._includeOnlyWithLayerMask = value;
  13316. this._resyncMeshes();
  13317. },
  13318. enumerable: true,
  13319. configurable: true
  13320. });
  13321. Object.defineProperty(Light.prototype, "lightmapMode", {
  13322. get: function () {
  13323. return this._lightmapMode;
  13324. },
  13325. set: function (value) {
  13326. if (this._lightmapMode === value) {
  13327. return;
  13328. }
  13329. this._lightmapMode = value;
  13330. this._markMeshesAsLightDirty();
  13331. },
  13332. enumerable: true,
  13333. configurable: true
  13334. });
  13335. Light.prototype._buildUniformLayout = function () {
  13336. // Overridden
  13337. };
  13338. /**
  13339. * Returns the string "Light".
  13340. */
  13341. Light.prototype.getClassName = function () {
  13342. return "Light";
  13343. };
  13344. /**
  13345. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13346. */
  13347. Light.prototype.toString = function (fullDetails) {
  13348. var ret = "Name: " + this.name;
  13349. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13350. if (this.animations) {
  13351. for (var i = 0; i < this.animations.length; i++) {
  13352. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13353. }
  13354. }
  13355. if (fullDetails) {
  13356. }
  13357. return ret;
  13358. };
  13359. /**
  13360. * Set the enabled state of this node.
  13361. * @param {boolean} value - the new enabled state
  13362. * @see isEnabled
  13363. */
  13364. Light.prototype.setEnabled = function (value) {
  13365. _super.prototype.setEnabled.call(this, value);
  13366. this._resyncMeshes();
  13367. };
  13368. /**
  13369. * Returns the Light associated shadow generator.
  13370. */
  13371. Light.prototype.getShadowGenerator = function () {
  13372. return this._shadowGenerator;
  13373. };
  13374. /**
  13375. * Returns a Vector3, the absolute light position in the World.
  13376. */
  13377. Light.prototype.getAbsolutePosition = function () {
  13378. return BABYLON.Vector3.Zero();
  13379. };
  13380. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13381. };
  13382. Light.prototype._getWorldMatrix = function () {
  13383. return BABYLON.Matrix.Identity();
  13384. };
  13385. /**
  13386. * Boolean : True if the light will affect the passed mesh.
  13387. */
  13388. Light.prototype.canAffectMesh = function (mesh) {
  13389. if (!mesh) {
  13390. return true;
  13391. }
  13392. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13393. return false;
  13394. }
  13395. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13396. return false;
  13397. }
  13398. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13399. return false;
  13400. }
  13401. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13402. return false;
  13403. }
  13404. return true;
  13405. };
  13406. /**
  13407. * Returns the light World matrix.
  13408. */
  13409. Light.prototype.getWorldMatrix = function () {
  13410. this._currentRenderId = this.getScene().getRenderId();
  13411. var worldMatrix = this._getWorldMatrix();
  13412. if (this.parent && this.parent.getWorldMatrix) {
  13413. if (!this._parentedWorldMatrix) {
  13414. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13415. }
  13416. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13417. this._markSyncedWithParent();
  13418. return this._parentedWorldMatrix;
  13419. }
  13420. return worldMatrix;
  13421. };
  13422. /**
  13423. * Sort function to order lights for rendering.
  13424. * @param a First Light object to compare to second.
  13425. * @param b Second Light object to compare first.
  13426. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13427. */
  13428. Light.compareLightsPriority = function (a, b) {
  13429. //shadow-casting lights have priority over non-shadow-casting lights
  13430. //the renderPrioirty is a secondary sort criterion
  13431. if (a.shadowEnabled !== b.shadowEnabled) {
  13432. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13433. }
  13434. return b.renderPriority - a.renderPriority;
  13435. };
  13436. /**
  13437. * Disposes the light.
  13438. */
  13439. Light.prototype.dispose = function () {
  13440. if (this._shadowGenerator) {
  13441. this._shadowGenerator.dispose();
  13442. this._shadowGenerator = null;
  13443. }
  13444. // Animations
  13445. this.getScene().stopAnimation(this);
  13446. // Remove from meshes
  13447. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13448. var mesh = _a[_i];
  13449. mesh._removeLightSource(this);
  13450. }
  13451. this._uniformBuffer.dispose();
  13452. // Remove from scene
  13453. this.getScene().removeLight(this);
  13454. _super.prototype.dispose.call(this);
  13455. };
  13456. /**
  13457. * Returns the light type ID (integer).
  13458. */
  13459. Light.prototype.getTypeID = function () {
  13460. return 0;
  13461. };
  13462. /**
  13463. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13464. */
  13465. Light.prototype.getScaledIntensity = function () {
  13466. return this._photometricScale * this.intensity;
  13467. };
  13468. /**
  13469. * Returns a new Light object, named "name", from the current one.
  13470. */
  13471. Light.prototype.clone = function (name) {
  13472. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13473. };
  13474. /**
  13475. * Serializes the current light into a Serialization object.
  13476. * Returns the serialized object.
  13477. */
  13478. Light.prototype.serialize = function () {
  13479. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13480. // Type
  13481. serializationObject.type = this.getTypeID();
  13482. // Parent
  13483. if (this.parent) {
  13484. serializationObject.parentId = this.parent.id;
  13485. }
  13486. // Inclusion / exclusions
  13487. if (this.excludedMeshes.length > 0) {
  13488. serializationObject.excludedMeshesIds = [];
  13489. this.excludedMeshes.forEach(function (mesh) {
  13490. serializationObject.excludedMeshesIds.push(mesh.id);
  13491. });
  13492. }
  13493. if (this.includedOnlyMeshes.length > 0) {
  13494. serializationObject.includedOnlyMeshesIds = [];
  13495. this.includedOnlyMeshes.forEach(function (mesh) {
  13496. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13497. });
  13498. }
  13499. // Animations
  13500. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13501. serializationObject.ranges = this.serializeAnimationRanges();
  13502. return serializationObject;
  13503. };
  13504. /**
  13505. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13506. * This new light is named "name" and added to the passed scene.
  13507. */
  13508. Light.GetConstructorFromName = function (type, name, scene) {
  13509. switch (type) {
  13510. case 0:
  13511. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13512. case 1:
  13513. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13514. case 2:
  13515. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13516. case 3:
  13517. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13518. }
  13519. };
  13520. /**
  13521. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13522. */
  13523. Light.Parse = function (parsedLight, scene) {
  13524. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13525. // Inclusion / exclusions
  13526. if (parsedLight.excludedMeshesIds) {
  13527. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13528. }
  13529. if (parsedLight.includedOnlyMeshesIds) {
  13530. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13531. }
  13532. // Parent
  13533. if (parsedLight.parentId) {
  13534. light._waitingParentId = parsedLight.parentId;
  13535. }
  13536. // Animations
  13537. if (parsedLight.animations) {
  13538. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13539. var parsedAnimation = parsedLight.animations[animationIndex];
  13540. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13541. }
  13542. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13543. }
  13544. if (parsedLight.autoAnimate) {
  13545. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13546. }
  13547. return light;
  13548. };
  13549. Light.prototype._hookArrayForExcluded = function (array) {
  13550. var _this = this;
  13551. var oldPush = array.push;
  13552. array.push = function () {
  13553. var items = [];
  13554. for (var _i = 0; _i < arguments.length; _i++) {
  13555. items[_i] = arguments[_i];
  13556. }
  13557. var result = oldPush.apply(array, items);
  13558. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13559. var item = items_1[_a];
  13560. item._resyncLighSource(_this);
  13561. }
  13562. return result;
  13563. };
  13564. var oldSplice = array.splice;
  13565. array.splice = function (index, deleteCount) {
  13566. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13567. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13568. var item = deleted_1[_i];
  13569. item._resyncLighSource(_this);
  13570. }
  13571. return deleted;
  13572. };
  13573. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13574. var item = array_1[_i];
  13575. item._resyncLighSource(this);
  13576. }
  13577. };
  13578. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13579. var _this = this;
  13580. var oldPush = array.push;
  13581. array.push = function () {
  13582. var items = [];
  13583. for (var _i = 0; _i < arguments.length; _i++) {
  13584. items[_i] = arguments[_i];
  13585. }
  13586. var result = oldPush.apply(array, items);
  13587. _this._resyncMeshes();
  13588. return result;
  13589. };
  13590. var oldSplice = array.splice;
  13591. array.splice = function (index, deleteCount) {
  13592. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13593. _this._resyncMeshes();
  13594. return deleted;
  13595. };
  13596. this._resyncMeshes();
  13597. };
  13598. Light.prototype._resyncMeshes = function () {
  13599. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13600. var mesh = _a[_i];
  13601. mesh._resyncLighSource(this);
  13602. }
  13603. };
  13604. Light.prototype._markMeshesAsLightDirty = function () {
  13605. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13606. var mesh = _a[_i];
  13607. if (mesh._lightSources.indexOf(this) !== -1) {
  13608. mesh._markSubMeshesAsLightDirty();
  13609. }
  13610. }
  13611. };
  13612. /**
  13613. * Recomputes the cached photometric scale if needed.
  13614. */
  13615. Light.prototype._computePhotometricScale = function () {
  13616. this._photometricScale = this._getPhotometricScale();
  13617. this.getScene().resetCachedMaterial();
  13618. };
  13619. /**
  13620. * Returns the Photometric Scale according to the light type and intensity mode.
  13621. */
  13622. Light.prototype._getPhotometricScale = function () {
  13623. var photometricScale = 0.0;
  13624. var lightTypeID = this.getTypeID();
  13625. //get photometric mode
  13626. var photometricMode = this.intensityMode;
  13627. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13628. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13629. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13630. }
  13631. else {
  13632. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13633. }
  13634. }
  13635. //compute photometric scale
  13636. switch (lightTypeID) {
  13637. case Light.LIGHTTYPEID_POINTLIGHT:
  13638. case Light.LIGHTTYPEID_SPOTLIGHT:
  13639. switch (photometricMode) {
  13640. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13641. photometricScale = 1.0 / (4.0 * Math.PI);
  13642. break;
  13643. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13644. photometricScale = 1.0;
  13645. break;
  13646. case Light.INTENSITYMODE_LUMINANCE:
  13647. photometricScale = this.radius * this.radius;
  13648. break;
  13649. }
  13650. break;
  13651. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13652. switch (photometricMode) {
  13653. case Light.INTENSITYMODE_ILLUMINANCE:
  13654. photometricScale = 1.0;
  13655. break;
  13656. case Light.INTENSITYMODE_LUMINANCE:
  13657. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13658. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13659. var apexAngleRadians = this.radius;
  13660. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13661. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13662. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13663. photometricScale = solidAngle;
  13664. break;
  13665. }
  13666. break;
  13667. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13668. // No fall off in hemisperic light.
  13669. photometricScale = 1.0;
  13670. break;
  13671. }
  13672. return photometricScale;
  13673. };
  13674. Light.prototype._reorderLightsInScene = function () {
  13675. var scene = this.getScene();
  13676. if (this.renderPriority != 0) {
  13677. scene.requireLightSorting = true;
  13678. }
  13679. this.getScene().sortLightsByPriority();
  13680. };
  13681. return Light;
  13682. }(BABYLON.Node));
  13683. //lightmapMode Consts
  13684. Light._LIGHTMAP_DEFAULT = 0;
  13685. Light._LIGHTMAP_SPECULAR = 1;
  13686. Light._LIGHTMAP_SHADOWSONLY = 2;
  13687. // Intensity Mode Consts
  13688. Light._INTENSITYMODE_AUTOMATIC = 0;
  13689. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13690. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13691. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13692. Light._INTENSITYMODE_LUMINANCE = 4;
  13693. // Light types ids const.
  13694. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13695. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13696. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13697. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13698. __decorate([
  13699. BABYLON.serializeAsColor3()
  13700. ], Light.prototype, "diffuse", void 0);
  13701. __decorate([
  13702. BABYLON.serializeAsColor3()
  13703. ], Light.prototype, "specular", void 0);
  13704. __decorate([
  13705. BABYLON.serialize()
  13706. ], Light.prototype, "intensity", void 0);
  13707. __decorate([
  13708. BABYLON.serialize()
  13709. ], Light.prototype, "range", void 0);
  13710. __decorate([
  13711. BABYLON.serialize()
  13712. ], Light.prototype, "intensityMode", null);
  13713. __decorate([
  13714. BABYLON.serialize()
  13715. ], Light.prototype, "radius", null);
  13716. __decorate([
  13717. BABYLON.serialize()
  13718. ], Light.prototype, "_renderPriority", void 0);
  13719. __decorate([
  13720. BABYLON.expandToProperty("_reorderLightsInScene")
  13721. ], Light.prototype, "renderPriority", void 0);
  13722. __decorate([
  13723. BABYLON.serialize()
  13724. ], Light.prototype, "shadowEnabled", void 0);
  13725. __decorate([
  13726. BABYLON.serialize("excludeWithLayerMask")
  13727. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13728. __decorate([
  13729. BABYLON.serialize("includeOnlyWithLayerMask")
  13730. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13731. __decorate([
  13732. BABYLON.serialize("lightmapMode")
  13733. ], Light.prototype, "_lightmapMode", void 0);
  13734. BABYLON.Light = Light;
  13735. })(BABYLON || (BABYLON = {}));
  13736. //# sourceMappingURL=babylon.light.js.map
  13737. var BABYLON;
  13738. (function (BABYLON) {
  13739. var Camera = (function (_super) {
  13740. __extends(Camera, _super);
  13741. function Camera(name, position, scene) {
  13742. var _this = _super.call(this, name, scene) || this;
  13743. _this.upVector = BABYLON.Vector3.Up();
  13744. _this.orthoLeft = null;
  13745. _this.orthoRight = null;
  13746. _this.orthoBottom = null;
  13747. _this.orthoTop = null;
  13748. _this.fov = 0.8;
  13749. _this.minZ = 1.0;
  13750. _this.maxZ = 10000.0;
  13751. _this.inertia = 0.9;
  13752. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13753. _this.isIntermediate = false;
  13754. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13755. _this.layerMask = 0x0FFFFFFF;
  13756. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13757. // Camera rig members
  13758. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13759. _this._rigCameras = new Array();
  13760. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13761. // Cache
  13762. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13763. _this._projectionMatrix = new BABYLON.Matrix();
  13764. _this._doNotComputeProjectionMatrix = false;
  13765. _this._postProcesses = new Array();
  13766. _this._transformMatrix = BABYLON.Matrix.Zero();
  13767. _this._activeMeshes = new BABYLON.SmartArray(256);
  13768. _this._globalPosition = BABYLON.Vector3.Zero();
  13769. _this._refreshFrustumPlanes = true;
  13770. _this.getScene().addCamera(_this);
  13771. if (!_this.getScene().activeCamera) {
  13772. _this.getScene().activeCamera = _this;
  13773. }
  13774. _this.position = position;
  13775. return _this;
  13776. }
  13777. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13778. get: function () {
  13779. return Camera._PERSPECTIVE_CAMERA;
  13780. },
  13781. enumerable: true,
  13782. configurable: true
  13783. });
  13784. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13785. get: function () {
  13786. return Camera._ORTHOGRAPHIC_CAMERA;
  13787. },
  13788. enumerable: true,
  13789. configurable: true
  13790. });
  13791. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13792. get: function () {
  13793. return Camera._FOVMODE_VERTICAL_FIXED;
  13794. },
  13795. enumerable: true,
  13796. configurable: true
  13797. });
  13798. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13799. get: function () {
  13800. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13801. },
  13802. enumerable: true,
  13803. configurable: true
  13804. });
  13805. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13806. get: function () {
  13807. return Camera._RIG_MODE_NONE;
  13808. },
  13809. enumerable: true,
  13810. configurable: true
  13811. });
  13812. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13813. get: function () {
  13814. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13815. },
  13816. enumerable: true,
  13817. configurable: true
  13818. });
  13819. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13820. get: function () {
  13821. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13822. },
  13823. enumerable: true,
  13824. configurable: true
  13825. });
  13826. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13827. get: function () {
  13828. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13829. },
  13830. enumerable: true,
  13831. configurable: true
  13832. });
  13833. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13834. get: function () {
  13835. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13836. },
  13837. enumerable: true,
  13838. configurable: true
  13839. });
  13840. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13841. get: function () {
  13842. return Camera._RIG_MODE_VR;
  13843. },
  13844. enumerable: true,
  13845. configurable: true
  13846. });
  13847. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13848. get: function () {
  13849. return Camera._RIG_MODE_WEBVR;
  13850. },
  13851. enumerable: true,
  13852. configurable: true
  13853. });
  13854. Camera.prototype.getClassName = function () {
  13855. return "Camera";
  13856. };
  13857. /**
  13858. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13859. */
  13860. Camera.prototype.toString = function (fullDetails) {
  13861. var ret = "Name: " + this.name;
  13862. ret += ", type: " + this.getClassName();
  13863. if (this.animations) {
  13864. for (var i = 0; i < this.animations.length; i++) {
  13865. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13866. }
  13867. }
  13868. if (fullDetails) {
  13869. }
  13870. return ret;
  13871. };
  13872. Object.defineProperty(Camera.prototype, "globalPosition", {
  13873. get: function () {
  13874. return this._globalPosition;
  13875. },
  13876. enumerable: true,
  13877. configurable: true
  13878. });
  13879. Camera.prototype.getActiveMeshes = function () {
  13880. return this._activeMeshes;
  13881. };
  13882. Camera.prototype.isActiveMesh = function (mesh) {
  13883. return (this._activeMeshes.indexOf(mesh) !== -1);
  13884. };
  13885. //Cache
  13886. Camera.prototype._initCache = function () {
  13887. _super.prototype._initCache.call(this);
  13888. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13889. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13890. this._cache.mode = undefined;
  13891. this._cache.minZ = undefined;
  13892. this._cache.maxZ = undefined;
  13893. this._cache.fov = undefined;
  13894. this._cache.fovMode = undefined;
  13895. this._cache.aspectRatio = undefined;
  13896. this._cache.orthoLeft = undefined;
  13897. this._cache.orthoRight = undefined;
  13898. this._cache.orthoBottom = undefined;
  13899. this._cache.orthoTop = undefined;
  13900. this._cache.renderWidth = undefined;
  13901. this._cache.renderHeight = undefined;
  13902. };
  13903. Camera.prototype._updateCache = function (ignoreParentClass) {
  13904. if (!ignoreParentClass) {
  13905. _super.prototype._updateCache.call(this);
  13906. }
  13907. var engine = this.getEngine();
  13908. this._cache.position.copyFrom(this.position);
  13909. this._cache.upVector.copyFrom(this.upVector);
  13910. this._cache.mode = this.mode;
  13911. this._cache.minZ = this.minZ;
  13912. this._cache.maxZ = this.maxZ;
  13913. this._cache.fov = this.fov;
  13914. this._cache.fovMode = this.fovMode;
  13915. this._cache.aspectRatio = engine.getAspectRatio(this);
  13916. this._cache.orthoLeft = this.orthoLeft;
  13917. this._cache.orthoRight = this.orthoRight;
  13918. this._cache.orthoBottom = this.orthoBottom;
  13919. this._cache.orthoTop = this.orthoTop;
  13920. this._cache.renderWidth = engine.getRenderWidth();
  13921. this._cache.renderHeight = engine.getRenderHeight();
  13922. };
  13923. Camera.prototype._updateFromScene = function () {
  13924. this.updateCache();
  13925. this.update();
  13926. };
  13927. // Synchronized
  13928. Camera.prototype._isSynchronized = function () {
  13929. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13930. };
  13931. Camera.prototype._isSynchronizedViewMatrix = function () {
  13932. if (!_super.prototype._isSynchronized.call(this))
  13933. return false;
  13934. return this._cache.position.equals(this.position)
  13935. && this._cache.upVector.equals(this.upVector)
  13936. && this.isSynchronizedWithParent();
  13937. };
  13938. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13939. var check = this._cache.mode === this.mode
  13940. && this._cache.minZ === this.minZ
  13941. && this._cache.maxZ === this.maxZ;
  13942. if (!check) {
  13943. return false;
  13944. }
  13945. var engine = this.getEngine();
  13946. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13947. check = this._cache.fov === this.fov
  13948. && this._cache.fovMode === this.fovMode
  13949. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13950. }
  13951. else {
  13952. check = this._cache.orthoLeft === this.orthoLeft
  13953. && this._cache.orthoRight === this.orthoRight
  13954. && this._cache.orthoBottom === this.orthoBottom
  13955. && this._cache.orthoTop === this.orthoTop
  13956. && this._cache.renderWidth === engine.getRenderWidth()
  13957. && this._cache.renderHeight === engine.getRenderHeight();
  13958. }
  13959. return check;
  13960. };
  13961. // Controls
  13962. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13963. };
  13964. Camera.prototype.detachControl = function (element) {
  13965. };
  13966. Camera.prototype.update = function () {
  13967. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13968. this._updateRigCameras();
  13969. }
  13970. this._checkInputs();
  13971. };
  13972. Camera.prototype._checkInputs = function () {
  13973. };
  13974. Object.defineProperty(Camera.prototype, "rigCameras", {
  13975. get: function () {
  13976. return this._rigCameras;
  13977. },
  13978. enumerable: true,
  13979. configurable: true
  13980. });
  13981. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  13982. get: function () {
  13983. return this._rigPostProcess;
  13984. },
  13985. enumerable: true,
  13986. configurable: true
  13987. });
  13988. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13989. // invalidate framebuffer
  13990. if (this._postProcesses.length > 0) {
  13991. this._postProcesses[0].markTextureDirty();
  13992. }
  13993. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13994. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13995. var cam = this._rigCameras[i];
  13996. var rigPostProcess = cam._rigPostProcess;
  13997. // for VR rig, there does not have to be a post process
  13998. if (rigPostProcess) {
  13999. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14000. if (isPass) {
  14001. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14002. cam.isIntermediate = this._postProcesses.length === 0;
  14003. }
  14004. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14005. rigPostProcess.markTextureDirty();
  14006. }
  14007. else {
  14008. cam._postProcesses = this._postProcesses.slice(0);
  14009. }
  14010. }
  14011. };
  14012. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14013. if (insertAt === void 0) { insertAt = null; }
  14014. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14015. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14016. return 0;
  14017. }
  14018. if (insertAt == null || insertAt < 0) {
  14019. this._postProcesses.push(postProcess);
  14020. }
  14021. else {
  14022. this._postProcesses.splice(insertAt, 0, postProcess);
  14023. }
  14024. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14025. return this._postProcesses.indexOf(postProcess);
  14026. };
  14027. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14028. if (atIndices === void 0) { atIndices = null; }
  14029. var result = [];
  14030. var i;
  14031. var index;
  14032. if (!atIndices) {
  14033. var idx = this._postProcesses.indexOf(postProcess);
  14034. if (idx !== -1) {
  14035. this._postProcesses.splice(idx, 1);
  14036. }
  14037. }
  14038. else {
  14039. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14040. // iterate descending, so can just splice as we go
  14041. for (i = atIndices.length - 1; i >= 0; i--) {
  14042. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14043. result.push(i);
  14044. continue;
  14045. }
  14046. index = atIndices[i];
  14047. this._postProcesses.splice(index, 1);
  14048. }
  14049. }
  14050. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14051. return result;
  14052. };
  14053. Camera.prototype.getWorldMatrix = function () {
  14054. if (!this._worldMatrix) {
  14055. this._worldMatrix = BABYLON.Matrix.Identity();
  14056. }
  14057. var viewMatrix = this.getViewMatrix();
  14058. viewMatrix.invertToRef(this._worldMatrix);
  14059. return this._worldMatrix;
  14060. };
  14061. Camera.prototype._getViewMatrix = function () {
  14062. return BABYLON.Matrix.Identity();
  14063. };
  14064. Camera.prototype.getViewMatrix = function (force) {
  14065. this._computedViewMatrix = this._computeViewMatrix(force);
  14066. if (!force && this._isSynchronizedViewMatrix()) {
  14067. return this._computedViewMatrix;
  14068. }
  14069. this._refreshFrustumPlanes = true;
  14070. if (!this.parent || !this.parent.getWorldMatrix) {
  14071. this._globalPosition.copyFrom(this.position);
  14072. }
  14073. else {
  14074. if (!this._worldMatrix) {
  14075. this._worldMatrix = BABYLON.Matrix.Identity();
  14076. }
  14077. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14078. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14079. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14080. this._computedViewMatrix.invert();
  14081. this._markSyncedWithParent();
  14082. }
  14083. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14084. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14085. }
  14086. this._currentRenderId = this.getScene().getRenderId();
  14087. return this._computedViewMatrix;
  14088. };
  14089. Camera.prototype._computeViewMatrix = function (force) {
  14090. if (!force && this._isSynchronizedViewMatrix()) {
  14091. return this._computedViewMatrix;
  14092. }
  14093. this._computedViewMatrix = this._getViewMatrix();
  14094. this._currentRenderId = this.getScene().getRenderId();
  14095. return this._computedViewMatrix;
  14096. };
  14097. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14098. this._doNotComputeProjectionMatrix = true;
  14099. if (projection !== undefined) {
  14100. this._projectionMatrix = projection;
  14101. }
  14102. };
  14103. ;
  14104. Camera.prototype.unfreezeProjectionMatrix = function () {
  14105. this._doNotComputeProjectionMatrix = false;
  14106. };
  14107. ;
  14108. Camera.prototype.getProjectionMatrix = function (force) {
  14109. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14110. return this._projectionMatrix;
  14111. }
  14112. this._refreshFrustumPlanes = true;
  14113. var engine = this.getEngine();
  14114. var scene = this.getScene();
  14115. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14116. if (this.minZ <= 0) {
  14117. this.minZ = 0.1;
  14118. }
  14119. if (scene.useRightHandedSystem) {
  14120. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14121. }
  14122. else {
  14123. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14124. }
  14125. return this._projectionMatrix;
  14126. }
  14127. var halfWidth = engine.getRenderWidth() / 2.0;
  14128. var halfHeight = engine.getRenderHeight() / 2.0;
  14129. if (scene.useRightHandedSystem) {
  14130. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14131. }
  14132. else {
  14133. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14134. }
  14135. return this._projectionMatrix;
  14136. };
  14137. Camera.prototype.getTranformationMatrix = function () {
  14138. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14139. return this._transformMatrix;
  14140. };
  14141. Camera.prototype.updateFrustumPlanes = function () {
  14142. if (!this._refreshFrustumPlanes) {
  14143. return;
  14144. }
  14145. this.getTranformationMatrix();
  14146. if (!this._frustumPlanes) {
  14147. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14148. }
  14149. else {
  14150. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14151. }
  14152. this._refreshFrustumPlanes = false;
  14153. };
  14154. Camera.prototype.isInFrustum = function (target) {
  14155. this.updateFrustumPlanes();
  14156. return target.isInFrustum(this._frustumPlanes);
  14157. };
  14158. Camera.prototype.isCompletelyInFrustum = function (target) {
  14159. this.updateFrustumPlanes();
  14160. return target.isCompletelyInFrustum(this._frustumPlanes);
  14161. };
  14162. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14163. if (length === void 0) { length = 100; }
  14164. if (!transform) {
  14165. transform = this.getWorldMatrix();
  14166. }
  14167. if (!origin) {
  14168. origin = this.position;
  14169. }
  14170. var forward = new BABYLON.Vector3(0, 0, 1);
  14171. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14172. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14173. return new BABYLON.Ray(origin, direction, length);
  14174. };
  14175. Camera.prototype.dispose = function () {
  14176. // Animations
  14177. this.getScene().stopAnimation(this);
  14178. // Remove from scene
  14179. this.getScene().removeCamera(this);
  14180. while (this._rigCameras.length > 0) {
  14181. this._rigCameras.pop().dispose();
  14182. }
  14183. // Postprocesses
  14184. var i = this._postProcesses.length;
  14185. while (--i >= 0) {
  14186. this._postProcesses[i].dispose(this);
  14187. }
  14188. _super.prototype.dispose.call(this);
  14189. };
  14190. Object.defineProperty(Camera.prototype, "leftCamera", {
  14191. // ---- Camera rigs section ----
  14192. get: function () {
  14193. if (this._rigCameras.length < 1) {
  14194. return undefined;
  14195. }
  14196. return this._rigCameras[0];
  14197. },
  14198. enumerable: true,
  14199. configurable: true
  14200. });
  14201. Object.defineProperty(Camera.prototype, "rightCamera", {
  14202. get: function () {
  14203. if (this._rigCameras.length < 2) {
  14204. return undefined;
  14205. }
  14206. return this._rigCameras[1];
  14207. },
  14208. enumerable: true,
  14209. configurable: true
  14210. });
  14211. Camera.prototype.getLeftTarget = function () {
  14212. if (this._rigCameras.length < 1) {
  14213. return undefined;
  14214. }
  14215. return this._rigCameras[0].getTarget();
  14216. };
  14217. Camera.prototype.getRightTarget = function () {
  14218. if (this._rigCameras.length < 2) {
  14219. return undefined;
  14220. }
  14221. return this._rigCameras[1].getTarget();
  14222. };
  14223. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14224. while (this._rigCameras.length > 0) {
  14225. this._rigCameras.pop().dispose();
  14226. }
  14227. this.cameraRigMode = mode;
  14228. this._cameraRigParams = {};
  14229. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14230. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14231. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14232. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14233. // create the rig cameras, unless none
  14234. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14235. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14236. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14237. }
  14238. switch (this.cameraRigMode) {
  14239. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14240. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14241. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14242. break;
  14243. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14244. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14245. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14246. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14247. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14248. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14249. break;
  14250. case Camera.RIG_MODE_VR:
  14251. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14252. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14253. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14254. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14255. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14256. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14257. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14258. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14259. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14260. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14261. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14262. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14263. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14264. if (metrics.compensateDistortion) {
  14265. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14266. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14267. }
  14268. break;
  14269. case Camera.RIG_MODE_WEBVR:
  14270. if (rigParams.vrDisplay) {
  14271. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14272. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14273. //Left eye
  14274. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14275. this._rigCameras[0].setCameraRigParameter("left", true);
  14276. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14277. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14278. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14279. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14280. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14281. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14282. this._rigCameras[0].parent = this;
  14283. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14284. //Right eye
  14285. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14286. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14287. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14288. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14289. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14290. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14291. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14292. this._rigCameras[1].parent = this;
  14293. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14294. }
  14295. break;
  14296. }
  14297. this._cascadePostProcessesToRigCams();
  14298. this.
  14299. update();
  14300. };
  14301. Camera.prototype._getVRProjectionMatrix = function () {
  14302. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14303. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14304. return this._projectionMatrix;
  14305. };
  14306. Camera.prototype._updateCameraRotationMatrix = function () {
  14307. //Here for WebVR
  14308. };
  14309. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14310. //Here for WebVR
  14311. };
  14312. /**
  14313. * This function MUST be overwritten by the different WebVR cameras available.
  14314. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14315. */
  14316. Camera.prototype._getWebVRProjectionMatrix = function () {
  14317. return BABYLON.Matrix.Identity();
  14318. };
  14319. /**
  14320. * This function MUST be overwritten by the different WebVR cameras available.
  14321. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14322. */
  14323. Camera.prototype._getWebVRViewMatrix = function () {
  14324. return BABYLON.Matrix.Identity();
  14325. };
  14326. Camera.prototype.setCameraRigParameter = function (name, value) {
  14327. if (!this._cameraRigParams) {
  14328. this._cameraRigParams = {};
  14329. }
  14330. this._cameraRigParams[name] = value;
  14331. //provisionnally:
  14332. if (name === "interaxialDistance") {
  14333. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14334. }
  14335. };
  14336. /**
  14337. * needs to be overridden by children so sub has required properties to be copied
  14338. */
  14339. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14340. return null;
  14341. };
  14342. /**
  14343. * May need to be overridden by children
  14344. */
  14345. Camera.prototype._updateRigCameras = function () {
  14346. for (var i = 0; i < this._rigCameras.length; i++) {
  14347. this._rigCameras[i].minZ = this.minZ;
  14348. this._rigCameras[i].maxZ = this.maxZ;
  14349. this._rigCameras[i].fov = this.fov;
  14350. }
  14351. // only update viewport when ANAGLYPH
  14352. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14353. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14354. }
  14355. };
  14356. Camera.prototype._setupInputs = function () {
  14357. };
  14358. Camera.prototype.serialize = function () {
  14359. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14360. // Type
  14361. serializationObject.type = this.getClassName();
  14362. // Parent
  14363. if (this.parent) {
  14364. serializationObject.parentId = this.parent.id;
  14365. }
  14366. if (this.inputs) {
  14367. this.inputs.serialize(serializationObject);
  14368. }
  14369. // Animations
  14370. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14371. serializationObject.ranges = this.serializeAnimationRanges();
  14372. return serializationObject;
  14373. };
  14374. Camera.prototype.clone = function (name) {
  14375. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14376. };
  14377. Camera.prototype.getDirection = function (localAxis) {
  14378. var result = BABYLON.Vector3.Zero();
  14379. this.getDirectionToRef(localAxis, result);
  14380. return result;
  14381. };
  14382. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14383. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14384. };
  14385. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14386. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14387. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14388. switch (type) {
  14389. case "ArcRotateCamera":
  14390. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14391. case "DeviceOrientationCamera":
  14392. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14393. case "FollowCamera":
  14394. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14395. case "ArcFollowCamera":
  14396. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14397. case "GamepadCamera":
  14398. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14399. case "TouchCamera":
  14400. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14401. case "VirtualJoysticksCamera":
  14402. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14403. case "WebVRFreeCamera":
  14404. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14405. case "WebVRGamepadCamera":
  14406. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14407. case "VRDeviceOrientationFreeCamera":
  14408. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14409. case "VRDeviceOrientationGamepadCamera":
  14410. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14411. case "AnaglyphArcRotateCamera":
  14412. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14413. case "AnaglyphFreeCamera":
  14414. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14415. case "AnaglyphGamepadCamera":
  14416. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14417. case "AnaglyphUniversalCamera":
  14418. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14419. case "StereoscopicArcRotateCamera":
  14420. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14421. case "StereoscopicFreeCamera":
  14422. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14423. case "StereoscopicGamepadCamera":
  14424. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14425. case "StereoscopicUniversalCamera":
  14426. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14427. case "FreeCamera":
  14428. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14429. default:
  14430. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14431. }
  14432. };
  14433. Camera.Parse = function (parsedCamera, scene) {
  14434. var type = parsedCamera.type;
  14435. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14436. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14437. // Parent
  14438. if (parsedCamera.parentId) {
  14439. camera._waitingParentId = parsedCamera.parentId;
  14440. }
  14441. //If camera has an input manager, let it parse inputs settings
  14442. if (camera.inputs) {
  14443. camera.inputs.parse(parsedCamera);
  14444. camera._setupInputs();
  14445. }
  14446. // Target
  14447. if (parsedCamera.target) {
  14448. if (camera.setTarget) {
  14449. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14450. }
  14451. }
  14452. // Apply 3d rig, when found
  14453. if (parsedCamera.cameraRigMode) {
  14454. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14455. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14456. }
  14457. // Animations
  14458. if (parsedCamera.animations) {
  14459. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14460. var parsedAnimation = parsedCamera.animations[animationIndex];
  14461. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14462. }
  14463. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14464. }
  14465. if (parsedCamera.autoAnimate) {
  14466. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14467. }
  14468. return camera;
  14469. };
  14470. return Camera;
  14471. }(BABYLON.Node));
  14472. // Statics
  14473. Camera._PERSPECTIVE_CAMERA = 0;
  14474. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14475. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14476. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14477. Camera._RIG_MODE_NONE = 0;
  14478. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14479. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14480. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14481. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14482. Camera._RIG_MODE_VR = 20;
  14483. Camera._RIG_MODE_WEBVR = 21;
  14484. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14485. __decorate([
  14486. BABYLON.serializeAsVector3()
  14487. ], Camera.prototype, "position", void 0);
  14488. __decorate([
  14489. BABYLON.serializeAsVector3()
  14490. ], Camera.prototype, "upVector", void 0);
  14491. __decorate([
  14492. BABYLON.serialize()
  14493. ], Camera.prototype, "orthoLeft", void 0);
  14494. __decorate([
  14495. BABYLON.serialize()
  14496. ], Camera.prototype, "orthoRight", void 0);
  14497. __decorate([
  14498. BABYLON.serialize()
  14499. ], Camera.prototype, "orthoBottom", void 0);
  14500. __decorate([
  14501. BABYLON.serialize()
  14502. ], Camera.prototype, "orthoTop", void 0);
  14503. __decorate([
  14504. BABYLON.serialize()
  14505. ], Camera.prototype, "fov", void 0);
  14506. __decorate([
  14507. BABYLON.serialize()
  14508. ], Camera.prototype, "minZ", void 0);
  14509. __decorate([
  14510. BABYLON.serialize()
  14511. ], Camera.prototype, "maxZ", void 0);
  14512. __decorate([
  14513. BABYLON.serialize()
  14514. ], Camera.prototype, "inertia", void 0);
  14515. __decorate([
  14516. BABYLON.serialize()
  14517. ], Camera.prototype, "mode", void 0);
  14518. __decorate([
  14519. BABYLON.serialize()
  14520. ], Camera.prototype, "layerMask", void 0);
  14521. __decorate([
  14522. BABYLON.serialize()
  14523. ], Camera.prototype, "fovMode", void 0);
  14524. __decorate([
  14525. BABYLON.serialize()
  14526. ], Camera.prototype, "cameraRigMode", void 0);
  14527. __decorate([
  14528. BABYLON.serialize()
  14529. ], Camera.prototype, "interaxialDistance", void 0);
  14530. __decorate([
  14531. BABYLON.serialize()
  14532. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14533. BABYLON.Camera = Camera;
  14534. })(BABYLON || (BABYLON = {}));
  14535. //# sourceMappingURL=babylon.camera.js.map
  14536. var BABYLON;
  14537. (function (BABYLON) {
  14538. var RenderingManager = (function () {
  14539. function RenderingManager(scene) {
  14540. this._renderingGroups = new Array();
  14541. this._autoClearDepthStencil = {};
  14542. this._customOpaqueSortCompareFn = {};
  14543. this._customAlphaTestSortCompareFn = {};
  14544. this._customTransparentSortCompareFn = {};
  14545. this._renderinGroupInfo = null;
  14546. this._scene = scene;
  14547. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14548. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14549. }
  14550. }
  14551. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14552. if (depth === void 0) { depth = true; }
  14553. if (stencil === void 0) { stencil = true; }
  14554. if (this._depthStencilBufferAlreadyCleaned) {
  14555. return;
  14556. }
  14557. this._scene.getEngine().clear(null, false, depth, stencil);
  14558. this._depthStencilBufferAlreadyCleaned = true;
  14559. };
  14560. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14561. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14562. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14563. var info = null;
  14564. if (observable) {
  14565. if (!this._renderinGroupInfo) {
  14566. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14567. }
  14568. info = this._renderinGroupInfo;
  14569. info.scene = this._scene;
  14570. info.camera = this._scene.activeCamera;
  14571. }
  14572. // Dispatch sprites
  14573. if (renderSprites) {
  14574. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14575. var manager = this._scene.spriteManagers[index];
  14576. this.dispatchSprites(manager);
  14577. }
  14578. }
  14579. // Render
  14580. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14581. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14582. var renderingGroup = this._renderingGroups[index];
  14583. if (!renderingGroup && !observable)
  14584. continue;
  14585. this._currentIndex = index;
  14586. var renderingGroupMask = 0;
  14587. // Fire PRECLEAR stage
  14588. if (observable) {
  14589. renderingGroupMask = Math.pow(2, index);
  14590. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14591. info.renderingGroupId = index;
  14592. observable.notifyObservers(info, renderingGroupMask);
  14593. }
  14594. // Clear depth/stencil if needed
  14595. if (RenderingManager.AUTOCLEAR) {
  14596. var autoClear = this._autoClearDepthStencil[index];
  14597. if (autoClear && autoClear.autoClear) {
  14598. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14599. }
  14600. }
  14601. if (observable) {
  14602. // Fire PREOPAQUE stage
  14603. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14604. observable.notifyObservers(info, renderingGroupMask);
  14605. // Fire PRETRANSPARENT stage
  14606. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14607. observable.notifyObservers(info, renderingGroupMask);
  14608. }
  14609. if (renderingGroup)
  14610. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14611. // Fire POSTTRANSPARENT stage
  14612. if (observable) {
  14613. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14614. observable.notifyObservers(info, renderingGroupMask);
  14615. }
  14616. }
  14617. };
  14618. RenderingManager.prototype.reset = function () {
  14619. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14620. var renderingGroup = this._renderingGroups[index];
  14621. if (renderingGroup) {
  14622. renderingGroup.prepare();
  14623. }
  14624. }
  14625. };
  14626. RenderingManager.prototype.dispose = function () {
  14627. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14628. var renderingGroup = this._renderingGroups[index];
  14629. if (renderingGroup) {
  14630. renderingGroup.dispose();
  14631. }
  14632. }
  14633. this._renderingGroups.length = 0;
  14634. };
  14635. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14636. if (!this._renderingGroups[renderingGroupId]) {
  14637. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14638. }
  14639. };
  14640. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14641. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14642. this._prepareRenderingGroup(renderingGroupId);
  14643. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14644. };
  14645. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14646. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14647. this._prepareRenderingGroup(renderingGroupId);
  14648. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14649. };
  14650. RenderingManager.prototype.dispatch = function (subMesh) {
  14651. var mesh = subMesh.getMesh();
  14652. var renderingGroupId = mesh.renderingGroupId || 0;
  14653. this._prepareRenderingGroup(renderingGroupId);
  14654. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14655. };
  14656. /**
  14657. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14658. * This allowed control for front to back rendering or reversly depending of the special needs.
  14659. *
  14660. * @param renderingGroupId The rendering group id corresponding to its index
  14661. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14662. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14663. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14664. */
  14665. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14666. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14667. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14668. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14669. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14670. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14671. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14672. if (this._renderingGroups[renderingGroupId]) {
  14673. var group = this._renderingGroups[renderingGroupId];
  14674. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14675. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14676. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14677. }
  14678. };
  14679. /**
  14680. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14681. *
  14682. * @param renderingGroupId The rendering group id corresponding to its index
  14683. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14684. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14685. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14686. */
  14687. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14688. if (depth === void 0) { depth = true; }
  14689. if (stencil === void 0) { stencil = true; }
  14690. this._autoClearDepthStencil[renderingGroupId] = {
  14691. autoClear: autoClearDepthStencil,
  14692. depth: depth,
  14693. stencil: stencil
  14694. };
  14695. };
  14696. return RenderingManager;
  14697. }());
  14698. /**
  14699. * The max id used for rendering groups (not included)
  14700. */
  14701. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14702. /**
  14703. * The min id used for rendering groups (included)
  14704. */
  14705. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14706. /**
  14707. * Used to globally prevent autoclearing scenes.
  14708. */
  14709. RenderingManager.AUTOCLEAR = true;
  14710. BABYLON.RenderingManager = RenderingManager;
  14711. })(BABYLON || (BABYLON = {}));
  14712. //# sourceMappingURL=babylon.renderingManager.js.map
  14713. var BABYLON;
  14714. (function (BABYLON) {
  14715. var RenderingGroup = (function () {
  14716. /**
  14717. * Creates a new rendering group.
  14718. * @param index The rendering group index
  14719. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14720. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14721. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14722. */
  14723. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14724. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14725. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14726. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14727. this.index = index;
  14728. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14729. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14730. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14731. this._particleSystems = new BABYLON.SmartArray(256);
  14732. this._spriteManagers = new BABYLON.SmartArray(256);
  14733. this._edgesRenderers = new BABYLON.SmartArray(16);
  14734. this._scene = scene;
  14735. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14736. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14737. this.transparentSortCompareFn = transparentSortCompareFn;
  14738. }
  14739. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14740. /**
  14741. * Set the opaque sort comparison function.
  14742. * If null the sub meshes will be render in the order they were created
  14743. */
  14744. set: function (value) {
  14745. this._opaqueSortCompareFn = value;
  14746. if (value) {
  14747. this._renderOpaque = this.renderOpaqueSorted;
  14748. }
  14749. else {
  14750. this._renderOpaque = RenderingGroup.renderUnsorted;
  14751. }
  14752. },
  14753. enumerable: true,
  14754. configurable: true
  14755. });
  14756. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14757. /**
  14758. * Set the alpha test sort comparison function.
  14759. * If null the sub meshes will be render in the order they were created
  14760. */
  14761. set: function (value) {
  14762. this._alphaTestSortCompareFn = value;
  14763. if (value) {
  14764. this._renderAlphaTest = this.renderAlphaTestSorted;
  14765. }
  14766. else {
  14767. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14768. }
  14769. },
  14770. enumerable: true,
  14771. configurable: true
  14772. });
  14773. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14774. /**
  14775. * Set the transparent sort comparison function.
  14776. * If null the sub meshes will be render in the order they were created
  14777. */
  14778. set: function (value) {
  14779. if (value) {
  14780. this._transparentSortCompareFn = value;
  14781. }
  14782. else {
  14783. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14784. }
  14785. this._renderTransparent = this.renderTransparentSorted;
  14786. },
  14787. enumerable: true,
  14788. configurable: true
  14789. });
  14790. /**
  14791. * Render all the sub meshes contained in the group.
  14792. * @param customRenderFunction Used to override the default render behaviour of the group.
  14793. * @returns true if rendered some submeshes.
  14794. */
  14795. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14796. if (customRenderFunction) {
  14797. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14798. return;
  14799. }
  14800. var engine = this._scene.getEngine();
  14801. // Opaque
  14802. if (this._opaqueSubMeshes.length !== 0) {
  14803. this._renderOpaque(this._opaqueSubMeshes);
  14804. }
  14805. // Alpha test
  14806. if (this._alphaTestSubMeshes.length !== 0) {
  14807. engine.setAlphaTesting(true);
  14808. this._renderAlphaTest(this._alphaTestSubMeshes);
  14809. engine.setAlphaTesting(false);
  14810. }
  14811. var stencilState = engine.getStencilBuffer();
  14812. engine.setStencilBuffer(false);
  14813. // Sprites
  14814. if (renderSprites) {
  14815. this._renderSprites();
  14816. }
  14817. // Particles
  14818. if (renderParticles) {
  14819. this._renderParticles(activeMeshes);
  14820. }
  14821. if (this.onBeforeTransparentRendering) {
  14822. this.onBeforeTransparentRendering();
  14823. }
  14824. // Transparent
  14825. if (this._transparentSubMeshes.length !== 0) {
  14826. this._renderTransparent(this._transparentSubMeshes);
  14827. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14828. }
  14829. engine.setStencilBuffer(stencilState);
  14830. // Edges
  14831. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14832. this._edgesRenderers.data[edgesRendererIndex].render();
  14833. }
  14834. };
  14835. /**
  14836. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14837. * @param subMeshes The submeshes to render
  14838. */
  14839. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14840. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14841. };
  14842. /**
  14843. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14844. * @param subMeshes The submeshes to render
  14845. */
  14846. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14847. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14848. };
  14849. /**
  14850. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14851. * @param subMeshes The submeshes to render
  14852. */
  14853. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14854. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14855. };
  14856. /**
  14857. * Renders the submeshes in a specified order.
  14858. * @param subMeshes The submeshes to sort before render
  14859. * @param sortCompareFn The comparison function use to sort
  14860. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14861. * @param transparent Specifies to activate blending if true
  14862. */
  14863. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14864. var subIndex = 0;
  14865. var subMesh;
  14866. for (; subIndex < subMeshes.length; subIndex++) {
  14867. subMesh = subMeshes.data[subIndex];
  14868. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14869. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14870. }
  14871. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14872. sortedArray.sort(sortCompareFn);
  14873. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14874. subMesh = sortedArray[subIndex];
  14875. subMesh.render(transparent);
  14876. }
  14877. };
  14878. /**
  14879. * Renders the submeshes in the order they were dispatched (no sort applied).
  14880. * @param subMeshes The submeshes to render
  14881. */
  14882. RenderingGroup.renderUnsorted = function (subMeshes) {
  14883. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14884. var submesh = subMeshes.data[subIndex];
  14885. submesh.render(false);
  14886. }
  14887. };
  14888. /**
  14889. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14890. * are rendered back to front if in the same alpha index.
  14891. *
  14892. * @param a The first submesh
  14893. * @param b The second submesh
  14894. * @returns The result of the comparison
  14895. */
  14896. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14897. // Alpha index first
  14898. if (a._alphaIndex > b._alphaIndex) {
  14899. return 1;
  14900. }
  14901. if (a._alphaIndex < b._alphaIndex) {
  14902. return -1;
  14903. }
  14904. // Then distance to camera
  14905. return RenderingGroup.backToFrontSortCompare(a, b);
  14906. };
  14907. /**
  14908. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14909. * are rendered back to front.
  14910. *
  14911. * @param a The first submesh
  14912. * @param b The second submesh
  14913. * @returns The result of the comparison
  14914. */
  14915. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14916. // Then distance to camera
  14917. if (a._distanceToCamera < b._distanceToCamera) {
  14918. return 1;
  14919. }
  14920. if (a._distanceToCamera > b._distanceToCamera) {
  14921. return -1;
  14922. }
  14923. return 0;
  14924. };
  14925. /**
  14926. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14927. * are rendered front to back (prevent overdraw).
  14928. *
  14929. * @param a The first submesh
  14930. * @param b The second submesh
  14931. * @returns The result of the comparison
  14932. */
  14933. RenderingGroup.frontToBackSortCompare = function (a, b) {
  14934. // Then distance to camera
  14935. if (a._distanceToCamera < b._distanceToCamera) {
  14936. return -1;
  14937. }
  14938. if (a._distanceToCamera > b._distanceToCamera) {
  14939. return 1;
  14940. }
  14941. return 0;
  14942. };
  14943. /**
  14944. * Resets the different lists of submeshes to prepare a new frame.
  14945. */
  14946. RenderingGroup.prototype.prepare = function () {
  14947. this._opaqueSubMeshes.reset();
  14948. this._transparentSubMeshes.reset();
  14949. this._alphaTestSubMeshes.reset();
  14950. this._particleSystems.reset();
  14951. this._spriteManagers.reset();
  14952. this._edgesRenderers.reset();
  14953. };
  14954. RenderingGroup.prototype.dispose = function () {
  14955. this._opaqueSubMeshes.dispose();
  14956. this._transparentSubMeshes.dispose();
  14957. this._alphaTestSubMeshes.dispose();
  14958. this._particleSystems.dispose();
  14959. this._spriteManagers.dispose();
  14960. this._edgesRenderers.dispose();
  14961. };
  14962. /**
  14963. * Inserts the submesh in its correct queue depending on its material.
  14964. * @param subMesh The submesh to dispatch
  14965. */
  14966. RenderingGroup.prototype.dispatch = function (subMesh) {
  14967. var material = subMesh.getMaterial();
  14968. var mesh = subMesh.getMesh();
  14969. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14970. this._transparentSubMeshes.push(subMesh);
  14971. }
  14972. else if (material.needAlphaTesting()) {
  14973. this._alphaTestSubMeshes.push(subMesh);
  14974. }
  14975. else {
  14976. this._opaqueSubMeshes.push(subMesh); // Opaque
  14977. }
  14978. if (mesh._edgesRenderer) {
  14979. this._edgesRenderers.push(mesh._edgesRenderer);
  14980. }
  14981. };
  14982. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  14983. this._spriteManagers.push(spriteManager);
  14984. };
  14985. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  14986. this._particleSystems.push(particleSystem);
  14987. };
  14988. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  14989. if (this._particleSystems.length === 0) {
  14990. return;
  14991. }
  14992. // Particles
  14993. var activeCamera = this._scene.activeCamera;
  14994. this._scene._particlesDuration.beginMonitoring();
  14995. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14996. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14997. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14998. continue;
  14999. }
  15000. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15001. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15002. }
  15003. }
  15004. this._scene._particlesDuration.endMonitoring(false);
  15005. };
  15006. RenderingGroup.prototype._renderSprites = function () {
  15007. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15008. return;
  15009. }
  15010. // Sprites
  15011. var activeCamera = this._scene.activeCamera;
  15012. this._scene._spritesDuration.beginMonitoring();
  15013. for (var id = 0; id < this._spriteManagers.length; id++) {
  15014. var spriteManager = this._spriteManagers.data[id];
  15015. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15016. spriteManager.render();
  15017. }
  15018. }
  15019. this._scene._spritesDuration.endMonitoring(false);
  15020. };
  15021. return RenderingGroup;
  15022. }());
  15023. BABYLON.RenderingGroup = RenderingGroup;
  15024. })(BABYLON || (BABYLON = {}));
  15025. //# sourceMappingURL=babylon.renderingGroup.js.map
  15026. var BABYLON;
  15027. (function (BABYLON) {
  15028. var ClickInfo = (function () {
  15029. function ClickInfo() {
  15030. this._singleClick = false;
  15031. this._doubleClick = false;
  15032. this._hasSwiped = false;
  15033. this._ignore = false;
  15034. }
  15035. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15036. get: function () {
  15037. return this._singleClick;
  15038. },
  15039. set: function (b) {
  15040. this._singleClick = b;
  15041. },
  15042. enumerable: true,
  15043. configurable: true
  15044. });
  15045. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15046. get: function () {
  15047. return this._doubleClick;
  15048. },
  15049. set: function (b) {
  15050. this._doubleClick = b;
  15051. },
  15052. enumerable: true,
  15053. configurable: true
  15054. });
  15055. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15056. get: function () {
  15057. return this._hasSwiped;
  15058. },
  15059. set: function (b) {
  15060. this._hasSwiped = b;
  15061. },
  15062. enumerable: true,
  15063. configurable: true
  15064. });
  15065. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15066. get: function () {
  15067. return this._ignore;
  15068. },
  15069. set: function (b) {
  15070. this._ignore = b;
  15071. },
  15072. enumerable: true,
  15073. configurable: true
  15074. });
  15075. return ClickInfo;
  15076. }());
  15077. var PointerEventTypes = (function () {
  15078. function PointerEventTypes() {
  15079. }
  15080. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15081. get: function () {
  15082. return PointerEventTypes._POINTERDOWN;
  15083. },
  15084. enumerable: true,
  15085. configurable: true
  15086. });
  15087. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15088. get: function () {
  15089. return PointerEventTypes._POINTERUP;
  15090. },
  15091. enumerable: true,
  15092. configurable: true
  15093. });
  15094. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15095. get: function () {
  15096. return PointerEventTypes._POINTERMOVE;
  15097. },
  15098. enumerable: true,
  15099. configurable: true
  15100. });
  15101. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15102. get: function () {
  15103. return PointerEventTypes._POINTERWHEEL;
  15104. },
  15105. enumerable: true,
  15106. configurable: true
  15107. });
  15108. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15109. get: function () {
  15110. return PointerEventTypes._POINTERPICK;
  15111. },
  15112. enumerable: true,
  15113. configurable: true
  15114. });
  15115. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15116. get: function () {
  15117. return PointerEventTypes._POINTERTAP;
  15118. },
  15119. enumerable: true,
  15120. configurable: true
  15121. });
  15122. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15123. get: function () {
  15124. return PointerEventTypes._POINTERDOUBLETAP;
  15125. },
  15126. enumerable: true,
  15127. configurable: true
  15128. });
  15129. return PointerEventTypes;
  15130. }());
  15131. PointerEventTypes._POINTERDOWN = 0x01;
  15132. PointerEventTypes._POINTERUP = 0x02;
  15133. PointerEventTypes._POINTERMOVE = 0x04;
  15134. PointerEventTypes._POINTERWHEEL = 0x08;
  15135. PointerEventTypes._POINTERPICK = 0x10;
  15136. PointerEventTypes._POINTERTAP = 0x20;
  15137. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15138. BABYLON.PointerEventTypes = PointerEventTypes;
  15139. var PointerInfoBase = (function () {
  15140. function PointerInfoBase(type, event) {
  15141. this.type = type;
  15142. this.event = event;
  15143. }
  15144. return PointerInfoBase;
  15145. }());
  15146. BABYLON.PointerInfoBase = PointerInfoBase;
  15147. /**
  15148. * This class is used to store pointer related info for the onPrePointerObservable event.
  15149. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15150. */
  15151. var PointerInfoPre = (function (_super) {
  15152. __extends(PointerInfoPre, _super);
  15153. function PointerInfoPre(type, event, localX, localY) {
  15154. var _this = _super.call(this, type, event) || this;
  15155. _this.skipOnPointerObservable = false;
  15156. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15157. return _this;
  15158. }
  15159. return PointerInfoPre;
  15160. }(PointerInfoBase));
  15161. BABYLON.PointerInfoPre = PointerInfoPre;
  15162. /**
  15163. * This type contains all the data related to a pointer event in Babylon.js.
  15164. * 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.
  15165. */
  15166. var PointerInfo = (function (_super) {
  15167. __extends(PointerInfo, _super);
  15168. function PointerInfo(type, event, pickInfo) {
  15169. var _this = _super.call(this, type, event) || this;
  15170. _this.pickInfo = pickInfo;
  15171. return _this;
  15172. }
  15173. return PointerInfo;
  15174. }(PointerInfoBase));
  15175. BABYLON.PointerInfo = PointerInfo;
  15176. /**
  15177. * This class is used by the onRenderingGroupObservable
  15178. */
  15179. var RenderingGroupInfo = (function () {
  15180. function RenderingGroupInfo() {
  15181. }
  15182. return RenderingGroupInfo;
  15183. }());
  15184. /**
  15185. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15186. * This stage will be fired no matter what
  15187. */
  15188. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15189. /**
  15190. * Called before opaque object are rendered.
  15191. * This stage will be fired only if there's 3D Opaque content to render
  15192. */
  15193. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15194. /**
  15195. * Called after the opaque objects are rendered and before the transparent ones
  15196. * This stage will be fired only if there's 3D transparent content to render
  15197. */
  15198. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15199. /**
  15200. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15201. * This stage will be fired no matter what
  15202. */
  15203. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15204. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15205. /**
  15206. * Represents a scene to be rendered by the engine.
  15207. * @see http://doc.babylonjs.com/page.php?p=21911
  15208. */
  15209. var Scene = (function () {
  15210. /**
  15211. * @constructor
  15212. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15213. */
  15214. function Scene(engine) {
  15215. // Members
  15216. this.autoClear = true;
  15217. this.autoClearDepthAndStencil = true;
  15218. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15219. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15220. this.forceWireframe = false;
  15221. this._forcePointsCloud = false;
  15222. this.forceShowBoundingBoxes = false;
  15223. this.animationsEnabled = true;
  15224. this.constantlyUpdateMeshUnderPointer = false;
  15225. this.hoverCursor = "pointer";
  15226. // Metadata
  15227. this.metadata = null;
  15228. // Events
  15229. /**
  15230. * An event triggered when the scene is disposed.
  15231. * @type {BABYLON.Observable}
  15232. */
  15233. this.onDisposeObservable = new BABYLON.Observable();
  15234. /**
  15235. * An event triggered before rendering the scene
  15236. * @type {BABYLON.Observable}
  15237. */
  15238. this.onBeforeRenderObservable = new BABYLON.Observable();
  15239. /**
  15240. * An event triggered after rendering the scene
  15241. * @type {BABYLON.Observable}
  15242. */
  15243. this.onAfterRenderObservable = new BABYLON.Observable();
  15244. /**
  15245. * An event triggered when the scene is ready
  15246. * @type {BABYLON.Observable}
  15247. */
  15248. this.onReadyObservable = new BABYLON.Observable();
  15249. /**
  15250. * An event triggered before rendering a camera
  15251. * @type {BABYLON.Observable}
  15252. */
  15253. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15254. /**
  15255. * An event triggered after rendering a camera
  15256. * @type {BABYLON.Observable}
  15257. */
  15258. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15259. /**
  15260. * An event triggered when a camera is created
  15261. * @type {BABYLON.Observable}
  15262. */
  15263. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15264. /**
  15265. * An event triggered when a camera is removed
  15266. * @type {BABYLON.Observable}
  15267. */
  15268. this.onCameraRemovedObservable = new BABYLON.Observable();
  15269. /**
  15270. * An event triggered when a light is created
  15271. * @type {BABYLON.Observable}
  15272. */
  15273. this.onNewLightAddedObservable = new BABYLON.Observable();
  15274. /**
  15275. * An event triggered when a light is removed
  15276. * @type {BABYLON.Observable}
  15277. */
  15278. this.onLightRemovedObservable = new BABYLON.Observable();
  15279. /**
  15280. * An event triggered when a geometry is created
  15281. * @type {BABYLON.Observable}
  15282. */
  15283. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15284. /**
  15285. * An event triggered when a geometry is removed
  15286. * @type {BABYLON.Observable}
  15287. */
  15288. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15289. /**
  15290. * An event triggered when a mesh is created
  15291. * @type {BABYLON.Observable}
  15292. */
  15293. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15294. /**
  15295. * An event triggered when a mesh is removed
  15296. * @type {BABYLON.Observable}
  15297. */
  15298. this.onMeshRemovedObservable = new BABYLON.Observable();
  15299. /**
  15300. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15301. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15302. * 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)
  15303. */
  15304. this.onRenderingGroupObservable = new BABYLON.Observable();
  15305. // Animations
  15306. this.animations = [];
  15307. /**
  15308. * 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).
  15309. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15310. */
  15311. this.onPrePointerObservable = new BABYLON.Observable();
  15312. /**
  15313. * Observable event triggered each time an input event is received from the rendering canvas
  15314. */
  15315. this.onPointerObservable = new BABYLON.Observable();
  15316. this._meshPickProceed = false;
  15317. this._previousHasSwiped = false;
  15318. this._currentPickResult = null;
  15319. this._previousPickResult = null;
  15320. this._isButtonPressed = false;
  15321. this._doubleClickOccured = false;
  15322. 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
  15323. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15324. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15325. this._startingPointerTime = 0;
  15326. this._previousStartingPointerTime = 0;
  15327. // Coordinate system
  15328. /**
  15329. * use right-handed coordinate system on this scene.
  15330. * @type {boolean}
  15331. */
  15332. this._useRightHandedSystem = false;
  15333. // Fog
  15334. /**
  15335. * is fog enabled on this scene.
  15336. * @type {boolean}
  15337. */
  15338. this._fogEnabled = true;
  15339. this._fogMode = Scene.FOGMODE_NONE;
  15340. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15341. this.fogDensity = 0.1;
  15342. this.fogStart = 0;
  15343. this.fogEnd = 1000.0;
  15344. // Lights
  15345. /**
  15346. * is shadow enabled on this scene.
  15347. * @type {boolean}
  15348. */
  15349. this._shadowsEnabled = true;
  15350. /**
  15351. * is light enabled on this scene.
  15352. * @type {boolean}
  15353. */
  15354. this._lightsEnabled = true;
  15355. /**
  15356. * All of the lights added to this scene.
  15357. * @see BABYLON.Light
  15358. * @type {BABYLON.Light[]}
  15359. */
  15360. this.lights = new Array();
  15361. // Cameras
  15362. /**
  15363. * All of the cameras added to this scene.
  15364. * @see BABYLON.Camera
  15365. * @type {BABYLON.Camera[]}
  15366. */
  15367. this.cameras = new Array();
  15368. this.activeCameras = new Array();
  15369. // Meshes
  15370. /**
  15371. * All of the (abstract) meshes added to this scene.
  15372. * @see BABYLON.AbstractMesh
  15373. * @type {BABYLON.AbstractMesh[]}
  15374. */
  15375. this.meshes = new Array();
  15376. // Geometries
  15377. this._geometries = new Array();
  15378. this.materials = new Array();
  15379. this.multiMaterials = new Array();
  15380. // Textures
  15381. this._texturesEnabled = true;
  15382. this.textures = new Array();
  15383. // Particles
  15384. this.particlesEnabled = true;
  15385. this.particleSystems = new Array();
  15386. // Sprites
  15387. this.spritesEnabled = true;
  15388. this.spriteManagers = new Array();
  15389. // Layers
  15390. this.layers = new Array();
  15391. this.highlightLayers = new Array();
  15392. // Skeletons
  15393. this._skeletonsEnabled = true;
  15394. this.skeletons = new Array();
  15395. // Morph targets
  15396. this.morphTargetManagers = new Array();
  15397. // Lens flares
  15398. this.lensFlaresEnabled = true;
  15399. this.lensFlareSystems = new Array();
  15400. // Collisions
  15401. this.collisionsEnabled = true;
  15402. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15403. // Postprocesses
  15404. this.postProcessesEnabled = true;
  15405. // Customs render targets
  15406. this.renderTargetsEnabled = true;
  15407. this.dumpNextRenderTargets = false;
  15408. this.customRenderTargets = new Array();
  15409. // Imported meshes
  15410. this.importedMeshesFiles = new Array();
  15411. // Probes
  15412. this.probesEnabled = true;
  15413. this.reflectionProbes = new Array();
  15414. this._actionManagers = new Array();
  15415. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15416. // Procedural textures
  15417. this.proceduralTexturesEnabled = true;
  15418. this._proceduralTextures = new Array();
  15419. this.soundTracks = new Array();
  15420. this._audioEnabled = true;
  15421. this._headphone = false;
  15422. // Performance counters
  15423. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15424. this._totalLightsCounter = new BABYLON.PerfCounter();
  15425. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15426. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15427. this._totalVertices = new BABYLON.PerfCounter();
  15428. this._activeIndices = new BABYLON.PerfCounter();
  15429. this._activeParticles = new BABYLON.PerfCounter();
  15430. this._lastFrameDuration = new BABYLON.PerfCounter();
  15431. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15432. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15433. this._particlesDuration = new BABYLON.PerfCounter();
  15434. this._renderDuration = new BABYLON.PerfCounter();
  15435. this._spritesDuration = new BABYLON.PerfCounter();
  15436. this._activeBones = new BABYLON.PerfCounter();
  15437. this._animationTime = 0;
  15438. this.animationTimeScale = 1;
  15439. this._renderId = 0;
  15440. this._executeWhenReadyTimeoutId = -1;
  15441. this._intermediateRendering = false;
  15442. this._viewUpdateFlag = -1;
  15443. this._projectionUpdateFlag = -1;
  15444. this._toBeDisposed = new BABYLON.SmartArray(256);
  15445. this._pendingData = []; //ANY
  15446. this._activeMeshes = new BABYLON.SmartArray(256);
  15447. this._processedMaterials = new BABYLON.SmartArray(256);
  15448. this._renderTargets = new BABYLON.SmartArray(256);
  15449. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15450. this._activeSkeletons = new BABYLON.SmartArray(32);
  15451. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15452. this._activeAnimatables = new Array();
  15453. this._transformMatrix = BABYLON.Matrix.Zero();
  15454. this.requireLightSorting = false;
  15455. this._uniqueIdCounter = 0;
  15456. this.offscreenRenderTarget = null;
  15457. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15458. this._engine.scenes.push(this);
  15459. this._uid = null;
  15460. this._renderingManager = new BABYLON.RenderingManager(this);
  15461. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15462. if (BABYLON.OutlineRenderer) {
  15463. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15464. }
  15465. this.attachControl();
  15466. if (BABYLON.SoundTrack) {
  15467. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15468. }
  15469. //simplification queue
  15470. if (BABYLON.SimplificationQueue) {
  15471. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15472. }
  15473. //collision coordinator initialization. For now legacy per default.
  15474. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15475. // Uniform Buffer
  15476. this._createUbo();
  15477. }
  15478. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15479. get: function () {
  15480. return Scene._FOGMODE_NONE;
  15481. },
  15482. enumerable: true,
  15483. configurable: true
  15484. });
  15485. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15486. get: function () {
  15487. return Scene._FOGMODE_EXP;
  15488. },
  15489. enumerable: true,
  15490. configurable: true
  15491. });
  15492. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15493. get: function () {
  15494. return Scene._FOGMODE_EXP2;
  15495. },
  15496. enumerable: true,
  15497. configurable: true
  15498. });
  15499. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15500. get: function () {
  15501. return Scene._FOGMODE_LINEAR;
  15502. },
  15503. enumerable: true,
  15504. configurable: true
  15505. });
  15506. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15507. /**
  15508. * Texture used in all pbr material as the reflection texture.
  15509. * As in the majority of the scene they are the same (exception for multi room and so on),
  15510. * this is easier to reference from here than from all the materials.
  15511. */
  15512. get: function () {
  15513. return this._environmentTexture;
  15514. },
  15515. /**
  15516. * Texture used in all pbr material as the reflection texture.
  15517. * As in the majority of the scene they are the same (exception for multi room and so on),
  15518. * this is easier to set here than in all the materials.
  15519. */
  15520. set: function (value) {
  15521. this._environmentTexture = value;
  15522. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15523. },
  15524. enumerable: true,
  15525. configurable: true
  15526. });
  15527. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15528. get: function () {
  15529. return this._forcePointsCloud;
  15530. },
  15531. set: function (value) {
  15532. if (this._forcePointsCloud === value) {
  15533. return;
  15534. }
  15535. this._forcePointsCloud = value;
  15536. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15537. },
  15538. enumerable: true,
  15539. configurable: true
  15540. });
  15541. Object.defineProperty(Scene.prototype, "onDispose", {
  15542. set: function (callback) {
  15543. if (this._onDisposeObserver) {
  15544. this.onDisposeObservable.remove(this._onDisposeObserver);
  15545. }
  15546. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15547. },
  15548. enumerable: true,
  15549. configurable: true
  15550. });
  15551. Object.defineProperty(Scene.prototype, "beforeRender", {
  15552. set: function (callback) {
  15553. if (this._onBeforeRenderObserver) {
  15554. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15555. }
  15556. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15557. },
  15558. enumerable: true,
  15559. configurable: true
  15560. });
  15561. Object.defineProperty(Scene.prototype, "afterRender", {
  15562. set: function (callback) {
  15563. if (this._onAfterRenderObserver) {
  15564. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15565. }
  15566. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15567. },
  15568. enumerable: true,
  15569. configurable: true
  15570. });
  15571. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15572. set: function (callback) {
  15573. if (this._onBeforeCameraRenderObserver) {
  15574. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15575. }
  15576. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15577. },
  15578. enumerable: true,
  15579. configurable: true
  15580. });
  15581. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15582. set: function (callback) {
  15583. if (this._onAfterCameraRenderObserver) {
  15584. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15585. }
  15586. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15587. },
  15588. enumerable: true,
  15589. configurable: true
  15590. });
  15591. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15592. get: function () {
  15593. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15594. },
  15595. enumerable: true,
  15596. configurable: true
  15597. });
  15598. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15599. get: function () {
  15600. return this._useRightHandedSystem;
  15601. },
  15602. set: function (value) {
  15603. if (this._useRightHandedSystem === value) {
  15604. return;
  15605. }
  15606. this._useRightHandedSystem = value;
  15607. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15608. },
  15609. enumerable: true,
  15610. configurable: true
  15611. });
  15612. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15613. get: function () {
  15614. return this._fogEnabled;
  15615. },
  15616. set: function (value) {
  15617. if (this._fogEnabled === value) {
  15618. return;
  15619. }
  15620. this._fogEnabled = value;
  15621. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15622. },
  15623. enumerable: true,
  15624. configurable: true
  15625. });
  15626. Object.defineProperty(Scene.prototype, "fogMode", {
  15627. get: function () {
  15628. return this._fogMode;
  15629. },
  15630. set: function (value) {
  15631. if (this._fogMode === value) {
  15632. return;
  15633. }
  15634. this._fogMode = value;
  15635. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15636. },
  15637. enumerable: true,
  15638. configurable: true
  15639. });
  15640. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15641. get: function () {
  15642. return this._shadowsEnabled;
  15643. },
  15644. set: function (value) {
  15645. if (this._shadowsEnabled === value) {
  15646. return;
  15647. }
  15648. this._shadowsEnabled = value;
  15649. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15650. },
  15651. enumerable: true,
  15652. configurable: true
  15653. });
  15654. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15655. get: function () {
  15656. return this._lightsEnabled;
  15657. },
  15658. set: function (value) {
  15659. if (this._lightsEnabled === value) {
  15660. return;
  15661. }
  15662. this._lightsEnabled = value;
  15663. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15664. },
  15665. enumerable: true,
  15666. configurable: true
  15667. });
  15668. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15669. get: function () {
  15670. if (!this._defaultMaterial) {
  15671. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15672. }
  15673. return this._defaultMaterial;
  15674. },
  15675. set: function (value) {
  15676. this._defaultMaterial = value;
  15677. },
  15678. enumerable: true,
  15679. configurable: true
  15680. });
  15681. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15682. get: function () {
  15683. return this._texturesEnabled;
  15684. },
  15685. set: function (value) {
  15686. if (this._texturesEnabled === value) {
  15687. return;
  15688. }
  15689. this._texturesEnabled = value;
  15690. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15696. get: function () {
  15697. return this._skeletonsEnabled;
  15698. },
  15699. set: function (value) {
  15700. if (this._skeletonsEnabled === value) {
  15701. return;
  15702. }
  15703. this._skeletonsEnabled = value;
  15704. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15710. get: function () {
  15711. if (!this._postProcessRenderPipelineManager) {
  15712. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15713. }
  15714. return this._postProcessRenderPipelineManager;
  15715. },
  15716. enumerable: true,
  15717. configurable: true
  15718. });
  15719. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15720. get: function () {
  15721. return this._frustumPlanes;
  15722. },
  15723. enumerable: true,
  15724. configurable: true
  15725. });
  15726. Object.defineProperty(Scene.prototype, "debugLayer", {
  15727. // Properties
  15728. get: function () {
  15729. if (!this._debugLayer) {
  15730. this._debugLayer = new BABYLON.DebugLayer(this);
  15731. }
  15732. return this._debugLayer;
  15733. },
  15734. enumerable: true,
  15735. configurable: true
  15736. });
  15737. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15738. get: function () {
  15739. return this._workerCollisions;
  15740. },
  15741. set: function (enabled) {
  15742. if (!BABYLON.CollisionCoordinatorLegacy) {
  15743. return;
  15744. }
  15745. enabled = (enabled && !!Worker);
  15746. this._workerCollisions = enabled;
  15747. if (this.collisionCoordinator) {
  15748. this.collisionCoordinator.destroy();
  15749. }
  15750. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15751. this.collisionCoordinator.init(this);
  15752. },
  15753. enumerable: true,
  15754. configurable: true
  15755. });
  15756. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15757. get: function () {
  15758. return this._selectionOctree;
  15759. },
  15760. enumerable: true,
  15761. configurable: true
  15762. });
  15763. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15764. /**
  15765. * The mesh that is currently under the pointer.
  15766. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15767. */
  15768. get: function () {
  15769. return this._pointerOverMesh;
  15770. },
  15771. enumerable: true,
  15772. configurable: true
  15773. });
  15774. Object.defineProperty(Scene.prototype, "pointerX", {
  15775. /**
  15776. * Current on-screen X position of the pointer
  15777. * @return {number} X position of the pointer
  15778. */
  15779. get: function () {
  15780. return this._pointerX;
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(Scene.prototype, "pointerY", {
  15786. /**
  15787. * Current on-screen Y position of the pointer
  15788. * @return {number} Y position of the pointer
  15789. */
  15790. get: function () {
  15791. return this._pointerY;
  15792. },
  15793. enumerable: true,
  15794. configurable: true
  15795. });
  15796. Scene.prototype.getCachedMaterial = function () {
  15797. return this._cachedMaterial;
  15798. };
  15799. Scene.prototype.getCachedEffect = function () {
  15800. return this._cachedEffect;
  15801. };
  15802. Scene.prototype.getCachedVisibility = function () {
  15803. return this._cachedVisibility;
  15804. };
  15805. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15806. if (visibility === void 0) { visibility = 0; }
  15807. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15808. };
  15809. Scene.prototype.getBoundingBoxRenderer = function () {
  15810. if (!this._boundingBoxRenderer) {
  15811. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15812. }
  15813. return this._boundingBoxRenderer;
  15814. };
  15815. Scene.prototype.getOutlineRenderer = function () {
  15816. return this._outlineRenderer;
  15817. };
  15818. Scene.prototype.getEngine = function () {
  15819. return this._engine;
  15820. };
  15821. Scene.prototype.getTotalVertices = function () {
  15822. return this._totalVertices.current;
  15823. };
  15824. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15825. get: function () {
  15826. return this._totalVertices;
  15827. },
  15828. enumerable: true,
  15829. configurable: true
  15830. });
  15831. Scene.prototype.getActiveIndices = function () {
  15832. return this._activeIndices.current;
  15833. };
  15834. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15835. get: function () {
  15836. return this._activeIndices;
  15837. },
  15838. enumerable: true,
  15839. configurable: true
  15840. });
  15841. Scene.prototype.getActiveParticles = function () {
  15842. return this._activeParticles.current;
  15843. };
  15844. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15845. get: function () {
  15846. return this._activeParticles;
  15847. },
  15848. enumerable: true,
  15849. configurable: true
  15850. });
  15851. Scene.prototype.getActiveBones = function () {
  15852. return this._activeBones.current;
  15853. };
  15854. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15855. get: function () {
  15856. return this._activeBones;
  15857. },
  15858. enumerable: true,
  15859. configurable: true
  15860. });
  15861. // Stats
  15862. Scene.prototype.getLastFrameDuration = function () {
  15863. return this._lastFrameDuration.current;
  15864. };
  15865. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15866. get: function () {
  15867. return this._lastFrameDuration;
  15868. },
  15869. enumerable: true,
  15870. configurable: true
  15871. });
  15872. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15873. return this._evaluateActiveMeshesDuration.current;
  15874. };
  15875. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15876. get: function () {
  15877. return this._evaluateActiveMeshesDuration;
  15878. },
  15879. enumerable: true,
  15880. configurable: true
  15881. });
  15882. Scene.prototype.getActiveMeshes = function () {
  15883. return this._activeMeshes;
  15884. };
  15885. Scene.prototype.getRenderTargetsDuration = function () {
  15886. return this._renderTargetsDuration.current;
  15887. };
  15888. Scene.prototype.getRenderDuration = function () {
  15889. return this._renderDuration.current;
  15890. };
  15891. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15892. get: function () {
  15893. return this._renderDuration;
  15894. },
  15895. enumerable: true,
  15896. configurable: true
  15897. });
  15898. Scene.prototype.getParticlesDuration = function () {
  15899. return this._particlesDuration.current;
  15900. };
  15901. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15902. get: function () {
  15903. return this._particlesDuration;
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. Scene.prototype.getSpritesDuration = function () {
  15909. return this._spritesDuration.current;
  15910. };
  15911. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15912. get: function () {
  15913. return this._spritesDuration;
  15914. },
  15915. enumerable: true,
  15916. configurable: true
  15917. });
  15918. Scene.prototype.getAnimationRatio = function () {
  15919. return this._animationRatio;
  15920. };
  15921. Scene.prototype.getRenderId = function () {
  15922. return this._renderId;
  15923. };
  15924. Scene.prototype.incrementRenderId = function () {
  15925. this._renderId++;
  15926. };
  15927. Scene.prototype._updatePointerPosition = function (evt) {
  15928. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15929. this._pointerX = evt.clientX - canvasRect.left;
  15930. this._pointerY = evt.clientY - canvasRect.top;
  15931. this._unTranslatedPointerX = this._pointerX;
  15932. this._unTranslatedPointerY = this._pointerY;
  15933. if (this.cameraToUseForPointers) {
  15934. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15935. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15936. }
  15937. };
  15938. Scene.prototype._createUbo = function () {
  15939. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  15940. this._sceneUbo.addUniform("viewProjection", 16);
  15941. this._sceneUbo.addUniform("view", 16);
  15942. };
  15943. // Pointers handling
  15944. /**
  15945. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15946. * @param attachUp defines if you want to attach events to pointerup
  15947. * @param attachDown defines if you want to attach events to pointerdown
  15948. * @param attachMove defines if you want to attach events to pointermove
  15949. */
  15950. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15951. var _this = this;
  15952. if (attachUp === void 0) { attachUp = true; }
  15953. if (attachDown === void 0) { attachDown = true; }
  15954. if (attachMove === void 0) { attachMove = true; }
  15955. this._initActionManager = function (act, clickInfo) {
  15956. if (!_this._meshPickProceed) {
  15957. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15958. _this._currentPickResult = pickResult;
  15959. if (pickResult) {
  15960. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  15961. }
  15962. _this._meshPickProceed = true;
  15963. }
  15964. return act;
  15965. };
  15966. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  15967. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  15968. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  15969. btn !== _this._previousButtonPressed) {
  15970. _this._doubleClickOccured = false;
  15971. clickInfo.singleClick = true;
  15972. clickInfo.ignore = false;
  15973. cb(clickInfo, _this._currentPickResult);
  15974. }
  15975. };
  15976. this._initClickEvent = function (obs1, obs2, evt, cb) {
  15977. var clickInfo = new ClickInfo();
  15978. _this._currentPickResult = null;
  15979. var act;
  15980. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  15981. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  15982. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15983. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  15984. act = _this._initActionManager(act, clickInfo);
  15985. if (act)
  15986. checkPicking = act.hasPickTriggers;
  15987. }
  15988. if (checkPicking) {
  15989. var btn = evt.button;
  15990. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  15991. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  15992. if (!clickInfo.hasSwiped) {
  15993. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  15994. if (!checkSingleClickImmediately) {
  15995. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  15996. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15997. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15998. act = _this._initActionManager(act, clickInfo);
  15999. if (act)
  16000. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16001. }
  16002. }
  16003. if (checkSingleClickImmediately) {
  16004. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16005. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16006. btn !== _this._previousButtonPressed) {
  16007. clickInfo.singleClick = true;
  16008. cb(clickInfo, _this._currentPickResult);
  16009. }
  16010. }
  16011. else {
  16012. // wait that no double click has been raised during the double click delay
  16013. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16014. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16015. }
  16016. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16017. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16018. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16019. act = _this._initActionManager(act, clickInfo);
  16020. if (act)
  16021. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16022. }
  16023. if (checkDoubleClick) {
  16024. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16025. if (btn === _this._previousButtonPressed &&
  16026. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16027. !_this._doubleClickOccured) {
  16028. // pointer has not moved for 2 clicks, it's a double click
  16029. if (!clickInfo.hasSwiped &&
  16030. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16031. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16032. _this._previousStartingPointerTime = 0;
  16033. _this._doubleClickOccured = true;
  16034. clickInfo.doubleClick = true;
  16035. clickInfo.ignore = false;
  16036. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16037. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16038. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16039. cb(clickInfo, _this._currentPickResult);
  16040. }
  16041. else {
  16042. _this._doubleClickOccured = false;
  16043. _this._previousStartingPointerTime = _this._startingPointerTime;
  16044. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16045. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16046. _this._previousButtonPressed = btn;
  16047. _this._previousHasSwiped = clickInfo.hasSwiped;
  16048. if (Scene.ExclusiveDoubleClickMode) {
  16049. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16050. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16051. }
  16052. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16053. cb(clickInfo, _this._previousPickResult);
  16054. }
  16055. else {
  16056. cb(clickInfo, _this._currentPickResult);
  16057. }
  16058. }
  16059. }
  16060. else {
  16061. _this._doubleClickOccured = false;
  16062. _this._previousStartingPointerTime = _this._startingPointerTime;
  16063. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16064. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16065. _this._previousButtonPressed = btn;
  16066. _this._previousHasSwiped = clickInfo.hasSwiped;
  16067. }
  16068. }
  16069. }
  16070. }
  16071. clickInfo.ignore = true;
  16072. cb(clickInfo, _this._currentPickResult);
  16073. };
  16074. var spritePredicate = function (sprite) {
  16075. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16076. };
  16077. this._onPointerMove = function (evt) {
  16078. _this._updatePointerPosition(evt);
  16079. // PreObservable support
  16080. if (_this.onPrePointerObservable.hasObservers()) {
  16081. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16082. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16083. _this.onPrePointerObservable.notifyObservers(pi, type);
  16084. if (pi.skipOnPointerObservable) {
  16085. return;
  16086. }
  16087. }
  16088. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16089. return;
  16090. }
  16091. var canvas = _this._engine.getRenderingCanvas();
  16092. if (!_this.pointerMovePredicate) {
  16093. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16094. }
  16095. // Meshes
  16096. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16097. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16098. _this.setPointerOverSprite(null);
  16099. _this.setPointerOverMesh(pickResult.pickedMesh);
  16100. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16101. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16102. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16103. }
  16104. else {
  16105. canvas.style.cursor = _this.hoverCursor;
  16106. }
  16107. }
  16108. else {
  16109. canvas.style.cursor = "";
  16110. }
  16111. }
  16112. else {
  16113. _this.setPointerOverMesh(null);
  16114. // Sprites
  16115. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16116. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16117. _this.setPointerOverSprite(pickResult.pickedSprite);
  16118. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16119. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16120. }
  16121. else {
  16122. canvas.style.cursor = _this.hoverCursor;
  16123. }
  16124. }
  16125. else {
  16126. _this.setPointerOverSprite(null);
  16127. // Restore pointer
  16128. canvas.style.cursor = "";
  16129. }
  16130. }
  16131. if (_this.onPointerMove) {
  16132. _this.onPointerMove(evt, pickResult);
  16133. }
  16134. if (_this.onPointerObservable.hasObservers()) {
  16135. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16136. var pi = new PointerInfo(type, evt, pickResult);
  16137. _this.onPointerObservable.notifyObservers(pi, type);
  16138. }
  16139. };
  16140. this._onPointerDown = function (evt) {
  16141. _this._isButtonPressed = true;
  16142. _this._pickedDownMesh = null;
  16143. _this._meshPickProceed = false;
  16144. _this._updatePointerPosition(evt);
  16145. // PreObservable support
  16146. if (_this.onPrePointerObservable.hasObservers()) {
  16147. var type = PointerEventTypes.POINTERDOWN;
  16148. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16149. _this.onPrePointerObservable.notifyObservers(pi, type);
  16150. if (pi.skipOnPointerObservable) {
  16151. return;
  16152. }
  16153. }
  16154. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16155. return;
  16156. }
  16157. _this._startingPointerPosition.x = _this._pointerX;
  16158. _this._startingPointerPosition.y = _this._pointerY;
  16159. _this._startingPointerTime = new Date().getTime();
  16160. if (!_this.pointerDownPredicate) {
  16161. _this.pointerDownPredicate = function (mesh) {
  16162. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16163. };
  16164. }
  16165. // Meshes
  16166. _this._pickedDownMesh = null;
  16167. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16168. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16169. _this._pickedDownMesh = pickResult.pickedMesh;
  16170. var actionManager = pickResult.pickedMesh.actionManager;
  16171. if (actionManager) {
  16172. if (actionManager.hasPickTriggers) {
  16173. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16174. switch (evt.button) {
  16175. case 0:
  16176. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16177. break;
  16178. case 1:
  16179. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16180. break;
  16181. case 2:
  16182. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16183. break;
  16184. }
  16185. }
  16186. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16187. window.setTimeout((function () {
  16188. var _this = this;
  16189. 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);
  16190. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16191. if (this._isButtonPressed &&
  16192. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16193. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16194. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16195. this._startingPointerTime = 0;
  16196. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16197. }
  16198. }
  16199. }).bind(_this), Scene.LongPressDelay);
  16200. }
  16201. }
  16202. }
  16203. if (_this.onPointerDown) {
  16204. _this.onPointerDown(evt, pickResult);
  16205. }
  16206. if (_this.onPointerObservable.hasObservers()) {
  16207. var type = PointerEventTypes.POINTERDOWN;
  16208. var pi = new PointerInfo(type, evt, pickResult);
  16209. _this.onPointerObservable.notifyObservers(pi, type);
  16210. }
  16211. // Sprites
  16212. _this._pickedDownSprite = null;
  16213. if (_this.spriteManagers.length > 0) {
  16214. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16215. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16216. if (pickResult.pickedSprite.actionManager) {
  16217. _this._pickedDownSprite = pickResult.pickedSprite;
  16218. switch (evt.button) {
  16219. case 0:
  16220. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16221. break;
  16222. case 1:
  16223. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16224. break;
  16225. case 2:
  16226. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16227. break;
  16228. }
  16229. if (pickResult.pickedSprite.actionManager) {
  16230. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16231. }
  16232. }
  16233. }
  16234. }
  16235. };
  16236. this._onPointerUp = function (evt) {
  16237. _this._isButtonPressed = false;
  16238. _this._pickedUpMesh = null;
  16239. _this._meshPickProceed = false;
  16240. _this._updatePointerPosition(evt);
  16241. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16242. // PreObservable support
  16243. if (this.onPrePointerObservable.hasObservers()) {
  16244. if (!clickInfo.ignore) {
  16245. if (!clickInfo.hasSwiped) {
  16246. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16247. var type = PointerEventTypes.POINTERTAP;
  16248. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16249. this.onPrePointerObservable.notifyObservers(pi, type);
  16250. if (pi.skipOnPointerObservable) {
  16251. return;
  16252. }
  16253. }
  16254. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16255. var type = PointerEventTypes.POINTERDOUBLETAP;
  16256. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16257. this.onPrePointerObservable.notifyObservers(pi, type);
  16258. if (pi.skipOnPointerObservable) {
  16259. return;
  16260. }
  16261. }
  16262. }
  16263. }
  16264. else {
  16265. var type = PointerEventTypes.POINTERUP;
  16266. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16267. this.onPrePointerObservable.notifyObservers(pi, type);
  16268. if (pi.skipOnPointerObservable) {
  16269. return;
  16270. }
  16271. }
  16272. }
  16273. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16274. return;
  16275. }
  16276. if (!this.pointerUpPredicate) {
  16277. this.pointerUpPredicate = function (mesh) {
  16278. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16279. };
  16280. }
  16281. // Meshes
  16282. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16283. this._initActionManager(null, clickInfo);
  16284. }
  16285. if (!pickResult) {
  16286. pickResult = this._currentPickResult;
  16287. }
  16288. if (pickResult && pickResult && pickResult.pickedMesh) {
  16289. this._pickedUpMesh = pickResult.pickedMesh;
  16290. if (this._pickedDownMesh === this._pickedUpMesh) {
  16291. if (this.onPointerPick) {
  16292. this.onPointerPick(evt, pickResult);
  16293. }
  16294. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16295. var type = PointerEventTypes.POINTERPICK;
  16296. var pi = new PointerInfo(type, evt, pickResult);
  16297. this.onPointerObservable.notifyObservers(pi, type);
  16298. }
  16299. }
  16300. if (pickResult.pickedMesh.actionManager) {
  16301. if (clickInfo.ignore) {
  16302. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16303. }
  16304. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16305. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16306. }
  16307. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16308. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16309. }
  16310. }
  16311. }
  16312. if (this._pickedDownMesh &&
  16313. this._pickedDownMesh.actionManager &&
  16314. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16315. this._pickedDownMesh !== this._pickedUpMesh) {
  16316. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16317. }
  16318. if (this.onPointerUp) {
  16319. this.onPointerUp(evt, pickResult);
  16320. }
  16321. if (this.onPointerObservable.hasObservers()) {
  16322. if (!clickInfo.ignore) {
  16323. if (!clickInfo.hasSwiped) {
  16324. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16325. var type = PointerEventTypes.POINTERTAP;
  16326. var pi = new PointerInfo(type, evt, pickResult);
  16327. this.onPointerObservable.notifyObservers(pi, type);
  16328. }
  16329. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16330. var type = PointerEventTypes.POINTERDOUBLETAP;
  16331. var pi = new PointerInfo(type, evt, pickResult);
  16332. this.onPointerObservable.notifyObservers(pi, type);
  16333. }
  16334. }
  16335. }
  16336. else {
  16337. var type = PointerEventTypes.POINTERUP;
  16338. var pi = new PointerInfo(type, evt, pickResult);
  16339. this.onPointerObservable.notifyObservers(pi, type);
  16340. }
  16341. }
  16342. // Sprites
  16343. if (this.spriteManagers.length > 0) {
  16344. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16345. if (pickResult.hit && pickResult.pickedSprite) {
  16346. if (pickResult.pickedSprite.actionManager) {
  16347. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16348. if (pickResult.pickedSprite.actionManager) {
  16349. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16350. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16351. }
  16352. }
  16353. }
  16354. }
  16355. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16356. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16357. }
  16358. }
  16359. this._previousPickResult = this._currentPickResult;
  16360. }).bind(_this));
  16361. };
  16362. this._onKeyDown = function (evt) {
  16363. if (_this.actionManager) {
  16364. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16365. }
  16366. };
  16367. this._onKeyUp = function (evt) {
  16368. if (_this.actionManager) {
  16369. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16370. }
  16371. };
  16372. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16373. var canvas = this._engine.getRenderingCanvas();
  16374. if (attachMove) {
  16375. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16376. // Wheel
  16377. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16378. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16379. }
  16380. if (attachDown) {
  16381. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16382. }
  16383. if (attachUp) {
  16384. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16385. }
  16386. canvas.tabIndex = 1;
  16387. canvas.addEventListener("keydown", this._onKeyDown, false);
  16388. canvas.addEventListener("keyup", this._onKeyUp, false);
  16389. };
  16390. Scene.prototype.detachControl = function () {
  16391. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16392. var canvas = this._engine.getRenderingCanvas();
  16393. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16394. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16395. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16396. // Wheel
  16397. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16398. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16399. canvas.removeEventListener("keydown", this._onKeyDown);
  16400. canvas.removeEventListener("keyup", this._onKeyUp);
  16401. };
  16402. // Ready
  16403. Scene.prototype.isReady = function () {
  16404. if (this._pendingData.length > 0) {
  16405. return false;
  16406. }
  16407. var index;
  16408. // Geometries
  16409. for (index = 0; index < this._geometries.length; index++) {
  16410. var geometry = this._geometries[index];
  16411. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16412. return false;
  16413. }
  16414. }
  16415. // Meshes
  16416. for (index = 0; index < this.meshes.length; index++) {
  16417. var mesh = this.meshes[index];
  16418. if (!mesh.isEnabled()) {
  16419. continue;
  16420. }
  16421. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16422. continue;
  16423. }
  16424. if (!mesh.isReady()) {
  16425. return false;
  16426. }
  16427. var mat = mesh.material;
  16428. if (mat) {
  16429. if (!mat.isReady(mesh)) {
  16430. return false;
  16431. }
  16432. }
  16433. }
  16434. return true;
  16435. };
  16436. Scene.prototype.resetCachedMaterial = function () {
  16437. this._cachedMaterial = null;
  16438. this._cachedEffect = null;
  16439. this._cachedVisibility = null;
  16440. };
  16441. Scene.prototype.registerBeforeRender = function (func) {
  16442. this.onBeforeRenderObservable.add(func);
  16443. };
  16444. Scene.prototype.unregisterBeforeRender = function (func) {
  16445. this.onBeforeRenderObservable.removeCallback(func);
  16446. };
  16447. Scene.prototype.registerAfterRender = function (func) {
  16448. this.onAfterRenderObservable.add(func);
  16449. };
  16450. Scene.prototype.unregisterAfterRender = function (func) {
  16451. this.onAfterRenderObservable.removeCallback(func);
  16452. };
  16453. Scene.prototype._addPendingData = function (data) {
  16454. this._pendingData.push(data);
  16455. };
  16456. Scene.prototype._removePendingData = function (data) {
  16457. var index = this._pendingData.indexOf(data);
  16458. if (index !== -1) {
  16459. this._pendingData.splice(index, 1);
  16460. }
  16461. };
  16462. Scene.prototype.getWaitingItemsCount = function () {
  16463. return this._pendingData.length;
  16464. };
  16465. /**
  16466. * Registers a function to be executed when the scene is ready.
  16467. * @param {Function} func - the function to be executed.
  16468. */
  16469. Scene.prototype.executeWhenReady = function (func) {
  16470. var _this = this;
  16471. this.onReadyObservable.add(func);
  16472. if (this._executeWhenReadyTimeoutId !== -1) {
  16473. return;
  16474. }
  16475. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16476. _this._checkIsReady();
  16477. }, 150);
  16478. };
  16479. Scene.prototype._checkIsReady = function () {
  16480. var _this = this;
  16481. if (this.isReady()) {
  16482. this.onReadyObservable.notifyObservers(this);
  16483. this.onReadyObservable.clear();
  16484. this._executeWhenReadyTimeoutId = -1;
  16485. return;
  16486. }
  16487. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16488. _this._checkIsReady();
  16489. }, 150);
  16490. };
  16491. // Animations
  16492. /**
  16493. * Will start the animation sequence of a given target
  16494. * @param target - the target
  16495. * @param {number} from - from which frame should animation start
  16496. * @param {number} to - till which frame should animation run.
  16497. * @param {boolean} [loop] - should the animation loop
  16498. * @param {number} [speedRatio] - the speed in which to run the animation
  16499. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16500. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16501. * @return {BABYLON.Animatable} the animatable object created for this animation
  16502. * @see BABYLON.Animatable
  16503. * @see http://doc.babylonjs.com/page.php?p=22081
  16504. */
  16505. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16506. if (speedRatio === void 0) { speedRatio = 1.0; }
  16507. this.stopAnimation(target);
  16508. if (!animatable) {
  16509. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16510. }
  16511. // Local animations
  16512. if (target.animations) {
  16513. animatable.appendAnimations(target, target.animations);
  16514. }
  16515. // Children animations
  16516. if (target.getAnimatables) {
  16517. var animatables = target.getAnimatables();
  16518. for (var index = 0; index < animatables.length; index++) {
  16519. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16520. }
  16521. }
  16522. animatable.reset();
  16523. return animatable;
  16524. };
  16525. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16526. if (speedRatio === undefined) {
  16527. speedRatio = 1.0;
  16528. }
  16529. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16530. return animatable;
  16531. };
  16532. Scene.prototype.getAnimatableByTarget = function (target) {
  16533. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16534. if (this._activeAnimatables[index].target === target) {
  16535. return this._activeAnimatables[index];
  16536. }
  16537. }
  16538. return null;
  16539. };
  16540. Object.defineProperty(Scene.prototype, "Animatables", {
  16541. get: function () {
  16542. return this._activeAnimatables;
  16543. },
  16544. enumerable: true,
  16545. configurable: true
  16546. });
  16547. /**
  16548. * Will stop the animation of the given target
  16549. * @param target - the target
  16550. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16551. * @see beginAnimation
  16552. */
  16553. Scene.prototype.stopAnimation = function (target, animationName) {
  16554. var animatable = this.getAnimatableByTarget(target);
  16555. if (animatable) {
  16556. animatable.stop(animationName);
  16557. }
  16558. };
  16559. Scene.prototype._animate = function () {
  16560. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16561. return;
  16562. }
  16563. // Getting time
  16564. var now = BABYLON.Tools.Now;
  16565. if (!this._animationTimeLast) {
  16566. if (this._pendingData.length > 0) {
  16567. return;
  16568. }
  16569. this._animationTimeLast = now;
  16570. }
  16571. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16572. this._animationTime += deltaTime;
  16573. this._animationTimeLast = now;
  16574. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16575. this._activeAnimatables[index]._animate(this._animationTime);
  16576. }
  16577. };
  16578. // Matrix
  16579. Scene.prototype.getViewMatrix = function () {
  16580. return this._viewMatrix;
  16581. };
  16582. Scene.prototype.getProjectionMatrix = function () {
  16583. return this._projectionMatrix;
  16584. };
  16585. Scene.prototype.getTransformMatrix = function () {
  16586. return this._transformMatrix;
  16587. };
  16588. Scene.prototype.setTransformMatrix = function (view, projection) {
  16589. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16590. return;
  16591. }
  16592. this._viewUpdateFlag = view.updateFlag;
  16593. this._projectionUpdateFlag = projection.updateFlag;
  16594. this._viewMatrix = view;
  16595. this._projectionMatrix = projection;
  16596. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16597. // Update frustum
  16598. if (!this._frustumPlanes) {
  16599. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16600. }
  16601. else {
  16602. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16603. }
  16604. if (this._sceneUbo.useUbo) {
  16605. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16606. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16607. this._sceneUbo.update();
  16608. }
  16609. };
  16610. Scene.prototype.getSceneUniformBuffer = function () {
  16611. return this._sceneUbo;
  16612. };
  16613. // Methods
  16614. Scene.prototype.getUniqueId = function () {
  16615. var result = this._uniqueIdCounter;
  16616. this._uniqueIdCounter++;
  16617. return result;
  16618. };
  16619. Scene.prototype.addMesh = function (newMesh) {
  16620. newMesh.uniqueId = this.getUniqueId();
  16621. var position = this.meshes.push(newMesh);
  16622. //notify the collision coordinator
  16623. if (this.collisionCoordinator) {
  16624. this.collisionCoordinator.onMeshAdded(newMesh);
  16625. }
  16626. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16627. };
  16628. Scene.prototype.removeMesh = function (toRemove) {
  16629. var index = this.meshes.indexOf(toRemove);
  16630. if (index !== -1) {
  16631. // Remove from the scene if mesh found
  16632. this.meshes.splice(index, 1);
  16633. }
  16634. //notify the collision coordinator
  16635. if (this.collisionCoordinator) {
  16636. this.collisionCoordinator.onMeshRemoved(toRemove);
  16637. }
  16638. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16639. return index;
  16640. };
  16641. Scene.prototype.removeSkeleton = function (toRemove) {
  16642. var index = this.skeletons.indexOf(toRemove);
  16643. if (index !== -1) {
  16644. // Remove from the scene if found
  16645. this.skeletons.splice(index, 1);
  16646. }
  16647. return index;
  16648. };
  16649. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16650. var index = this.morphTargetManagers.indexOf(toRemove);
  16651. if (index !== -1) {
  16652. // Remove from the scene if found
  16653. this.morphTargetManagers.splice(index, 1);
  16654. }
  16655. return index;
  16656. };
  16657. Scene.prototype.removeLight = function (toRemove) {
  16658. var index = this.lights.indexOf(toRemove);
  16659. if (index !== -1) {
  16660. // Remove from the scene if mesh found
  16661. this.lights.splice(index, 1);
  16662. this.sortLightsByPriority();
  16663. }
  16664. this.onLightRemovedObservable.notifyObservers(toRemove);
  16665. return index;
  16666. };
  16667. Scene.prototype.removeCamera = function (toRemove) {
  16668. var index = this.cameras.indexOf(toRemove);
  16669. if (index !== -1) {
  16670. // Remove from the scene if mesh found
  16671. this.cameras.splice(index, 1);
  16672. }
  16673. // Remove from activeCameras
  16674. var index2 = this.activeCameras.indexOf(toRemove);
  16675. if (index2 !== -1) {
  16676. // Remove from the scene if mesh found
  16677. this.activeCameras.splice(index2, 1);
  16678. }
  16679. // Reset the activeCamera
  16680. if (this.activeCamera === toRemove) {
  16681. if (this.cameras.length > 0) {
  16682. this.activeCamera = this.cameras[0];
  16683. }
  16684. else {
  16685. this.activeCamera = null;
  16686. }
  16687. }
  16688. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16689. return index;
  16690. };
  16691. Scene.prototype.addLight = function (newLight) {
  16692. newLight.uniqueId = this.getUniqueId();
  16693. this.lights.push(newLight);
  16694. this.sortLightsByPriority();
  16695. this.onNewLightAddedObservable.notifyObservers(newLight);
  16696. };
  16697. Scene.prototype.sortLightsByPriority = function () {
  16698. if (this.requireLightSorting) {
  16699. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16700. }
  16701. };
  16702. Scene.prototype.addCamera = function (newCamera) {
  16703. newCamera.uniqueId = this.getUniqueId();
  16704. var position = this.cameras.push(newCamera);
  16705. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16706. };
  16707. /**
  16708. * Switch active camera
  16709. * @param {Camera} newCamera - new active camera
  16710. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16711. */
  16712. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16713. if (attachControl === void 0) { attachControl = true; }
  16714. var canvas = this._engine.getRenderingCanvas();
  16715. this.activeCamera.detachControl(canvas);
  16716. this.activeCamera = newCamera;
  16717. if (attachControl) {
  16718. newCamera.attachControl(canvas);
  16719. }
  16720. };
  16721. /**
  16722. * sets the active camera of the scene using its ID
  16723. * @param {string} id - the camera's ID
  16724. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16725. * @see activeCamera
  16726. */
  16727. Scene.prototype.setActiveCameraByID = function (id) {
  16728. var camera = this.getCameraByID(id);
  16729. if (camera) {
  16730. this.activeCamera = camera;
  16731. return camera;
  16732. }
  16733. return null;
  16734. };
  16735. /**
  16736. * sets the active camera of the scene using its name
  16737. * @param {string} name - the camera's name
  16738. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16739. * @see activeCamera
  16740. */
  16741. Scene.prototype.setActiveCameraByName = function (name) {
  16742. var camera = this.getCameraByName(name);
  16743. if (camera) {
  16744. this.activeCamera = camera;
  16745. return camera;
  16746. }
  16747. return null;
  16748. };
  16749. /**
  16750. * get a material using its id
  16751. * @param {string} the material's ID
  16752. * @return {BABYLON.Material|null} the material or null if none found.
  16753. */
  16754. Scene.prototype.getMaterialByID = function (id) {
  16755. for (var index = 0; index < this.materials.length; index++) {
  16756. if (this.materials[index].id === id) {
  16757. return this.materials[index];
  16758. }
  16759. }
  16760. return null;
  16761. };
  16762. /**
  16763. * get a material using its name
  16764. * @param {string} the material's name
  16765. * @return {BABYLON.Material|null} the material or null if none found.
  16766. */
  16767. Scene.prototype.getMaterialByName = function (name) {
  16768. for (var index = 0; index < this.materials.length; index++) {
  16769. if (this.materials[index].name === name) {
  16770. return this.materials[index];
  16771. }
  16772. }
  16773. return null;
  16774. };
  16775. Scene.prototype.getLensFlareSystemByName = function (name) {
  16776. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16777. if (this.lensFlareSystems[index].name === name) {
  16778. return this.lensFlareSystems[index];
  16779. }
  16780. }
  16781. return null;
  16782. };
  16783. Scene.prototype.getLensFlareSystemByID = function (id) {
  16784. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16785. if (this.lensFlareSystems[index].id === id) {
  16786. return this.lensFlareSystems[index];
  16787. }
  16788. }
  16789. return null;
  16790. };
  16791. Scene.prototype.getCameraByID = function (id) {
  16792. for (var index = 0; index < this.cameras.length; index++) {
  16793. if (this.cameras[index].id === id) {
  16794. return this.cameras[index];
  16795. }
  16796. }
  16797. return null;
  16798. };
  16799. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16800. for (var index = 0; index < this.cameras.length; index++) {
  16801. if (this.cameras[index].uniqueId === uniqueId) {
  16802. return this.cameras[index];
  16803. }
  16804. }
  16805. return null;
  16806. };
  16807. /**
  16808. * get a camera using its name
  16809. * @param {string} the camera's name
  16810. * @return {BABYLON.Camera|null} the camera or null if none found.
  16811. */
  16812. Scene.prototype.getCameraByName = function (name) {
  16813. for (var index = 0; index < this.cameras.length; index++) {
  16814. if (this.cameras[index].name === name) {
  16815. return this.cameras[index];
  16816. }
  16817. }
  16818. return null;
  16819. };
  16820. /**
  16821. * get a bone using its id
  16822. * @param {string} the bone's id
  16823. * @return {BABYLON.Bone|null} the bone or null if not found
  16824. */
  16825. Scene.prototype.getBoneByID = function (id) {
  16826. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16827. var skeleton = this.skeletons[skeletonIndex];
  16828. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16829. if (skeleton.bones[boneIndex].id === id) {
  16830. return skeleton.bones[boneIndex];
  16831. }
  16832. }
  16833. }
  16834. return null;
  16835. };
  16836. /**
  16837. * get a bone using its id
  16838. * @param {string} the bone's name
  16839. * @return {BABYLON.Bone|null} the bone or null if not found
  16840. */
  16841. Scene.prototype.getBoneByName = function (name) {
  16842. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16843. var skeleton = this.skeletons[skeletonIndex];
  16844. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16845. if (skeleton.bones[boneIndex].name === name) {
  16846. return skeleton.bones[boneIndex];
  16847. }
  16848. }
  16849. }
  16850. return null;
  16851. };
  16852. /**
  16853. * get a light node using its name
  16854. * @param {string} the light's name
  16855. * @return {BABYLON.Light|null} the light or null if none found.
  16856. */
  16857. Scene.prototype.getLightByName = function (name) {
  16858. for (var index = 0; index < this.lights.length; index++) {
  16859. if (this.lights[index].name === name) {
  16860. return this.lights[index];
  16861. }
  16862. }
  16863. return null;
  16864. };
  16865. /**
  16866. * get a light node using its ID
  16867. * @param {string} the light's id
  16868. * @return {BABYLON.Light|null} the light or null if none found.
  16869. */
  16870. Scene.prototype.getLightByID = function (id) {
  16871. for (var index = 0; index < this.lights.length; index++) {
  16872. if (this.lights[index].id === id) {
  16873. return this.lights[index];
  16874. }
  16875. }
  16876. return null;
  16877. };
  16878. /**
  16879. * get a light node using its scene-generated unique ID
  16880. * @param {number} the light's unique id
  16881. * @return {BABYLON.Light|null} the light or null if none found.
  16882. */
  16883. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16884. for (var index = 0; index < this.lights.length; index++) {
  16885. if (this.lights[index].uniqueId === uniqueId) {
  16886. return this.lights[index];
  16887. }
  16888. }
  16889. return null;
  16890. };
  16891. /**
  16892. * get a particle system by id
  16893. * @param id {number} the particle system id
  16894. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16895. */
  16896. Scene.prototype.getParticleSystemByID = function (id) {
  16897. for (var index = 0; index < this.particleSystems.length; index++) {
  16898. if (this.particleSystems[index].id === id) {
  16899. return this.particleSystems[index];
  16900. }
  16901. }
  16902. return null;
  16903. };
  16904. /**
  16905. * get a geometry using its ID
  16906. * @param {string} the geometry's id
  16907. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16908. */
  16909. Scene.prototype.getGeometryByID = function (id) {
  16910. for (var index = 0; index < this._geometries.length; index++) {
  16911. if (this._geometries[index].id === id) {
  16912. return this._geometries[index];
  16913. }
  16914. }
  16915. return null;
  16916. };
  16917. /**
  16918. * add a new geometry to this scene.
  16919. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16920. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16921. * @return {boolean} was the geometry added or not
  16922. */
  16923. Scene.prototype.pushGeometry = function (geometry, force) {
  16924. if (!force && this.getGeometryByID(geometry.id)) {
  16925. return false;
  16926. }
  16927. this._geometries.push(geometry);
  16928. //notify the collision coordinator
  16929. if (this.collisionCoordinator) {
  16930. this.collisionCoordinator.onGeometryAdded(geometry);
  16931. }
  16932. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16933. return true;
  16934. };
  16935. /**
  16936. * Removes an existing geometry
  16937. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16938. * @return {boolean} was the geometry removed or not
  16939. */
  16940. Scene.prototype.removeGeometry = function (geometry) {
  16941. var index = this._geometries.indexOf(geometry);
  16942. if (index > -1) {
  16943. this._geometries.splice(index, 1);
  16944. //notify the collision coordinator
  16945. if (this.collisionCoordinator) {
  16946. this.collisionCoordinator.onGeometryDeleted(geometry);
  16947. }
  16948. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16949. return true;
  16950. }
  16951. return false;
  16952. };
  16953. Scene.prototype.getGeometries = function () {
  16954. return this._geometries;
  16955. };
  16956. /**
  16957. * Get the first added mesh found of a given ID
  16958. * @param {string} id - the id to search for
  16959. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16960. */
  16961. Scene.prototype.getMeshByID = function (id) {
  16962. for (var index = 0; index < this.meshes.length; index++) {
  16963. if (this.meshes[index].id === id) {
  16964. return this.meshes[index];
  16965. }
  16966. }
  16967. return null;
  16968. };
  16969. Scene.prototype.getMeshesByID = function (id) {
  16970. return this.meshes.filter(function (m) {
  16971. return m.id === id;
  16972. });
  16973. };
  16974. /**
  16975. * Get a mesh with its auto-generated unique id
  16976. * @param {number} uniqueId - the unique id to search for
  16977. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16978. */
  16979. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16980. for (var index = 0; index < this.meshes.length; index++) {
  16981. if (this.meshes[index].uniqueId === uniqueId) {
  16982. return this.meshes[index];
  16983. }
  16984. }
  16985. return null;
  16986. };
  16987. /**
  16988. * Get a the last added mesh found of a given ID
  16989. * @param {string} id - the id to search for
  16990. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16991. */
  16992. Scene.prototype.getLastMeshByID = function (id) {
  16993. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16994. if (this.meshes[index].id === id) {
  16995. return this.meshes[index];
  16996. }
  16997. }
  16998. return null;
  16999. };
  17000. /**
  17001. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17002. * @param {string} id - the id to search for
  17003. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17004. */
  17005. Scene.prototype.getLastEntryByID = function (id) {
  17006. var index;
  17007. for (index = this.meshes.length - 1; index >= 0; index--) {
  17008. if (this.meshes[index].id === id) {
  17009. return this.meshes[index];
  17010. }
  17011. }
  17012. for (index = this.cameras.length - 1; index >= 0; index--) {
  17013. if (this.cameras[index].id === id) {
  17014. return this.cameras[index];
  17015. }
  17016. }
  17017. for (index = this.lights.length - 1; index >= 0; index--) {
  17018. if (this.lights[index].id === id) {
  17019. return this.lights[index];
  17020. }
  17021. }
  17022. return null;
  17023. };
  17024. Scene.prototype.getNodeByID = function (id) {
  17025. var mesh = this.getMeshByID(id);
  17026. if (mesh) {
  17027. return mesh;
  17028. }
  17029. var light = this.getLightByID(id);
  17030. if (light) {
  17031. return light;
  17032. }
  17033. var camera = this.getCameraByID(id);
  17034. if (camera) {
  17035. return camera;
  17036. }
  17037. var bone = this.getBoneByID(id);
  17038. return bone;
  17039. };
  17040. Scene.prototype.getNodeByName = function (name) {
  17041. var mesh = this.getMeshByName(name);
  17042. if (mesh) {
  17043. return mesh;
  17044. }
  17045. var light = this.getLightByName(name);
  17046. if (light) {
  17047. return light;
  17048. }
  17049. var camera = this.getCameraByName(name);
  17050. if (camera) {
  17051. return camera;
  17052. }
  17053. var bone = this.getBoneByName(name);
  17054. return bone;
  17055. };
  17056. Scene.prototype.getMeshByName = function (name) {
  17057. for (var index = 0; index < this.meshes.length; index++) {
  17058. if (this.meshes[index].name === name) {
  17059. return this.meshes[index];
  17060. }
  17061. }
  17062. return null;
  17063. };
  17064. Scene.prototype.getSoundByName = function (name) {
  17065. var index;
  17066. if (BABYLON.AudioEngine) {
  17067. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17068. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17069. return this.mainSoundTrack.soundCollection[index];
  17070. }
  17071. }
  17072. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17073. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17074. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17075. return this.soundTracks[sdIndex].soundCollection[index];
  17076. }
  17077. }
  17078. }
  17079. }
  17080. return null;
  17081. };
  17082. Scene.prototype.getLastSkeletonByID = function (id) {
  17083. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17084. if (this.skeletons[index].id === id) {
  17085. return this.skeletons[index];
  17086. }
  17087. }
  17088. return null;
  17089. };
  17090. Scene.prototype.getSkeletonById = function (id) {
  17091. for (var index = 0; index < this.skeletons.length; index++) {
  17092. if (this.skeletons[index].id === id) {
  17093. return this.skeletons[index];
  17094. }
  17095. }
  17096. return null;
  17097. };
  17098. Scene.prototype.getSkeletonByName = function (name) {
  17099. for (var index = 0; index < this.skeletons.length; index++) {
  17100. if (this.skeletons[index].name === name) {
  17101. return this.skeletons[index];
  17102. }
  17103. }
  17104. return null;
  17105. };
  17106. Scene.prototype.getMorphTargetManagerById = function (id) {
  17107. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17108. if (this.morphTargetManagers[index].uniqueId === id) {
  17109. return this.morphTargetManagers[index];
  17110. }
  17111. }
  17112. return null;
  17113. };
  17114. Scene.prototype.isActiveMesh = function (mesh) {
  17115. return (this._activeMeshes.indexOf(mesh) !== -1);
  17116. };
  17117. /**
  17118. * Return a the first highlight layer of the scene with a given name.
  17119. * @param name The name of the highlight layer to look for.
  17120. * @return The highlight layer if found otherwise null.
  17121. */
  17122. Scene.prototype.getHighlightLayerByName = function (name) {
  17123. for (var index = 0; index < this.highlightLayers.length; index++) {
  17124. if (this.highlightLayers[index].name === name) {
  17125. return this.highlightLayers[index];
  17126. }
  17127. }
  17128. return null;
  17129. };
  17130. Object.defineProperty(Scene.prototype, "uid", {
  17131. /**
  17132. * Return a unique id as a string which can serve as an identifier for the scene
  17133. */
  17134. get: function () {
  17135. if (!this._uid) {
  17136. this._uid = BABYLON.Tools.RandomId();
  17137. }
  17138. return this._uid;
  17139. },
  17140. enumerable: true,
  17141. configurable: true
  17142. });
  17143. /**
  17144. * Add an externaly attached data from its key.
  17145. * This method call will fail and return false, if such key already exists.
  17146. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17147. * @param key the unique key that identifies the data
  17148. * @param data the data object to associate to the key for this Engine instance
  17149. * @return true if no such key were already present and the data was added successfully, false otherwise
  17150. */
  17151. Scene.prototype.addExternalData = function (key, data) {
  17152. if (!this._externalData) {
  17153. this._externalData = new BABYLON.StringDictionary();
  17154. }
  17155. return this._externalData.add(key, data);
  17156. };
  17157. /**
  17158. * Get an externaly attached data from its key
  17159. * @param key the unique key that identifies the data
  17160. * @return the associated data, if present (can be null), or undefined if not present
  17161. */
  17162. Scene.prototype.getExternalData = function (key) {
  17163. if (!this._externalData) {
  17164. return null;
  17165. }
  17166. return this._externalData.get(key);
  17167. };
  17168. /**
  17169. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17170. * @param key the unique key that identifies the data
  17171. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17172. * @return the associated data, can be null if the factory returned null.
  17173. */
  17174. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17175. if (!this._externalData) {
  17176. this._externalData = new BABYLON.StringDictionary();
  17177. }
  17178. return this._externalData.getOrAddWithFactory(key, factory);
  17179. };
  17180. /**
  17181. * Remove an externaly attached data from the Engine instance
  17182. * @param key the unique key that identifies the data
  17183. * @return true if the data was successfully removed, false if it doesn't exist
  17184. */
  17185. Scene.prototype.removeExternalData = function (key) {
  17186. return this._externalData.remove(key);
  17187. };
  17188. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17189. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17190. var material = subMesh.getMaterial();
  17191. if (mesh.showSubMeshesBoundingBox) {
  17192. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17193. }
  17194. if (material) {
  17195. // Render targets
  17196. if (material.getRenderTargetTextures) {
  17197. if (this._processedMaterials.indexOf(material) === -1) {
  17198. this._processedMaterials.push(material);
  17199. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17200. }
  17201. }
  17202. // Dispatch
  17203. this._activeIndices.addCount(subMesh.indexCount, false);
  17204. this._renderingManager.dispatch(subMesh);
  17205. }
  17206. }
  17207. };
  17208. Scene.prototype._isInIntermediateRendering = function () {
  17209. return this._intermediateRendering;
  17210. };
  17211. Scene.prototype._evaluateActiveMeshes = function () {
  17212. this.activeCamera._activeMeshes.reset();
  17213. this._activeMeshes.reset();
  17214. this._renderingManager.reset();
  17215. this._processedMaterials.reset();
  17216. this._activeParticleSystems.reset();
  17217. this._activeSkeletons.reset();
  17218. this._softwareSkinnedMeshes.reset();
  17219. if (this._boundingBoxRenderer) {
  17220. this._boundingBoxRenderer.reset();
  17221. }
  17222. // Meshes
  17223. var meshes;
  17224. var len;
  17225. if (this._selectionOctree) {
  17226. var selection = this._selectionOctree.select(this._frustumPlanes);
  17227. meshes = selection.data;
  17228. len = selection.length;
  17229. }
  17230. else {
  17231. len = this.meshes.length;
  17232. meshes = this.meshes;
  17233. }
  17234. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17235. var mesh = meshes[meshIndex];
  17236. if (mesh.isBlocked) {
  17237. continue;
  17238. }
  17239. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17240. if (!mesh.isReady() || !mesh.isEnabled()) {
  17241. continue;
  17242. }
  17243. mesh.computeWorldMatrix();
  17244. // Intersections
  17245. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17246. this._meshesForIntersections.pushNoDuplicate(mesh);
  17247. }
  17248. // Switch to current LOD
  17249. var meshLOD = mesh.getLOD(this.activeCamera);
  17250. if (!meshLOD) {
  17251. continue;
  17252. }
  17253. mesh._preActivate();
  17254. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17255. this._activeMeshes.push(mesh);
  17256. this.activeCamera._activeMeshes.push(mesh);
  17257. mesh._activate(this._renderId);
  17258. this._activeMesh(mesh, meshLOD);
  17259. }
  17260. }
  17261. // Particle systems
  17262. this._particlesDuration.beginMonitoring();
  17263. var beforeParticlesDate = BABYLON.Tools.Now;
  17264. if (this.particlesEnabled) {
  17265. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17266. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17267. var particleSystem = this.particleSystems[particleIndex];
  17268. if (!particleSystem.isStarted()) {
  17269. continue;
  17270. }
  17271. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17272. this._activeParticleSystems.push(particleSystem);
  17273. particleSystem.animate();
  17274. this._renderingManager.dispatchParticles(particleSystem);
  17275. }
  17276. }
  17277. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17278. }
  17279. this._particlesDuration.endMonitoring(false);
  17280. };
  17281. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17282. if (mesh.skeleton && this.skeletonsEnabled) {
  17283. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17284. mesh.skeleton.prepare();
  17285. }
  17286. if (!mesh.computeBonesUsingShaders) {
  17287. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17288. }
  17289. }
  17290. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17291. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17292. }
  17293. if (mesh && mesh.subMeshes) {
  17294. // Submeshes Octrees
  17295. var len;
  17296. var subMeshes;
  17297. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17298. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17299. len = intersections.length;
  17300. subMeshes = intersections.data;
  17301. }
  17302. else {
  17303. subMeshes = mesh.subMeshes;
  17304. len = subMeshes.length;
  17305. }
  17306. for (var subIndex = 0; subIndex < len; subIndex++) {
  17307. var subMesh = subMeshes[subIndex];
  17308. this._evaluateSubMesh(subMesh, mesh);
  17309. }
  17310. }
  17311. };
  17312. Scene.prototype.updateTransformMatrix = function (force) {
  17313. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17314. };
  17315. Scene.prototype._renderForCamera = function (camera) {
  17316. var engine = this._engine;
  17317. var startTime = BABYLON.Tools.Now;
  17318. this.activeCamera = camera;
  17319. if (!this.activeCamera)
  17320. throw new Error("Active camera not set");
  17321. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17322. // Viewport
  17323. engine.setViewport(this.activeCamera.viewport);
  17324. // Camera
  17325. this.resetCachedMaterial();
  17326. this._renderId++;
  17327. this.updateTransformMatrix();
  17328. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17329. // Meshes
  17330. this._evaluateActiveMeshesDuration.beginMonitoring();
  17331. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17332. this._evaluateActiveMeshes();
  17333. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17334. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17335. // Software skinning
  17336. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17337. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17338. mesh.applySkeleton(mesh.skeleton);
  17339. }
  17340. // Render targets
  17341. this._renderTargetsDuration.beginMonitoring();
  17342. var needsRestoreFrameBuffer = false;
  17343. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17344. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17345. this._intermediateRendering = true;
  17346. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17347. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17348. var renderTarget = this._renderTargets.data[renderIndex];
  17349. if (renderTarget._shouldRender()) {
  17350. this._renderId++;
  17351. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17352. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17353. }
  17354. }
  17355. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17356. this._intermediateRendering = false;
  17357. this._renderId++;
  17358. needsRestoreFrameBuffer = true; // Restore back buffer
  17359. }
  17360. // Render HighlightLayer Texture
  17361. var stencilState = this._engine.getStencilBuffer();
  17362. var renderhighlights = false;
  17363. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17364. this._intermediateRendering = true;
  17365. for (var i = 0; i < this.highlightLayers.length; i++) {
  17366. var highlightLayer = this.highlightLayers[i];
  17367. if (highlightLayer.shouldRender() &&
  17368. (!highlightLayer.camera ||
  17369. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17370. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17371. renderhighlights = true;
  17372. var renderTarget = highlightLayer._mainTexture;
  17373. if (renderTarget._shouldRender()) {
  17374. this._renderId++;
  17375. renderTarget.render(false, false);
  17376. needsRestoreFrameBuffer = true;
  17377. }
  17378. }
  17379. }
  17380. this._intermediateRendering = false;
  17381. this._renderId++;
  17382. }
  17383. if (needsRestoreFrameBuffer) {
  17384. if (this.offscreenRenderTarget) {
  17385. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17386. }
  17387. else {
  17388. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17389. }
  17390. }
  17391. this._renderTargetsDuration.endMonitoring(false);
  17392. // Prepare Frame
  17393. this.postProcessManager._prepareFrame();
  17394. this._renderDuration.beginMonitoring();
  17395. // Backgrounds
  17396. var layerIndex;
  17397. var layer;
  17398. if (this.layers.length) {
  17399. engine.setDepthBuffer(false);
  17400. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17401. layer = this.layers[layerIndex];
  17402. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17403. layer.render();
  17404. }
  17405. }
  17406. engine.setDepthBuffer(true);
  17407. }
  17408. // Render
  17409. BABYLON.Tools.StartPerformanceCounter("Main render");
  17410. // Activate HighlightLayer stencil
  17411. if (renderhighlights) {
  17412. this._engine.setStencilBuffer(true);
  17413. }
  17414. this._renderingManager.render(null, null, true, true);
  17415. // Restore HighlightLayer stencil
  17416. if (renderhighlights) {
  17417. this._engine.setStencilBuffer(stencilState);
  17418. }
  17419. BABYLON.Tools.EndPerformanceCounter("Main render");
  17420. // Bounding boxes
  17421. if (this._boundingBoxRenderer) {
  17422. this._boundingBoxRenderer.render();
  17423. }
  17424. // Lens flares
  17425. if (this.lensFlaresEnabled) {
  17426. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17427. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17428. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17429. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17430. lensFlareSystem.render();
  17431. }
  17432. }
  17433. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17434. }
  17435. // Foregrounds
  17436. if (this.layers.length) {
  17437. engine.setDepthBuffer(false);
  17438. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17439. layer = this.layers[layerIndex];
  17440. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17441. layer.render();
  17442. }
  17443. }
  17444. engine.setDepthBuffer(true);
  17445. }
  17446. // Highlight Layer
  17447. if (renderhighlights) {
  17448. engine.setDepthBuffer(false);
  17449. for (var i = 0; i < this.highlightLayers.length; i++) {
  17450. if (this.highlightLayers[i].shouldRender()) {
  17451. this.highlightLayers[i].render();
  17452. }
  17453. }
  17454. engine.setDepthBuffer(true);
  17455. }
  17456. this._renderDuration.endMonitoring(false);
  17457. // Finalize frame
  17458. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17459. // Update camera
  17460. this.activeCamera._updateFromScene();
  17461. // Reset some special arrays
  17462. this._renderTargets.reset();
  17463. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17464. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17465. };
  17466. Scene.prototype._processSubCameras = function (camera) {
  17467. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17468. this._renderForCamera(camera);
  17469. return;
  17470. }
  17471. // rig cameras
  17472. for (var index = 0; index < camera._rigCameras.length; index++) {
  17473. this._renderForCamera(camera._rigCameras[index]);
  17474. }
  17475. this.activeCamera = camera;
  17476. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17477. // Update camera
  17478. this.activeCamera._updateFromScene();
  17479. };
  17480. Scene.prototype._checkIntersections = function () {
  17481. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17482. var sourceMesh = this._meshesForIntersections.data[index];
  17483. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17484. var action = sourceMesh.actionManager.actions[actionIndex];
  17485. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17486. var parameters = action.getTriggerParameter();
  17487. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17488. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17489. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17490. if (areIntersecting && currentIntersectionInProgress === -1) {
  17491. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17492. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17493. sourceMesh._intersectionsInProgress.push(otherMesh);
  17494. }
  17495. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17496. sourceMesh._intersectionsInProgress.push(otherMesh);
  17497. }
  17498. }
  17499. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17500. //They intersected, and now they don't.
  17501. //is this trigger an exit trigger? execute an event.
  17502. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17503. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17504. }
  17505. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17506. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17507. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17508. }
  17509. }
  17510. }
  17511. }
  17512. }
  17513. };
  17514. Scene.prototype.render = function () {
  17515. if (this.isDisposed) {
  17516. return;
  17517. }
  17518. this._lastFrameDuration.beginMonitoring();
  17519. this._particlesDuration.fetchNewFrame();
  17520. this._spritesDuration.fetchNewFrame();
  17521. this._activeParticles.fetchNewFrame();
  17522. this._renderDuration.fetchNewFrame();
  17523. this._renderTargetsDuration.fetchNewFrame();
  17524. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17525. this._totalVertices.fetchNewFrame();
  17526. this._activeIndices.fetchNewFrame();
  17527. this._activeBones.fetchNewFrame();
  17528. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17529. this._meshesForIntersections.reset();
  17530. this.resetCachedMaterial();
  17531. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17532. // Actions
  17533. if (this.actionManager) {
  17534. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17535. }
  17536. //Simplification Queue
  17537. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17538. this.simplificationQueue.executeNext();
  17539. }
  17540. // Animations
  17541. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17542. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17543. this._animate();
  17544. // Physics
  17545. if (this._physicsEngine) {
  17546. BABYLON.Tools.StartPerformanceCounter("Physics");
  17547. this._physicsEngine._step(deltaTime / 1000.0);
  17548. BABYLON.Tools.EndPerformanceCounter("Physics");
  17549. }
  17550. // Before render
  17551. this.onBeforeRenderObservable.notifyObservers(this);
  17552. // Customs render targets
  17553. this._renderTargetsDuration.beginMonitoring();
  17554. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17555. var engine = this.getEngine();
  17556. var currentActiveCamera = this.activeCamera;
  17557. if (this.renderTargetsEnabled) {
  17558. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17559. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17560. var renderTarget = this.customRenderTargets[customIndex];
  17561. if (renderTarget._shouldRender()) {
  17562. this._renderId++;
  17563. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17564. if (!this.activeCamera)
  17565. throw new Error("Active camera not set");
  17566. // Viewport
  17567. engine.setViewport(this.activeCamera.viewport);
  17568. // Camera
  17569. this.updateTransformMatrix();
  17570. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17571. }
  17572. }
  17573. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17574. this._renderId++;
  17575. }
  17576. if (this.offscreenRenderTarget) {
  17577. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17578. }
  17579. else {
  17580. // Restore back buffer
  17581. if (this.customRenderTargets.length > 0) {
  17582. engine.restoreDefaultFramebuffer();
  17583. }
  17584. }
  17585. this._renderTargetsDuration.endMonitoring();
  17586. this.activeCamera = currentActiveCamera;
  17587. // Procedural textures
  17588. if (this.proceduralTexturesEnabled) {
  17589. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17590. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17591. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17592. if (proceduralTexture._shouldRender()) {
  17593. proceduralTexture.render();
  17594. }
  17595. }
  17596. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17597. }
  17598. // Clear
  17599. if (this.autoClearDepthAndStencil || this.autoClear) {
  17600. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17601. }
  17602. // Shadows
  17603. if (this.shadowsEnabled) {
  17604. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17605. var light = this.lights[lightIndex];
  17606. var shadowGenerator = light.getShadowGenerator();
  17607. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17608. var shadowMap = shadowGenerator.getShadowMap();
  17609. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17610. this._renderTargets.push(shadowMap);
  17611. }
  17612. }
  17613. }
  17614. }
  17615. // Depth renderer
  17616. if (this._depthRenderer) {
  17617. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17618. }
  17619. // Geometry renderer
  17620. if (this._geometryBufferRenderer) {
  17621. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17622. }
  17623. // RenderPipeline
  17624. if (this._postProcessRenderPipelineManager) {
  17625. this._postProcessRenderPipelineManager.update();
  17626. }
  17627. // Multi-cameras?
  17628. if (this.activeCameras.length > 0) {
  17629. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17630. if (cameraIndex > 0) {
  17631. this._engine.clear(null, false, true, true);
  17632. }
  17633. this._processSubCameras(this.activeCameras[cameraIndex]);
  17634. }
  17635. }
  17636. else {
  17637. if (!this.activeCamera) {
  17638. throw new Error("No camera defined");
  17639. }
  17640. this._processSubCameras(this.activeCamera);
  17641. }
  17642. // Intersection checks
  17643. this._checkIntersections();
  17644. // Update the audio listener attached to the camera
  17645. if (BABYLON.AudioEngine) {
  17646. this._updateAudioParameters();
  17647. }
  17648. // After render
  17649. if (this.afterRender) {
  17650. this.afterRender();
  17651. }
  17652. this.onAfterRenderObservable.notifyObservers(this);
  17653. // Cleaning
  17654. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17655. this._toBeDisposed.data[index].dispose();
  17656. this._toBeDisposed[index] = null;
  17657. }
  17658. this._toBeDisposed.reset();
  17659. if (this.dumpNextRenderTargets) {
  17660. this.dumpNextRenderTargets = false;
  17661. }
  17662. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17663. this._lastFrameDuration.endMonitoring();
  17664. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17665. this._totalLightsCounter.addCount(this.lights.length, true);
  17666. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17667. this._totalTexturesCounter.addCount(this.textures.length, true);
  17668. this._activeBones.addCount(0, true);
  17669. this._activeIndices.addCount(0, true);
  17670. this._activeParticles.addCount(0, true);
  17671. };
  17672. Scene.prototype._updateAudioParameters = function () {
  17673. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17674. return;
  17675. }
  17676. var listeningCamera;
  17677. var audioEngine = BABYLON.Engine.audioEngine;
  17678. if (this.activeCameras.length > 0) {
  17679. listeningCamera = this.activeCameras[0];
  17680. }
  17681. else {
  17682. listeningCamera = this.activeCamera;
  17683. }
  17684. if (listeningCamera && audioEngine.canUseWebAudio) {
  17685. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17686. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17687. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17688. cameraDirection.normalize();
  17689. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17690. var i;
  17691. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17692. var sound = this.mainSoundTrack.soundCollection[i];
  17693. if (sound.useCustomAttenuation) {
  17694. sound.updateDistanceFromListener();
  17695. }
  17696. }
  17697. for (i = 0; i < this.soundTracks.length; i++) {
  17698. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17699. sound = this.soundTracks[i].soundCollection[j];
  17700. if (sound.useCustomAttenuation) {
  17701. sound.updateDistanceFromListener();
  17702. }
  17703. }
  17704. }
  17705. }
  17706. };
  17707. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17708. // Audio
  17709. get: function () {
  17710. return this._audioEnabled;
  17711. },
  17712. set: function (value) {
  17713. this._audioEnabled = value;
  17714. if (BABYLON.AudioEngine) {
  17715. if (this._audioEnabled) {
  17716. this._enableAudio();
  17717. }
  17718. else {
  17719. this._disableAudio();
  17720. }
  17721. }
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Scene.prototype._disableAudio = function () {
  17727. var i;
  17728. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17729. this.mainSoundTrack.soundCollection[i].pause();
  17730. }
  17731. for (i = 0; i < this.soundTracks.length; i++) {
  17732. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17733. this.soundTracks[i].soundCollection[j].pause();
  17734. }
  17735. }
  17736. };
  17737. Scene.prototype._enableAudio = function () {
  17738. var i;
  17739. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17740. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17741. this.mainSoundTrack.soundCollection[i].play();
  17742. }
  17743. }
  17744. for (i = 0; i < this.soundTracks.length; i++) {
  17745. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17746. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17747. this.soundTracks[i].soundCollection[j].play();
  17748. }
  17749. }
  17750. }
  17751. };
  17752. Object.defineProperty(Scene.prototype, "headphone", {
  17753. get: function () {
  17754. return this._headphone;
  17755. },
  17756. set: function (value) {
  17757. this._headphone = value;
  17758. if (BABYLON.AudioEngine) {
  17759. if (this._headphone) {
  17760. this._switchAudioModeForHeadphones();
  17761. }
  17762. else {
  17763. this._switchAudioModeForNormalSpeakers();
  17764. }
  17765. }
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. Scene.prototype._switchAudioModeForHeadphones = function () {
  17771. this.mainSoundTrack.switchPanningModelToHRTF();
  17772. for (var i = 0; i < this.soundTracks.length; i++) {
  17773. this.soundTracks[i].switchPanningModelToHRTF();
  17774. }
  17775. };
  17776. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17777. this.mainSoundTrack.switchPanningModelToEqualPower();
  17778. for (var i = 0; i < this.soundTracks.length; i++) {
  17779. this.soundTracks[i].switchPanningModelToEqualPower();
  17780. }
  17781. };
  17782. Scene.prototype.enableDepthRenderer = function () {
  17783. if (this._depthRenderer) {
  17784. return this._depthRenderer;
  17785. }
  17786. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17787. return this._depthRenderer;
  17788. };
  17789. Scene.prototype.disableDepthRenderer = function () {
  17790. if (!this._depthRenderer) {
  17791. return;
  17792. }
  17793. this._depthRenderer.dispose();
  17794. this._depthRenderer = null;
  17795. };
  17796. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17797. if (ratio === void 0) { ratio = 1; }
  17798. if (this._geometryBufferRenderer) {
  17799. return this._geometryBufferRenderer;
  17800. }
  17801. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17802. if (!this._geometryBufferRenderer.isSupported) {
  17803. this._geometryBufferRenderer = null;
  17804. }
  17805. return this._geometryBufferRenderer;
  17806. };
  17807. Scene.prototype.disableGeometryBufferRenderer = function () {
  17808. if (!this._geometryBufferRenderer) {
  17809. return;
  17810. }
  17811. this._geometryBufferRenderer.dispose();
  17812. this._geometryBufferRenderer = null;
  17813. };
  17814. Scene.prototype.freezeMaterials = function () {
  17815. for (var i = 0; i < this.materials.length; i++) {
  17816. this.materials[i].freeze();
  17817. }
  17818. };
  17819. Scene.prototype.unfreezeMaterials = function () {
  17820. for (var i = 0; i < this.materials.length; i++) {
  17821. this.materials[i].unfreeze();
  17822. }
  17823. };
  17824. Scene.prototype.dispose = function () {
  17825. this.beforeRender = null;
  17826. this.afterRender = null;
  17827. this.skeletons = [];
  17828. this.morphTargetManagers = [];
  17829. this.importedMeshesFiles = new Array();
  17830. if (this._depthRenderer) {
  17831. this._depthRenderer.dispose();
  17832. }
  17833. // Smart arrays
  17834. if (this.activeCamera) {
  17835. this.activeCamera._activeMeshes.dispose();
  17836. this.activeCamera = null;
  17837. }
  17838. this._activeMeshes.dispose();
  17839. this._renderingManager.dispose();
  17840. this._processedMaterials.dispose();
  17841. this._activeParticleSystems.dispose();
  17842. this._activeSkeletons.dispose();
  17843. this._softwareSkinnedMeshes.dispose();
  17844. if (this._boundingBoxRenderer) {
  17845. this._boundingBoxRenderer.dispose();
  17846. }
  17847. this._meshesForIntersections.dispose();
  17848. this._toBeDisposed.dispose();
  17849. // Debug layer
  17850. if (this._debugLayer) {
  17851. this._debugLayer.hide();
  17852. }
  17853. // Events
  17854. this.onDisposeObservable.notifyObservers(this);
  17855. this.onDisposeObservable.clear();
  17856. this.onBeforeRenderObservable.clear();
  17857. this.onAfterRenderObservable.clear();
  17858. this.detachControl();
  17859. // Release sounds & sounds tracks
  17860. if (BABYLON.AudioEngine) {
  17861. this.disposeSounds();
  17862. }
  17863. // Detach cameras
  17864. var canvas = this._engine.getRenderingCanvas();
  17865. var index;
  17866. for (index = 0; index < this.cameras.length; index++) {
  17867. this.cameras[index].detachControl(canvas);
  17868. }
  17869. // Release lights
  17870. while (this.lights.length) {
  17871. this.lights[0].dispose();
  17872. }
  17873. // Release meshes
  17874. while (this.meshes.length) {
  17875. this.meshes[0].dispose(true);
  17876. }
  17877. // Release cameras
  17878. while (this.cameras.length) {
  17879. this.cameras[0].dispose();
  17880. }
  17881. // Release materials
  17882. while (this.materials.length) {
  17883. this.materials[0].dispose();
  17884. }
  17885. // Release particles
  17886. while (this.particleSystems.length) {
  17887. this.particleSystems[0].dispose();
  17888. }
  17889. // Release sprites
  17890. while (this.spriteManagers.length) {
  17891. this.spriteManagers[0].dispose();
  17892. }
  17893. // Release layers
  17894. while (this.layers.length) {
  17895. this.layers[0].dispose();
  17896. }
  17897. while (this.highlightLayers.length) {
  17898. this.highlightLayers[0].dispose();
  17899. }
  17900. // Release textures
  17901. while (this.textures.length) {
  17902. this.textures[0].dispose();
  17903. }
  17904. // Release UBO
  17905. this._sceneUbo.dispose();
  17906. // Post-processes
  17907. this.postProcessManager.dispose();
  17908. // Physics
  17909. if (this._physicsEngine) {
  17910. this.disablePhysicsEngine();
  17911. }
  17912. // Remove from engine
  17913. index = this._engine.scenes.indexOf(this);
  17914. if (index > -1) {
  17915. this._engine.scenes.splice(index, 1);
  17916. }
  17917. this._engine.wipeCaches();
  17918. this._engine = null;
  17919. };
  17920. Object.defineProperty(Scene.prototype, "isDisposed", {
  17921. get: function () {
  17922. return !this._engine;
  17923. },
  17924. enumerable: true,
  17925. configurable: true
  17926. });
  17927. // Release sounds & sounds tracks
  17928. Scene.prototype.disposeSounds = function () {
  17929. this.mainSoundTrack.dispose();
  17930. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17931. this.soundTracks[scIndex].dispose();
  17932. }
  17933. };
  17934. // Octrees
  17935. Scene.prototype.getWorldExtends = function () {
  17936. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17937. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17938. for (var index = 0; index < this.meshes.length; index++) {
  17939. var mesh = this.meshes[index];
  17940. mesh.computeWorldMatrix(true);
  17941. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17942. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17943. BABYLON.Tools.CheckExtends(minBox, min, max);
  17944. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17945. }
  17946. return {
  17947. min: min,
  17948. max: max
  17949. };
  17950. };
  17951. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17952. if (maxCapacity === void 0) { maxCapacity = 64; }
  17953. if (maxDepth === void 0) { maxDepth = 2; }
  17954. if (!this._selectionOctree) {
  17955. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17956. }
  17957. var worldExtends = this.getWorldExtends();
  17958. // Update octree
  17959. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17960. return this._selectionOctree;
  17961. };
  17962. // Picking
  17963. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17964. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17965. var engine = this._engine;
  17966. if (!camera) {
  17967. if (!this.activeCamera)
  17968. throw new Error("Active camera not set");
  17969. camera = this.activeCamera;
  17970. }
  17971. var cameraViewport = camera.viewport;
  17972. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17973. // Moving coordinates to local viewport world
  17974. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17975. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17976. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17977. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17978. };
  17979. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17980. if (!BABYLON.PickingInfo) {
  17981. return null;
  17982. }
  17983. var engine = this._engine;
  17984. if (!camera) {
  17985. if (!this.activeCamera)
  17986. throw new Error("Active camera not set");
  17987. camera = this.activeCamera;
  17988. }
  17989. var cameraViewport = camera.viewport;
  17990. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17991. var identity = BABYLON.Matrix.Identity();
  17992. // Moving coordinates to local viewport world
  17993. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17994. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17995. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17996. };
  17997. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17998. if (!BABYLON.PickingInfo) {
  17999. return null;
  18000. }
  18001. var pickingInfo = null;
  18002. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18003. var mesh = this.meshes[meshIndex];
  18004. if (predicate) {
  18005. if (!predicate(mesh)) {
  18006. continue;
  18007. }
  18008. }
  18009. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18010. continue;
  18011. }
  18012. var world = mesh.getWorldMatrix();
  18013. var ray = rayFunction(world);
  18014. var result = mesh.intersects(ray, fastCheck);
  18015. if (!result || !result.hit)
  18016. continue;
  18017. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18018. continue;
  18019. pickingInfo = result;
  18020. if (fastCheck) {
  18021. break;
  18022. }
  18023. }
  18024. return pickingInfo || new BABYLON.PickingInfo();
  18025. };
  18026. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18027. if (!BABYLON.PickingInfo) {
  18028. return null;
  18029. }
  18030. var pickingInfos = new Array();
  18031. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18032. var mesh = this.meshes[meshIndex];
  18033. if (predicate) {
  18034. if (!predicate(mesh)) {
  18035. continue;
  18036. }
  18037. }
  18038. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18039. continue;
  18040. }
  18041. var world = mesh.getWorldMatrix();
  18042. var ray = rayFunction(world);
  18043. var result = mesh.intersects(ray, false);
  18044. if (!result || !result.hit)
  18045. continue;
  18046. pickingInfos.push(result);
  18047. }
  18048. return pickingInfos;
  18049. };
  18050. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18051. if (!BABYLON.PickingInfo) {
  18052. return null;
  18053. }
  18054. var pickingInfo = null;
  18055. camera = camera || this.activeCamera;
  18056. if (this.spriteManagers.length > 0) {
  18057. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18058. var spriteManager = this.spriteManagers[spriteIndex];
  18059. if (!spriteManager.isPickable) {
  18060. continue;
  18061. }
  18062. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18063. if (!result || !result.hit)
  18064. continue;
  18065. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18066. continue;
  18067. pickingInfo = result;
  18068. if (fastCheck) {
  18069. break;
  18070. }
  18071. }
  18072. }
  18073. return pickingInfo || new BABYLON.PickingInfo();
  18074. };
  18075. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18076. /// <param name="x">X position on screen</param>
  18077. /// <param name="y">Y position on screen</param>
  18078. /// <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>
  18079. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18080. /// <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>
  18081. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18082. var _this = this;
  18083. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18084. };
  18085. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18086. /// <param name="x">X position on screen</param>
  18087. /// <param name="y">Y position on screen</param>
  18088. /// <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>
  18089. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18090. /// <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>
  18091. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18092. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18093. };
  18094. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18095. var _this = this;
  18096. return this._internalPick(function (world) {
  18097. if (!_this._pickWithRayInverseMatrix) {
  18098. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18099. }
  18100. world.invertToRef(_this._pickWithRayInverseMatrix);
  18101. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18102. }, predicate, fastCheck);
  18103. };
  18104. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18105. /// <param name="x">X position on screen</param>
  18106. /// <param name="y">Y position on screen</param>
  18107. /// <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>
  18108. /// <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>
  18109. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18110. var _this = this;
  18111. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18112. };
  18113. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18114. /// <param name="ray">Ray to use</param>
  18115. /// <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>
  18116. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18117. var _this = this;
  18118. return this._internalMultiPick(function (world) {
  18119. if (!_this._pickWithRayInverseMatrix) {
  18120. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18121. }
  18122. world.invertToRef(_this._pickWithRayInverseMatrix);
  18123. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18124. }, predicate);
  18125. };
  18126. Scene.prototype.setPointerOverMesh = function (mesh) {
  18127. if (this._pointerOverMesh === mesh) {
  18128. return;
  18129. }
  18130. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18131. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18132. }
  18133. this._pointerOverMesh = mesh;
  18134. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18135. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18136. }
  18137. };
  18138. Scene.prototype.getPointerOverMesh = function () {
  18139. return this._pointerOverMesh;
  18140. };
  18141. Scene.prototype.setPointerOverSprite = function (sprite) {
  18142. if (this._pointerOverSprite === sprite) {
  18143. return;
  18144. }
  18145. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18146. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18147. }
  18148. this._pointerOverSprite = sprite;
  18149. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18150. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18151. }
  18152. };
  18153. Scene.prototype.getPointerOverSprite = function () {
  18154. return this._pointerOverSprite;
  18155. };
  18156. // Physics
  18157. Scene.prototype.getPhysicsEngine = function () {
  18158. return this._physicsEngine;
  18159. };
  18160. /**
  18161. * Enables physics to the current scene
  18162. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18163. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18164. * @return {boolean} was the physics engine initialized
  18165. */
  18166. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18167. if (this._physicsEngine) {
  18168. return true;
  18169. }
  18170. try {
  18171. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18172. return true;
  18173. }
  18174. catch (e) {
  18175. BABYLON.Tools.Error(e.message);
  18176. return false;
  18177. }
  18178. };
  18179. Scene.prototype.disablePhysicsEngine = function () {
  18180. if (!this._physicsEngine) {
  18181. return;
  18182. }
  18183. this._physicsEngine.dispose();
  18184. this._physicsEngine = undefined;
  18185. };
  18186. Scene.prototype.isPhysicsEnabled = function () {
  18187. return this._physicsEngine !== undefined;
  18188. };
  18189. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18190. var mesh = compound.parts[0].mesh;
  18191. mesh.physicsImpostor.dispose();
  18192. mesh.physicsImpostor = null;
  18193. };
  18194. // Misc.
  18195. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18196. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18197. // Light
  18198. if (this.lights.length === 0) {
  18199. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18200. }
  18201. // Camera
  18202. if (!this.activeCamera) {
  18203. var worldExtends = this.getWorldExtends();
  18204. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18205. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18206. var camera;
  18207. var radius = worldSize.length() * 1.5;
  18208. if (createArcRotateCamera) {
  18209. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18210. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18211. arcRotateCamera.wheelPrecision = 100 / radius;
  18212. camera = arcRotateCamera;
  18213. }
  18214. else {
  18215. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18216. freeCamera.setTarget(worldCenter);
  18217. camera = freeCamera;
  18218. }
  18219. camera.minZ = radius * 0.01;
  18220. camera.maxZ = radius * 100;
  18221. camera.speed = radius * 0.2;
  18222. this.activeCamera = camera;
  18223. }
  18224. };
  18225. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18226. if (pbr === void 0) { pbr = false; }
  18227. if (environmentTexture) {
  18228. this.environmentTexture = environmentTexture;
  18229. }
  18230. if (!this.environmentTexture) {
  18231. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18232. return;
  18233. }
  18234. if (!this.environmentTexture) {
  18235. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18236. return;
  18237. }
  18238. // Skybox
  18239. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18240. if (pbr) {
  18241. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18242. hdrSkyboxMaterial.backFaceCulling = false;
  18243. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18244. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18245. hdrSkyboxMaterial.microSurface = 1.0;
  18246. hdrSkyboxMaterial.disableLighting = true;
  18247. hdrSkybox.infiniteDistance = true;
  18248. hdrSkybox.material = hdrSkyboxMaterial;
  18249. }
  18250. else {
  18251. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18252. skyboxMaterial.backFaceCulling = false;
  18253. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18254. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18255. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18256. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18257. skyboxMaterial.disableLighting = true;
  18258. hdrSkybox.infiniteDistance = true;
  18259. hdrSkybox.material = skyboxMaterial;
  18260. }
  18261. return hdrSkybox;
  18262. };
  18263. // Tags
  18264. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18265. if (tagsQuery === undefined) {
  18266. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18267. return list;
  18268. }
  18269. var listByTags = [];
  18270. forEach = forEach || (function (item) { return; });
  18271. for (var i in list) {
  18272. var item = list[i];
  18273. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18274. listByTags.push(item);
  18275. forEach(item);
  18276. }
  18277. }
  18278. return listByTags;
  18279. };
  18280. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18281. return this._getByTags(this.meshes, tagsQuery, forEach);
  18282. };
  18283. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18284. return this._getByTags(this.cameras, tagsQuery, forEach);
  18285. };
  18286. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18287. return this._getByTags(this.lights, tagsQuery, forEach);
  18288. };
  18289. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18290. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18291. };
  18292. /**
  18293. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18294. * This allowed control for front to back rendering or reversly depending of the special needs.
  18295. *
  18296. * @param renderingGroupId The rendering group id corresponding to its index
  18297. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18298. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18299. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18300. */
  18301. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18302. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18303. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18304. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18305. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18306. };
  18307. /**
  18308. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18309. *
  18310. * @param renderingGroupId The rendering group id corresponding to its index
  18311. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18312. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18313. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18314. */
  18315. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18316. if (depth === void 0) { depth = true; }
  18317. if (stencil === void 0) { stencil = true; }
  18318. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18319. };
  18320. /**
  18321. * Will flag all materials as dirty to trigger new shader compilation
  18322. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18323. */
  18324. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18325. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18326. var material = _a[_i];
  18327. if (predicate && !predicate(material)) {
  18328. continue;
  18329. }
  18330. material.markAsDirty(flag);
  18331. }
  18332. };
  18333. return Scene;
  18334. }());
  18335. // Statics
  18336. Scene._FOGMODE_NONE = 0;
  18337. Scene._FOGMODE_EXP = 1;
  18338. Scene._FOGMODE_EXP2 = 2;
  18339. Scene._FOGMODE_LINEAR = 3;
  18340. Scene.MinDeltaTime = 1.0;
  18341. Scene.MaxDeltaTime = 1000.0;
  18342. Scene.DragMovementThreshold = 10; // in pixels
  18343. Scene.LongPressDelay = 500; // in milliseconds
  18344. Scene.DoubleClickDelay = 300; // in milliseconds
  18345. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18346. BABYLON.Scene = Scene;
  18347. })(BABYLON || (BABYLON = {}));
  18348. //# sourceMappingURL=babylon.scene.js.map
  18349. var BABYLON;
  18350. (function (BABYLON) {
  18351. var Buffer = (function () {
  18352. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18353. if (engine instanceof BABYLON.Mesh) {
  18354. this._engine = engine.getScene().getEngine();
  18355. }
  18356. else {
  18357. this._engine = engine;
  18358. }
  18359. this._updatable = updatable;
  18360. this._data = data;
  18361. this._strideSize = stride;
  18362. if (!postponeInternalCreation) {
  18363. this.create();
  18364. }
  18365. this._instanced = instanced;
  18366. }
  18367. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18368. // a lot of these parameters are ignored as they are overriden by the buffer
  18369. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18370. };
  18371. // Properties
  18372. Buffer.prototype.isUpdatable = function () {
  18373. return this._updatable;
  18374. };
  18375. Buffer.prototype.getData = function () {
  18376. return this._data;
  18377. };
  18378. Buffer.prototype.getBuffer = function () {
  18379. return this._buffer;
  18380. };
  18381. Buffer.prototype.getStrideSize = function () {
  18382. return this._strideSize;
  18383. };
  18384. Buffer.prototype.getIsInstanced = function () {
  18385. return this._instanced;
  18386. };
  18387. // Methods
  18388. Buffer.prototype.create = function (data) {
  18389. if (!data && this._buffer) {
  18390. return; // nothing to do
  18391. }
  18392. data = data || this._data;
  18393. if (!this._buffer) {
  18394. if (this._updatable) {
  18395. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18396. this._data = data;
  18397. }
  18398. else {
  18399. this._buffer = this._engine.createVertexBuffer(data);
  18400. }
  18401. }
  18402. else if (this._updatable) {
  18403. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18404. this._data = data;
  18405. }
  18406. };
  18407. Buffer.prototype.update = function (data) {
  18408. this.create(data);
  18409. };
  18410. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18411. if (!this._buffer) {
  18412. return;
  18413. }
  18414. if (this._updatable) {
  18415. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18416. this._data = null;
  18417. }
  18418. };
  18419. Buffer.prototype.dispose = function () {
  18420. if (!this._buffer) {
  18421. return;
  18422. }
  18423. if (this._engine._releaseBuffer(this._buffer)) {
  18424. this._buffer = null;
  18425. }
  18426. };
  18427. return Buffer;
  18428. }());
  18429. BABYLON.Buffer = Buffer;
  18430. })(BABYLON || (BABYLON = {}));
  18431. //# sourceMappingURL=babylon.buffer.js.map
  18432. var BABYLON;
  18433. (function (BABYLON) {
  18434. var VertexBuffer = (function () {
  18435. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18436. if (!stride) {
  18437. // Deduce stride from kind
  18438. switch (kind) {
  18439. case VertexBuffer.PositionKind:
  18440. stride = 3;
  18441. break;
  18442. case VertexBuffer.NormalKind:
  18443. stride = 3;
  18444. break;
  18445. case VertexBuffer.UVKind:
  18446. case VertexBuffer.UV2Kind:
  18447. case VertexBuffer.UV3Kind:
  18448. case VertexBuffer.UV4Kind:
  18449. case VertexBuffer.UV5Kind:
  18450. case VertexBuffer.UV6Kind:
  18451. stride = 2;
  18452. break;
  18453. case VertexBuffer.TangentKind:
  18454. case VertexBuffer.ColorKind:
  18455. stride = 4;
  18456. break;
  18457. case VertexBuffer.MatricesIndicesKind:
  18458. case VertexBuffer.MatricesIndicesExtraKind:
  18459. stride = 4;
  18460. break;
  18461. case VertexBuffer.MatricesWeightsKind:
  18462. case VertexBuffer.MatricesWeightsExtraKind:
  18463. stride = 4;
  18464. break;
  18465. }
  18466. }
  18467. if (data instanceof BABYLON.Buffer) {
  18468. if (!stride) {
  18469. stride = data.getStrideSize();
  18470. }
  18471. this._buffer = data;
  18472. this._ownsBuffer = false;
  18473. }
  18474. else {
  18475. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18476. this._ownsBuffer = true;
  18477. }
  18478. this._stride = stride;
  18479. this._offset = offset ? offset : 0;
  18480. this._size = size ? size : stride;
  18481. this._kind = kind;
  18482. }
  18483. /**
  18484. * Returns the kind of the VertexBuffer (string).
  18485. */
  18486. VertexBuffer.prototype.getKind = function () {
  18487. return this._kind;
  18488. };
  18489. // Properties
  18490. /**
  18491. * Boolean : is the VertexBuffer updatable ?
  18492. */
  18493. VertexBuffer.prototype.isUpdatable = function () {
  18494. return this._buffer.isUpdatable();
  18495. };
  18496. /**
  18497. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18498. */
  18499. VertexBuffer.prototype.getData = function () {
  18500. return this._buffer.getData();
  18501. };
  18502. /**
  18503. * Returns the WebGLBuffer associated to the VertexBuffer.
  18504. */
  18505. VertexBuffer.prototype.getBuffer = function () {
  18506. return this._buffer.getBuffer();
  18507. };
  18508. /**
  18509. * Returns the stride of the VertexBuffer (integer).
  18510. */
  18511. VertexBuffer.prototype.getStrideSize = function () {
  18512. return this._stride;
  18513. };
  18514. /**
  18515. * Returns the offset (integer).
  18516. */
  18517. VertexBuffer.prototype.getOffset = function () {
  18518. return this._offset;
  18519. };
  18520. /**
  18521. * Returns the VertexBuffer total size (integer).
  18522. */
  18523. VertexBuffer.prototype.getSize = function () {
  18524. return this._size;
  18525. };
  18526. /**
  18527. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18528. */
  18529. VertexBuffer.prototype.getIsInstanced = function () {
  18530. return this._buffer.getIsInstanced();
  18531. };
  18532. // Methods
  18533. /**
  18534. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18535. * Returns the created WebGLBuffer.
  18536. */
  18537. VertexBuffer.prototype.create = function (data) {
  18538. return this._buffer.create(data);
  18539. };
  18540. /**
  18541. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18542. * Returns the updated WebGLBuffer.
  18543. */
  18544. VertexBuffer.prototype.update = function (data) {
  18545. return this._buffer.update(data);
  18546. };
  18547. /**
  18548. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18549. * Returns the directly updated WebGLBuffer.
  18550. */
  18551. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18552. return this._buffer.updateDirectly(data, offset);
  18553. };
  18554. /**
  18555. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18556. */
  18557. VertexBuffer.prototype.dispose = function () {
  18558. if (this._ownsBuffer) {
  18559. this._buffer.dispose();
  18560. }
  18561. };
  18562. Object.defineProperty(VertexBuffer, "PositionKind", {
  18563. get: function () {
  18564. return VertexBuffer._PositionKind;
  18565. },
  18566. enumerable: true,
  18567. configurable: true
  18568. });
  18569. Object.defineProperty(VertexBuffer, "NormalKind", {
  18570. get: function () {
  18571. return VertexBuffer._NormalKind;
  18572. },
  18573. enumerable: true,
  18574. configurable: true
  18575. });
  18576. Object.defineProperty(VertexBuffer, "TangentKind", {
  18577. get: function () {
  18578. return VertexBuffer._TangentKind;
  18579. },
  18580. enumerable: true,
  18581. configurable: true
  18582. });
  18583. Object.defineProperty(VertexBuffer, "UVKind", {
  18584. get: function () {
  18585. return VertexBuffer._UVKind;
  18586. },
  18587. enumerable: true,
  18588. configurable: true
  18589. });
  18590. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18591. get: function () {
  18592. return VertexBuffer._UV2Kind;
  18593. },
  18594. enumerable: true,
  18595. configurable: true
  18596. });
  18597. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18598. get: function () {
  18599. return VertexBuffer._UV3Kind;
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18605. get: function () {
  18606. return VertexBuffer._UV4Kind;
  18607. },
  18608. enumerable: true,
  18609. configurable: true
  18610. });
  18611. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18612. get: function () {
  18613. return VertexBuffer._UV5Kind;
  18614. },
  18615. enumerable: true,
  18616. configurable: true
  18617. });
  18618. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18619. get: function () {
  18620. return VertexBuffer._UV6Kind;
  18621. },
  18622. enumerable: true,
  18623. configurable: true
  18624. });
  18625. Object.defineProperty(VertexBuffer, "ColorKind", {
  18626. get: function () {
  18627. return VertexBuffer._ColorKind;
  18628. },
  18629. enumerable: true,
  18630. configurable: true
  18631. });
  18632. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18633. get: function () {
  18634. return VertexBuffer._MatricesIndicesKind;
  18635. },
  18636. enumerable: true,
  18637. configurable: true
  18638. });
  18639. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18640. get: function () {
  18641. return VertexBuffer._MatricesWeightsKind;
  18642. },
  18643. enumerable: true,
  18644. configurable: true
  18645. });
  18646. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18647. get: function () {
  18648. return VertexBuffer._MatricesIndicesExtraKind;
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18654. get: function () {
  18655. return VertexBuffer._MatricesWeightsExtraKind;
  18656. },
  18657. enumerable: true,
  18658. configurable: true
  18659. });
  18660. return VertexBuffer;
  18661. }());
  18662. // Enums
  18663. VertexBuffer._PositionKind = "position";
  18664. VertexBuffer._NormalKind = "normal";
  18665. VertexBuffer._TangentKind = "tangent";
  18666. VertexBuffer._UVKind = "uv";
  18667. VertexBuffer._UV2Kind = "uv2";
  18668. VertexBuffer._UV3Kind = "uv3";
  18669. VertexBuffer._UV4Kind = "uv4";
  18670. VertexBuffer._UV5Kind = "uv5";
  18671. VertexBuffer._UV6Kind = "uv6";
  18672. VertexBuffer._ColorKind = "color";
  18673. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18674. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18675. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18676. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18677. BABYLON.VertexBuffer = VertexBuffer;
  18678. })(BABYLON || (BABYLON = {}));
  18679. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18680. var BABYLON;
  18681. (function (BABYLON) {
  18682. var BaseTexture = (function () {
  18683. function BaseTexture(scene) {
  18684. this._hasAlpha = false;
  18685. this.getAlphaFromRGB = false;
  18686. this.level = 1;
  18687. this.coordinatesIndex = 0;
  18688. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18689. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18690. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18691. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18692. this.isCube = false;
  18693. this.isRenderTarget = false;
  18694. this.animations = new Array();
  18695. /**
  18696. * An event triggered when the texture is disposed.
  18697. * @type {BABYLON.Observable}
  18698. */
  18699. this.onDisposeObservable = new BABYLON.Observable();
  18700. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18701. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18702. this._scene.textures.push(this);
  18703. this._uid = null;
  18704. }
  18705. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18706. get: function () {
  18707. return this._hasAlpha;
  18708. },
  18709. set: function (value) {
  18710. if (this._hasAlpha === value) {
  18711. return;
  18712. }
  18713. this._hasAlpha = value;
  18714. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18715. },
  18716. enumerable: true,
  18717. configurable: true
  18718. });
  18719. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18720. get: function () {
  18721. return this._coordinatesMode;
  18722. },
  18723. set: function (value) {
  18724. if (this._coordinatesMode === value) {
  18725. return;
  18726. }
  18727. this._coordinatesMode = value;
  18728. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18729. },
  18730. enumerable: true,
  18731. configurable: true
  18732. });
  18733. Object.defineProperty(BaseTexture.prototype, "uid", {
  18734. get: function () {
  18735. if (!this._uid) {
  18736. this._uid = BABYLON.Tools.RandomId();
  18737. }
  18738. return this._uid;
  18739. },
  18740. enumerable: true,
  18741. configurable: true
  18742. });
  18743. BaseTexture.prototype.toString = function () {
  18744. return this.name;
  18745. };
  18746. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18747. set: function (callback) {
  18748. if (this._onDisposeObserver) {
  18749. this.onDisposeObservable.remove(this._onDisposeObserver);
  18750. }
  18751. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18752. },
  18753. enumerable: true,
  18754. configurable: true
  18755. });
  18756. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18757. get: function () {
  18758. return true;
  18759. },
  18760. enumerable: true,
  18761. configurable: true
  18762. });
  18763. BaseTexture.prototype.getScene = function () {
  18764. return this._scene;
  18765. };
  18766. BaseTexture.prototype.getTextureMatrix = function () {
  18767. return null;
  18768. };
  18769. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18770. return null;
  18771. };
  18772. BaseTexture.prototype.getInternalTexture = function () {
  18773. return this._texture;
  18774. };
  18775. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18776. return !this.isBlocking || this.isReady();
  18777. };
  18778. BaseTexture.prototype.isReady = function () {
  18779. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18780. this.delayLoad();
  18781. return false;
  18782. }
  18783. if (this._texture) {
  18784. return this._texture.isReady;
  18785. }
  18786. return false;
  18787. };
  18788. BaseTexture.prototype.getSize = function () {
  18789. if (this._texture._width) {
  18790. return new BABYLON.Size(this._texture._width, this._texture._height);
  18791. }
  18792. if (this._texture._size) {
  18793. return new BABYLON.Size(this._texture._size, this._texture._size);
  18794. }
  18795. return BABYLON.Size.Zero();
  18796. };
  18797. BaseTexture.prototype.getBaseSize = function () {
  18798. if (!this.isReady() || !this._texture)
  18799. return BABYLON.Size.Zero();
  18800. if (this._texture._size) {
  18801. return new BABYLON.Size(this._texture._size, this._texture._size);
  18802. }
  18803. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18804. };
  18805. BaseTexture.prototype.scale = function (ratio) {
  18806. };
  18807. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18808. get: function () {
  18809. return false;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18815. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18816. for (var index = 0; index < texturesCache.length; index++) {
  18817. var texturesCacheEntry = texturesCache[index];
  18818. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18819. texturesCache.splice(index, 1);
  18820. return;
  18821. }
  18822. }
  18823. };
  18824. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18825. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18826. for (var index = 0; index < texturesCache.length; index++) {
  18827. var texturesCacheEntry = texturesCache[index];
  18828. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18829. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18830. texturesCacheEntry.references++;
  18831. return texturesCacheEntry;
  18832. }
  18833. }
  18834. }
  18835. return null;
  18836. };
  18837. BaseTexture.prototype.delayLoad = function () {
  18838. };
  18839. BaseTexture.prototype.clone = function () {
  18840. return null;
  18841. };
  18842. BaseTexture.prototype.releaseInternalTexture = function () {
  18843. if (this._texture) {
  18844. this._scene.getEngine().releaseInternalTexture(this._texture);
  18845. delete this._texture;
  18846. }
  18847. };
  18848. BaseTexture.prototype.dispose = function () {
  18849. // Animations
  18850. this.getScene().stopAnimation(this);
  18851. // Remove from scene
  18852. this._scene._removePendingData(this);
  18853. var index = this._scene.textures.indexOf(this);
  18854. if (index >= 0) {
  18855. this._scene.textures.splice(index, 1);
  18856. }
  18857. if (this._texture === undefined) {
  18858. return;
  18859. }
  18860. // Release
  18861. this.releaseInternalTexture();
  18862. // Callback
  18863. this.onDisposeObservable.notifyObservers(this);
  18864. this.onDisposeObservable.clear();
  18865. };
  18866. BaseTexture.prototype.serialize = function () {
  18867. if (!this.name) {
  18868. return null;
  18869. }
  18870. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18871. // Animations
  18872. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18873. return serializationObject;
  18874. };
  18875. return BaseTexture;
  18876. }());
  18877. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18878. __decorate([
  18879. BABYLON.serialize()
  18880. ], BaseTexture.prototype, "name", void 0);
  18881. __decorate([
  18882. BABYLON.serialize("hasAlpha")
  18883. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18884. __decorate([
  18885. BABYLON.serialize()
  18886. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18887. __decorate([
  18888. BABYLON.serialize()
  18889. ], BaseTexture.prototype, "level", void 0);
  18890. __decorate([
  18891. BABYLON.serialize()
  18892. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18893. __decorate([
  18894. BABYLON.serialize("coordinatesMode")
  18895. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18896. __decorate([
  18897. BABYLON.serialize()
  18898. ], BaseTexture.prototype, "wrapU", void 0);
  18899. __decorate([
  18900. BABYLON.serialize()
  18901. ], BaseTexture.prototype, "wrapV", void 0);
  18902. __decorate([
  18903. BABYLON.serialize()
  18904. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18905. __decorate([
  18906. BABYLON.serialize()
  18907. ], BaseTexture.prototype, "isCube", void 0);
  18908. __decorate([
  18909. BABYLON.serialize()
  18910. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18911. BABYLON.BaseTexture = BaseTexture;
  18912. })(BABYLON || (BABYLON = {}));
  18913. //# sourceMappingURL=babylon.baseTexture.js.map
  18914. var BABYLON;
  18915. (function (BABYLON) {
  18916. var Texture = (function (_super) {
  18917. __extends(Texture, _super);
  18918. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18919. if (noMipmap === void 0) { noMipmap = false; }
  18920. if (invertY === void 0) { invertY = true; }
  18921. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18922. if (onLoad === void 0) { onLoad = null; }
  18923. if (onError === void 0) { onError = null; }
  18924. if (buffer === void 0) { buffer = null; }
  18925. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18926. var _this = _super.call(this, scene) || this;
  18927. _this.uOffset = 0;
  18928. _this.vOffset = 0;
  18929. _this.uScale = 1.0;
  18930. _this.vScale = 1.0;
  18931. _this.uAng = 0;
  18932. _this.vAng = 0;
  18933. _this.wAng = 0;
  18934. _this._isBlocking = true;
  18935. _this.name = url;
  18936. _this.url = url;
  18937. _this._noMipmap = noMipmap;
  18938. _this._invertY = invertY;
  18939. _this._samplingMode = samplingMode;
  18940. _this._buffer = buffer;
  18941. _this._deleteBuffer = deleteBuffer;
  18942. _this._format = format;
  18943. scene = _this.getScene();
  18944. if (!url) {
  18945. return _this;
  18946. }
  18947. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  18948. var load = function () {
  18949. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  18950. _this.onLoadObservable.notifyObservers(true);
  18951. }
  18952. if (onLoad) {
  18953. onLoad();
  18954. }
  18955. if (!_this.isBlocking) {
  18956. scene.resetCachedMaterial();
  18957. }
  18958. };
  18959. if (!_this._texture) {
  18960. if (!scene.useDelayedTextureLoading) {
  18961. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  18962. if (deleteBuffer) {
  18963. delete _this._buffer;
  18964. }
  18965. }
  18966. else {
  18967. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18968. _this._delayedOnLoad = load;
  18969. _this._delayedOnError = onError;
  18970. }
  18971. }
  18972. else {
  18973. if (_this._texture.isReady) {
  18974. BABYLON.Tools.SetImmediate(function () { return load(); });
  18975. }
  18976. else {
  18977. _this._texture.onLoadedCallbacks.push(load);
  18978. }
  18979. }
  18980. return _this;
  18981. }
  18982. Object.defineProperty(Texture.prototype, "noMipmap", {
  18983. get: function () {
  18984. return this._noMipmap;
  18985. },
  18986. enumerable: true,
  18987. configurable: true
  18988. });
  18989. Object.defineProperty(Texture.prototype, "isBlocking", {
  18990. get: function () {
  18991. return this._isBlocking;
  18992. },
  18993. set: function (value) {
  18994. this._isBlocking = value;
  18995. },
  18996. enumerable: true,
  18997. configurable: true
  18998. });
  18999. Texture.prototype.delayLoad = function () {
  19000. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19001. return;
  19002. }
  19003. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19004. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19005. if (!this._texture) {
  19006. 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);
  19007. if (this._deleteBuffer) {
  19008. delete this._buffer;
  19009. }
  19010. }
  19011. };
  19012. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19013. if (!this._texture) {
  19014. return;
  19015. }
  19016. this._samplingMode = samplingMode;
  19017. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19018. };
  19019. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19020. x *= this.uScale;
  19021. y *= this.vScale;
  19022. x -= 0.5 * this.uScale;
  19023. y -= 0.5 * this.vScale;
  19024. z -= 0.5;
  19025. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19026. t.x += 0.5 * this.uScale + this.uOffset;
  19027. t.y += 0.5 * this.vScale + this.vOffset;
  19028. t.z += 0.5;
  19029. };
  19030. Texture.prototype.getTextureMatrix = function () {
  19031. if (this.uOffset === this._cachedUOffset &&
  19032. this.vOffset === this._cachedVOffset &&
  19033. this.uScale === this._cachedUScale &&
  19034. this.vScale === this._cachedVScale &&
  19035. this.uAng === this._cachedUAng &&
  19036. this.vAng === this._cachedVAng &&
  19037. this.wAng === this._cachedWAng) {
  19038. return this._cachedTextureMatrix;
  19039. }
  19040. this._cachedUOffset = this.uOffset;
  19041. this._cachedVOffset = this.vOffset;
  19042. this._cachedUScale = this.uScale;
  19043. this._cachedVScale = this.vScale;
  19044. this._cachedUAng = this.uAng;
  19045. this._cachedVAng = this.vAng;
  19046. this._cachedWAng = this.wAng;
  19047. if (!this._cachedTextureMatrix) {
  19048. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19049. this._rowGenerationMatrix = new BABYLON.Matrix();
  19050. this._t0 = BABYLON.Vector3.Zero();
  19051. this._t1 = BABYLON.Vector3.Zero();
  19052. this._t2 = BABYLON.Vector3.Zero();
  19053. }
  19054. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19055. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19056. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19057. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19058. this._t1.subtractInPlace(this._t0);
  19059. this._t2.subtractInPlace(this._t0);
  19060. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19061. this._cachedTextureMatrix.m[0] = this._t1.x;
  19062. this._cachedTextureMatrix.m[1] = this._t1.y;
  19063. this._cachedTextureMatrix.m[2] = this._t1.z;
  19064. this._cachedTextureMatrix.m[4] = this._t2.x;
  19065. this._cachedTextureMatrix.m[5] = this._t2.y;
  19066. this._cachedTextureMatrix.m[6] = this._t2.z;
  19067. this._cachedTextureMatrix.m[8] = this._t0.x;
  19068. this._cachedTextureMatrix.m[9] = this._t0.y;
  19069. this._cachedTextureMatrix.m[10] = this._t0.z;
  19070. return this._cachedTextureMatrix;
  19071. };
  19072. Texture.prototype.getReflectionTextureMatrix = function () {
  19073. if (this.uOffset === this._cachedUOffset &&
  19074. this.vOffset === this._cachedVOffset &&
  19075. this.uScale === this._cachedUScale &&
  19076. this.vScale === this._cachedVScale &&
  19077. this.coordinatesMode === this._cachedCoordinatesMode) {
  19078. return this._cachedTextureMatrix;
  19079. }
  19080. if (!this._cachedTextureMatrix) {
  19081. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19082. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19083. }
  19084. this._cachedCoordinatesMode = this.coordinatesMode;
  19085. switch (this.coordinatesMode) {
  19086. case Texture.PLANAR_MODE:
  19087. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19088. this._cachedTextureMatrix[0] = this.uScale;
  19089. this._cachedTextureMatrix[5] = this.vScale;
  19090. this._cachedTextureMatrix[12] = this.uOffset;
  19091. this._cachedTextureMatrix[13] = this.vOffset;
  19092. break;
  19093. case Texture.PROJECTION_MODE:
  19094. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19095. this._projectionModeMatrix.m[0] = 0.5;
  19096. this._projectionModeMatrix.m[5] = -0.5;
  19097. this._projectionModeMatrix.m[10] = 0.0;
  19098. this._projectionModeMatrix.m[12] = 0.5;
  19099. this._projectionModeMatrix.m[13] = 0.5;
  19100. this._projectionModeMatrix.m[14] = 1.0;
  19101. this._projectionModeMatrix.m[15] = 1.0;
  19102. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19103. break;
  19104. default:
  19105. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19106. break;
  19107. }
  19108. return this._cachedTextureMatrix;
  19109. };
  19110. Texture.prototype.clone = function () {
  19111. var _this = this;
  19112. return BABYLON.SerializationHelper.Clone(function () {
  19113. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19114. }, this);
  19115. };
  19116. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19117. get: function () {
  19118. if (!this._onLoadObservarble) {
  19119. this._onLoadObservarble = new BABYLON.Observable();
  19120. }
  19121. return this._onLoadObservarble;
  19122. },
  19123. enumerable: true,
  19124. configurable: true
  19125. });
  19126. // Statics
  19127. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19128. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19129. if (onLoad === void 0) { onLoad = null; }
  19130. if (onError === void 0) { onError = null; }
  19131. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19132. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19133. };
  19134. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19135. if (parsedTexture.customType) {
  19136. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19137. // Update Sampling Mode
  19138. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19139. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19140. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19141. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19142. }
  19143. }
  19144. return parsedCustomTexture;
  19145. }
  19146. if (parsedTexture.isCube) {
  19147. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19148. }
  19149. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19150. return null;
  19151. }
  19152. var texture = BABYLON.SerializationHelper.Parse(function () {
  19153. if (parsedTexture.mirrorPlane) {
  19154. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19155. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19156. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19157. return mirrorTexture;
  19158. }
  19159. else if (parsedTexture.isRenderTarget) {
  19160. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19161. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19162. return renderTargetTexture;
  19163. }
  19164. else {
  19165. var texture;
  19166. if (parsedTexture.base64String) {
  19167. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19168. }
  19169. else {
  19170. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19171. }
  19172. return texture;
  19173. }
  19174. }, parsedTexture, scene);
  19175. // Update Sampling Mode
  19176. if (parsedTexture.samplingMode) {
  19177. var sampling = parsedTexture.samplingMode;
  19178. if (texture._samplingMode !== sampling) {
  19179. texture.updateSamplingMode(sampling);
  19180. }
  19181. }
  19182. // Animations
  19183. if (parsedTexture.animations) {
  19184. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19185. var parsedAnimation = parsedTexture.animations[animationIndex];
  19186. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19187. }
  19188. }
  19189. return texture;
  19190. };
  19191. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19192. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19193. if (noMipmap === void 0) { noMipmap = false; }
  19194. if (invertY === void 0) { invertY = true; }
  19195. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19196. if (onLoad === void 0) { onLoad = null; }
  19197. if (onError === void 0) { onError = null; }
  19198. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19199. if (name.substr(0, 5) !== "data:") {
  19200. name = "data:" + name;
  19201. }
  19202. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19203. };
  19204. return Texture;
  19205. }(BABYLON.BaseTexture));
  19206. // Constants
  19207. Texture.NEAREST_SAMPLINGMODE = 1;
  19208. Texture.BILINEAR_SAMPLINGMODE = 2;
  19209. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19210. Texture.EXPLICIT_MODE = 0;
  19211. Texture.SPHERICAL_MODE = 1;
  19212. Texture.PLANAR_MODE = 2;
  19213. Texture.CUBIC_MODE = 3;
  19214. Texture.PROJECTION_MODE = 4;
  19215. Texture.SKYBOX_MODE = 5;
  19216. Texture.INVCUBIC_MODE = 6;
  19217. Texture.EQUIRECTANGULAR_MODE = 7;
  19218. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19219. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19220. Texture.CLAMP_ADDRESSMODE = 0;
  19221. Texture.WRAP_ADDRESSMODE = 1;
  19222. Texture.MIRROR_ADDRESSMODE = 2;
  19223. __decorate([
  19224. BABYLON.serialize()
  19225. ], Texture.prototype, "url", void 0);
  19226. __decorate([
  19227. BABYLON.serialize()
  19228. ], Texture.prototype, "uOffset", void 0);
  19229. __decorate([
  19230. BABYLON.serialize()
  19231. ], Texture.prototype, "vOffset", void 0);
  19232. __decorate([
  19233. BABYLON.serialize()
  19234. ], Texture.prototype, "uScale", void 0);
  19235. __decorate([
  19236. BABYLON.serialize()
  19237. ], Texture.prototype, "vScale", void 0);
  19238. __decorate([
  19239. BABYLON.serialize()
  19240. ], Texture.prototype, "uAng", void 0);
  19241. __decorate([
  19242. BABYLON.serialize()
  19243. ], Texture.prototype, "vAng", void 0);
  19244. __decorate([
  19245. BABYLON.serialize()
  19246. ], Texture.prototype, "wAng", void 0);
  19247. __decorate([
  19248. BABYLON.serialize()
  19249. ], Texture.prototype, "isBlocking", null);
  19250. BABYLON.Texture = Texture;
  19251. })(BABYLON || (BABYLON = {}));
  19252. //# sourceMappingURL=babylon.texture.js.map
  19253. var BABYLON;
  19254. (function (BABYLON) {
  19255. var _InstancesBatch = (function () {
  19256. function _InstancesBatch() {
  19257. this.mustReturn = false;
  19258. this.visibleInstances = new Array();
  19259. this.renderSelf = new Array();
  19260. }
  19261. return _InstancesBatch;
  19262. }());
  19263. BABYLON._InstancesBatch = _InstancesBatch;
  19264. var Mesh = (function (_super) {
  19265. __extends(Mesh, _super);
  19266. /**
  19267. * @constructor
  19268. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19269. * @param {Scene} scene The scene to add this mesh to.
  19270. * @param {Node} parent The parent of this mesh, if it has one
  19271. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19272. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19273. * When false, achieved by calling a clone(), also passing False.
  19274. * This will make creation of children, recursive.
  19275. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19276. */
  19277. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19278. if (parent === void 0) { parent = null; }
  19279. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19280. var _this = _super.call(this, name, scene) || this;
  19281. // Events
  19282. /**
  19283. * An event triggered before rendering the mesh
  19284. * @type {BABYLON.Observable}
  19285. */
  19286. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19287. /**
  19288. * An event triggered after rendering the mesh
  19289. * @type {BABYLON.Observable}
  19290. */
  19291. _this.onAfterRenderObservable = new BABYLON.Observable();
  19292. /**
  19293. * An event triggered before drawing the mesh
  19294. * @type {BABYLON.Observable}
  19295. */
  19296. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19297. // Members
  19298. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19299. _this.instances = new Array();
  19300. _this._LODLevels = new Array();
  19301. _this._visibleInstances = {};
  19302. _this._renderIdForInstances = new Array();
  19303. _this._batchCache = new _InstancesBatch();
  19304. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19305. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19306. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19307. // Will be used to save a source mesh reference, If any
  19308. _this._source = null;
  19309. if (source) {
  19310. // Source mesh
  19311. _this._source = source;
  19312. // Geometry
  19313. if (source._geometry) {
  19314. source._geometry.applyToMesh(_this);
  19315. }
  19316. // Deep copy
  19317. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19318. // Parent
  19319. _this.parent = source.parent;
  19320. // Pivot
  19321. _this.setPivotMatrix(source.getPivotMatrix());
  19322. _this.id = name + "." + source.id;
  19323. // Material
  19324. _this.material = source.material;
  19325. var index;
  19326. if (!doNotCloneChildren) {
  19327. // Children
  19328. for (index = 0; index < scene.meshes.length; index++) {
  19329. var mesh = scene.meshes[index];
  19330. if (mesh.parent === source) {
  19331. // doNotCloneChildren is always going to be False
  19332. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19333. }
  19334. }
  19335. }
  19336. // Physics clone
  19337. var physicsEngine = _this.getScene().getPhysicsEngine();
  19338. if (clonePhysicsImpostor && physicsEngine) {
  19339. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19340. if (impostor) {
  19341. _this.physicsImpostor = impostor.clone(_this);
  19342. }
  19343. }
  19344. // Particles
  19345. for (index = 0; index < scene.particleSystems.length; index++) {
  19346. var system = scene.particleSystems[index];
  19347. if (system.emitter === source) {
  19348. system.clone(system.name, _this);
  19349. }
  19350. }
  19351. _this.computeWorldMatrix(true);
  19352. }
  19353. // Parent
  19354. if (parent !== null) {
  19355. _this.parent = parent;
  19356. }
  19357. return _this;
  19358. }
  19359. Object.defineProperty(Mesh, "FRONTSIDE", {
  19360. /**
  19361. * Mesh side orientation : usually the external or front surface
  19362. */
  19363. get: function () {
  19364. return Mesh._FRONTSIDE;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(Mesh, "BACKSIDE", {
  19370. /**
  19371. * Mesh side orientation : usually the internal or back surface
  19372. */
  19373. get: function () {
  19374. return Mesh._BACKSIDE;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19380. /**
  19381. * Mesh side orientation : both internal and external or front and back surfaces
  19382. */
  19383. get: function () {
  19384. return Mesh._DOUBLESIDE;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19390. /**
  19391. * Mesh side orientation : by default, `FRONTSIDE`
  19392. */
  19393. get: function () {
  19394. return Mesh._DEFAULTSIDE;
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. Object.defineProperty(Mesh, "NO_CAP", {
  19400. /**
  19401. * Mesh cap setting : no cap
  19402. */
  19403. get: function () {
  19404. return Mesh._NO_CAP;
  19405. },
  19406. enumerable: true,
  19407. configurable: true
  19408. });
  19409. Object.defineProperty(Mesh, "CAP_START", {
  19410. /**
  19411. * Mesh cap setting : one cap at the beginning of the mesh
  19412. */
  19413. get: function () {
  19414. return Mesh._CAP_START;
  19415. },
  19416. enumerable: true,
  19417. configurable: true
  19418. });
  19419. Object.defineProperty(Mesh, "CAP_END", {
  19420. /**
  19421. * Mesh cap setting : one cap at the end of the mesh
  19422. */
  19423. get: function () {
  19424. return Mesh._CAP_END;
  19425. },
  19426. enumerable: true,
  19427. configurable: true
  19428. });
  19429. Object.defineProperty(Mesh, "CAP_ALL", {
  19430. /**
  19431. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19432. */
  19433. get: function () {
  19434. return Mesh._CAP_ALL;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19440. set: function (callback) {
  19441. if (this._onBeforeDrawObserver) {
  19442. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19443. }
  19444. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19445. },
  19446. enumerable: true,
  19447. configurable: true
  19448. });
  19449. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19450. get: function () {
  19451. return this._morphTargetManager;
  19452. },
  19453. set: function (value) {
  19454. if (this._morphTargetManager === value) {
  19455. return;
  19456. }
  19457. this._morphTargetManager = value;
  19458. this._syncGeometryWithMorphTargetManager();
  19459. },
  19460. enumerable: true,
  19461. configurable: true
  19462. });
  19463. Object.defineProperty(Mesh.prototype, "source", {
  19464. get: function () {
  19465. return this._source;
  19466. },
  19467. enumerable: true,
  19468. configurable: true
  19469. });
  19470. // Methods
  19471. /**
  19472. * Returns the string "Mesh".
  19473. */
  19474. Mesh.prototype.getClassName = function () {
  19475. return "Mesh";
  19476. };
  19477. /**
  19478. * Returns a string.
  19479. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19480. */
  19481. Mesh.prototype.toString = function (fullDetails) {
  19482. var ret = _super.prototype.toString.call(this, fullDetails);
  19483. ret += ", n vertices: " + this.getTotalVertices();
  19484. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19485. if (this.animations) {
  19486. for (var i = 0; i < this.animations.length; i++) {
  19487. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19488. }
  19489. }
  19490. if (fullDetails) {
  19491. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19492. }
  19493. return ret;
  19494. };
  19495. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19496. /**
  19497. * True if the mesh has some Levels Of Details (LOD).
  19498. * Returns a boolean.
  19499. */
  19500. get: function () {
  19501. return this._LODLevels.length > 0;
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. Mesh.prototype._sortLODLevels = function () {
  19507. this._LODLevels.sort(function (a, b) {
  19508. if (a.distance < b.distance) {
  19509. return 1;
  19510. }
  19511. if (a.distance > b.distance) {
  19512. return -1;
  19513. }
  19514. return 0;
  19515. });
  19516. };
  19517. /**
  19518. * Add a mesh as LOD level triggered at the given distance.
  19519. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19520. * @param {number} distance The distance from the center of the object to show this level
  19521. * @param {Mesh} mesh The mesh to be added as LOD level
  19522. * @return {Mesh} This mesh (for chaining)
  19523. */
  19524. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19525. if (mesh && mesh._masterMesh) {
  19526. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19527. return this;
  19528. }
  19529. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19530. this._LODLevels.push(level);
  19531. if (mesh) {
  19532. mesh._masterMesh = this;
  19533. }
  19534. this._sortLODLevels();
  19535. return this;
  19536. };
  19537. /**
  19538. * Returns the LOD level mesh at the passed distance or null if not found.
  19539. * It is related to the method `addLODLevel(distance, mesh)`.
  19540. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19541. * Returns an object Mesh or `null`.
  19542. */
  19543. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19544. for (var index = 0; index < this._LODLevels.length; index++) {
  19545. var level = this._LODLevels[index];
  19546. if (level.distance === distance) {
  19547. return level.mesh;
  19548. }
  19549. }
  19550. return null;
  19551. };
  19552. /**
  19553. * Remove a mesh from the LOD array
  19554. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19555. * @param {Mesh} mesh The mesh to be removed.
  19556. * @return {Mesh} This mesh (for chaining)
  19557. */
  19558. Mesh.prototype.removeLODLevel = function (mesh) {
  19559. for (var index = 0; index < this._LODLevels.length; index++) {
  19560. if (this._LODLevels[index].mesh === mesh) {
  19561. this._LODLevels.splice(index, 1);
  19562. if (mesh) {
  19563. mesh._masterMesh = null;
  19564. }
  19565. }
  19566. }
  19567. this._sortLODLevels();
  19568. return this;
  19569. };
  19570. /**
  19571. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19572. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19573. */
  19574. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19575. if (!this._LODLevels || this._LODLevels.length === 0) {
  19576. return this;
  19577. }
  19578. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19579. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19580. if (this.onLODLevelSelection) {
  19581. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19582. }
  19583. return this;
  19584. }
  19585. for (var index = 0; index < this._LODLevels.length; index++) {
  19586. var level = this._LODLevels[index];
  19587. if (level.distance < distanceToCamera) {
  19588. if (level.mesh) {
  19589. level.mesh._preActivate();
  19590. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19591. }
  19592. if (this.onLODLevelSelection) {
  19593. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19594. }
  19595. return level.mesh;
  19596. }
  19597. }
  19598. if (this.onLODLevelSelection) {
  19599. this.onLODLevelSelection(distanceToCamera, this, this);
  19600. }
  19601. return this;
  19602. };
  19603. Object.defineProperty(Mesh.prototype, "geometry", {
  19604. /**
  19605. * Returns the mesh internal Geometry object.
  19606. */
  19607. get: function () {
  19608. return this._geometry;
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. /**
  19614. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19615. */
  19616. Mesh.prototype.getTotalVertices = function () {
  19617. if (!this._geometry) {
  19618. return 0;
  19619. }
  19620. return this._geometry.getTotalVertices();
  19621. };
  19622. /**
  19623. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19624. * 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.
  19625. * You can force the copy with forceCopy === true
  19626. * Returns null if the mesh has no geometry or no vertex buffer.
  19627. * Possible `kind` values :
  19628. * - BABYLON.VertexBuffer.PositionKind
  19629. * - BABYLON.VertexBuffer.UVKind
  19630. * - BABYLON.VertexBuffer.UV2Kind
  19631. * - BABYLON.VertexBuffer.UV3Kind
  19632. * - BABYLON.VertexBuffer.UV4Kind
  19633. * - BABYLON.VertexBuffer.UV5Kind
  19634. * - BABYLON.VertexBuffer.UV6Kind
  19635. * - BABYLON.VertexBuffer.ColorKind
  19636. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19637. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19638. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19639. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19640. */
  19641. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19642. if (!this._geometry) {
  19643. return null;
  19644. }
  19645. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19646. };
  19647. /**
  19648. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19649. * Returns `undefined` if the mesh has no geometry.
  19650. * Possible `kind` values :
  19651. * - BABYLON.VertexBuffer.PositionKind
  19652. * - BABYLON.VertexBuffer.UVKind
  19653. * - BABYLON.VertexBuffer.UV2Kind
  19654. * - BABYLON.VertexBuffer.UV3Kind
  19655. * - BABYLON.VertexBuffer.UV4Kind
  19656. * - BABYLON.VertexBuffer.UV5Kind
  19657. * - BABYLON.VertexBuffer.UV6Kind
  19658. * - BABYLON.VertexBuffer.ColorKind
  19659. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19660. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19661. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19662. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19663. */
  19664. Mesh.prototype.getVertexBuffer = function (kind) {
  19665. if (!this._geometry) {
  19666. return undefined;
  19667. }
  19668. return this._geometry.getVertexBuffer(kind);
  19669. };
  19670. /**
  19671. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19672. * Possible `kind` values :
  19673. * - BABYLON.VertexBuffer.PositionKind
  19674. * - BABYLON.VertexBuffer.UVKind
  19675. * - BABYLON.VertexBuffer.UV2Kind
  19676. * - BABYLON.VertexBuffer.UV3Kind
  19677. * - BABYLON.VertexBuffer.UV4Kind
  19678. * - BABYLON.VertexBuffer.UV5Kind
  19679. * - BABYLON.VertexBuffer.UV6Kind
  19680. * - BABYLON.VertexBuffer.ColorKind
  19681. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19682. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19683. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19684. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19685. */
  19686. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19687. if (!this._geometry) {
  19688. if (this._delayInfo) {
  19689. return this._delayInfo.indexOf(kind) !== -1;
  19690. }
  19691. return false;
  19692. }
  19693. return this._geometry.isVerticesDataPresent(kind);
  19694. };
  19695. /**
  19696. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19697. * Possible `kind` values :
  19698. * - BABYLON.VertexBuffer.PositionKind
  19699. * - BABYLON.VertexBuffer.UVKind
  19700. * - BABYLON.VertexBuffer.UV2Kind
  19701. * - BABYLON.VertexBuffer.UV3Kind
  19702. * - BABYLON.VertexBuffer.UV4Kind
  19703. * - BABYLON.VertexBuffer.UV5Kind
  19704. * - BABYLON.VertexBuffer.UV6Kind
  19705. * - BABYLON.VertexBuffer.ColorKind
  19706. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19707. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19708. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19709. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19710. */
  19711. Mesh.prototype.getVerticesDataKinds = function () {
  19712. if (!this._geometry) {
  19713. var result = [];
  19714. if (this._delayInfo) {
  19715. this._delayInfo.forEach(function (kind, index, array) {
  19716. result.push(kind);
  19717. });
  19718. }
  19719. return result;
  19720. }
  19721. return this._geometry.getVerticesDataKinds();
  19722. };
  19723. /**
  19724. * Returns a positive integer : the total number of indices in this mesh geometry.
  19725. * Returns zero if the mesh has no geometry.
  19726. */
  19727. Mesh.prototype.getTotalIndices = function () {
  19728. if (!this._geometry) {
  19729. return 0;
  19730. }
  19731. return this._geometry.getTotalIndices();
  19732. };
  19733. /**
  19734. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19735. * 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.
  19736. * Returns an empty array if the mesh has no geometry.
  19737. */
  19738. Mesh.prototype.getIndices = function (copyWhenShared) {
  19739. if (!this._geometry) {
  19740. return [];
  19741. }
  19742. return this._geometry.getIndices(copyWhenShared);
  19743. };
  19744. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19745. get: function () {
  19746. return this._masterMesh !== null && this._masterMesh !== undefined;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. /**
  19752. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19753. */
  19754. Mesh.prototype.isReady = function () {
  19755. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19756. return false;
  19757. }
  19758. return _super.prototype.isReady.call(this);
  19759. };
  19760. /**
  19761. * Boolean : true if the mesh has been disposed.
  19762. */
  19763. Mesh.prototype.isDisposed = function () {
  19764. return this._isDisposed;
  19765. };
  19766. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19767. get: function () {
  19768. return this._sideOrientation;
  19769. },
  19770. /**
  19771. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19772. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19773. */
  19774. set: function (sideO) {
  19775. this._sideOrientation = sideO;
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19781. /**
  19782. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19783. * This property is pertinent only for updatable parametric shapes.
  19784. */
  19785. get: function () {
  19786. return this._areNormalsFrozen;
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. /**
  19792. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19793. * It has no effect at all on other shapes.
  19794. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19795. * Returns the Mesh.
  19796. */
  19797. Mesh.prototype.freezeNormals = function () {
  19798. this._areNormalsFrozen = true;
  19799. return this;
  19800. };
  19801. /**
  19802. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19803. * It has no effect at all on other shapes.
  19804. * It reactivates the mesh normals computation if it was previously frozen.
  19805. * Returns the Mesh.
  19806. */
  19807. Mesh.prototype.unfreezeNormals = function () {
  19808. this._areNormalsFrozen = false;
  19809. return this;
  19810. };
  19811. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19812. /**
  19813. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19814. */
  19815. set: function (count) {
  19816. this._overridenInstanceCount = count;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. // Methods
  19822. Mesh.prototype._preActivate = function () {
  19823. var sceneRenderId = this.getScene().getRenderId();
  19824. if (this._preActivateId === sceneRenderId) {
  19825. return this;
  19826. }
  19827. this._preActivateId = sceneRenderId;
  19828. this._visibleInstances = null;
  19829. return this;
  19830. };
  19831. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19832. if (this._visibleInstances) {
  19833. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19834. }
  19835. return this;
  19836. };
  19837. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19838. if (!this._visibleInstances) {
  19839. this._visibleInstances = {};
  19840. this._visibleInstances.defaultRenderId = renderId;
  19841. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19842. }
  19843. if (!this._visibleInstances[renderId]) {
  19844. this._visibleInstances[renderId] = new Array();
  19845. }
  19846. this._visibleInstances[renderId].push(instance);
  19847. return this;
  19848. };
  19849. /**
  19850. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19851. * This means the mesh underlying bounding box and sphere are recomputed.
  19852. * Returns the Mesh.
  19853. */
  19854. Mesh.prototype.refreshBoundingInfo = function () {
  19855. if (this._boundingInfo.isLocked) {
  19856. return;
  19857. }
  19858. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19859. if (data) {
  19860. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19861. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19862. }
  19863. if (this.subMeshes) {
  19864. for (var index = 0; index < this.subMeshes.length; index++) {
  19865. this.subMeshes[index].refreshBoundingInfo();
  19866. }
  19867. }
  19868. this._updateBoundingInfo();
  19869. return this;
  19870. };
  19871. Mesh.prototype._createGlobalSubMesh = function () {
  19872. var totalVertices = this.getTotalVertices();
  19873. if (!totalVertices || !this.getIndices()) {
  19874. return null;
  19875. }
  19876. this.releaseSubMeshes();
  19877. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19878. };
  19879. Mesh.prototype.subdivide = function (count) {
  19880. if (count < 1) {
  19881. return;
  19882. }
  19883. var totalIndices = this.getTotalIndices();
  19884. var subdivisionSize = (totalIndices / count) | 0;
  19885. var offset = 0;
  19886. // Ensure that subdivisionSize is a multiple of 3
  19887. while (subdivisionSize % 3 !== 0) {
  19888. subdivisionSize++;
  19889. }
  19890. this.releaseSubMeshes();
  19891. for (var index = 0; index < count; index++) {
  19892. if (offset >= totalIndices) {
  19893. break;
  19894. }
  19895. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19896. offset += subdivisionSize;
  19897. }
  19898. this.synchronizeInstances();
  19899. };
  19900. /**
  19901. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19902. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19903. * The `data` are either a numeric array either a Float32Array.
  19904. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19905. * 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).
  19906. * Note that a new underlying VertexBuffer object is created each call.
  19907. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19908. *
  19909. * Possible `kind` values :
  19910. * - BABYLON.VertexBuffer.PositionKind
  19911. * - BABYLON.VertexBuffer.UVKind
  19912. * - BABYLON.VertexBuffer.UV2Kind
  19913. * - BABYLON.VertexBuffer.UV3Kind
  19914. * - BABYLON.VertexBuffer.UV4Kind
  19915. * - BABYLON.VertexBuffer.UV5Kind
  19916. * - BABYLON.VertexBuffer.UV6Kind
  19917. * - BABYLON.VertexBuffer.ColorKind
  19918. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19919. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19920. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19921. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19922. *
  19923. * Returns the Mesh.
  19924. */
  19925. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19926. if (!this._geometry) {
  19927. var vertexData = new BABYLON.VertexData();
  19928. vertexData.set(data, kind);
  19929. var scene = this.getScene();
  19930. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19931. }
  19932. else {
  19933. this._geometry.setVerticesData(kind, data, updatable, stride);
  19934. }
  19935. return this;
  19936. };
  19937. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  19938. if (updatable === void 0) { updatable = true; }
  19939. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  19940. return;
  19941. }
  19942. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  19943. };
  19944. /**
  19945. * Sets the mesh VertexBuffer.
  19946. * Returns the Mesh.
  19947. */
  19948. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19949. if (!this._geometry) {
  19950. var scene = this.getScene();
  19951. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19952. }
  19953. this._geometry.setVerticesBuffer(buffer);
  19954. return this;
  19955. };
  19956. /**
  19957. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19958. * If the mesh has no geometry, it is simply returned as it is.
  19959. * The `data` are either a numeric array either a Float32Array.
  19960. * No new underlying VertexBuffer object is created.
  19961. * 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.
  19962. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19963. *
  19964. * Possible `kind` values :
  19965. * - BABYLON.VertexBuffer.PositionKind
  19966. * - BABYLON.VertexBuffer.UVKind
  19967. * - BABYLON.VertexBuffer.UV2Kind
  19968. * - BABYLON.VertexBuffer.UV3Kind
  19969. * - BABYLON.VertexBuffer.UV4Kind
  19970. * - BABYLON.VertexBuffer.UV5Kind
  19971. * - BABYLON.VertexBuffer.UV6Kind
  19972. * - BABYLON.VertexBuffer.ColorKind
  19973. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19974. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19975. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19976. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19977. *
  19978. * Returns the Mesh.
  19979. */
  19980. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19981. if (!this._geometry) {
  19982. return;
  19983. }
  19984. if (!makeItUnique) {
  19985. this._geometry.updateVerticesData(kind, data, updateExtends);
  19986. }
  19987. else {
  19988. this.makeGeometryUnique();
  19989. this.updateVerticesData(kind, data, updateExtends, false);
  19990. }
  19991. return this;
  19992. };
  19993. /**
  19994. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19995. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19996. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19997. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19998. * Returns the Mesh.
  19999. */
  20000. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20001. if (computeNormals === void 0) { computeNormals = true; }
  20002. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20003. positionFunction(positions);
  20004. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20005. if (computeNormals) {
  20006. var indices = this.getIndices();
  20007. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20008. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20009. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20010. }
  20011. return this;
  20012. };
  20013. /**
  20014. * Creates a un-shared specific occurence of the geometry for the mesh.
  20015. * Returns the Mesh.
  20016. */
  20017. Mesh.prototype.makeGeometryUnique = function () {
  20018. if (!this._geometry) {
  20019. return;
  20020. }
  20021. var oldGeometry = this._geometry;
  20022. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20023. oldGeometry.releaseForMesh(this, true);
  20024. geometry.applyToMesh(this);
  20025. return this;
  20026. };
  20027. /**
  20028. * Sets the mesh indices.
  20029. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20030. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20031. * This method creates a new index buffer each call.
  20032. * Returns the Mesh.
  20033. */
  20034. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20035. if (!this._geometry) {
  20036. var vertexData = new BABYLON.VertexData();
  20037. vertexData.indices = indices;
  20038. var scene = this.getScene();
  20039. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20040. }
  20041. else {
  20042. this._geometry.setIndices(indices, totalVertices);
  20043. }
  20044. return this;
  20045. };
  20046. /**
  20047. * Invert the geometry to move from a right handed system to a left handed one.
  20048. * Returns the Mesh.
  20049. */
  20050. Mesh.prototype.toLeftHanded = function () {
  20051. if (!this._geometry) {
  20052. return;
  20053. }
  20054. this._geometry.toLeftHanded();
  20055. return this;
  20056. };
  20057. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20058. var engine = this.getScene().getEngine();
  20059. // Wireframe
  20060. var indexToBind;
  20061. if (this._unIndexed) {
  20062. indexToBind = null;
  20063. }
  20064. else {
  20065. switch (fillMode) {
  20066. case BABYLON.Material.PointFillMode:
  20067. indexToBind = null;
  20068. break;
  20069. case BABYLON.Material.WireFrameFillMode:
  20070. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20071. break;
  20072. default:
  20073. case BABYLON.Material.TriangleFillMode:
  20074. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20075. break;
  20076. }
  20077. }
  20078. // VBOs
  20079. this._geometry._bind(effect, indexToBind);
  20080. return this;
  20081. };
  20082. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20083. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20084. return this;
  20085. }
  20086. this.onBeforeDrawObservable.notifyObservers(this);
  20087. var engine = this.getScene().getEngine();
  20088. // Draw order
  20089. switch (fillMode) {
  20090. case BABYLON.Material.PointFillMode:
  20091. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20092. break;
  20093. case BABYLON.Material.WireFrameFillMode:
  20094. if (this._unIndexed) {
  20095. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20096. }
  20097. else {
  20098. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20099. }
  20100. break;
  20101. default:
  20102. if (this._unIndexed) {
  20103. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20104. }
  20105. else {
  20106. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20107. }
  20108. }
  20109. return this;
  20110. };
  20111. /**
  20112. * Registers for this mesh a javascript function called just before the rendering process.
  20113. * This function is passed the current mesh.
  20114. * Return the Mesh.
  20115. */
  20116. Mesh.prototype.registerBeforeRender = function (func) {
  20117. this.onBeforeRenderObservable.add(func);
  20118. return this;
  20119. };
  20120. /**
  20121. * Disposes a previously registered javascript function called before the rendering.
  20122. * This function is passed the current mesh.
  20123. * Returns the Mesh.
  20124. */
  20125. Mesh.prototype.unregisterBeforeRender = function (func) {
  20126. this.onBeforeRenderObservable.removeCallback(func);
  20127. return this;
  20128. };
  20129. /**
  20130. * Registers for this mesh a javascript function called just after the rendering is complete.
  20131. * This function is passed the current mesh.
  20132. * Returns the Mesh.
  20133. */
  20134. Mesh.prototype.registerAfterRender = function (func) {
  20135. this.onAfterRenderObservable.add(func);
  20136. return this;
  20137. };
  20138. /**
  20139. * Disposes a previously registered javascript function called after the rendering.
  20140. * This function is passed the current mesh.
  20141. * Return the Mesh.
  20142. */
  20143. Mesh.prototype.unregisterAfterRender = function (func) {
  20144. this.onAfterRenderObservable.removeCallback(func);
  20145. return this;
  20146. };
  20147. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20148. var scene = this.getScene();
  20149. this._batchCache.mustReturn = false;
  20150. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20151. this._batchCache.visibleInstances[subMeshId] = null;
  20152. if (this._visibleInstances) {
  20153. var currentRenderId = scene.getRenderId();
  20154. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20155. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20156. var selfRenderId = this._renderId;
  20157. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20158. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20159. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20160. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20161. }
  20162. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20163. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20164. this._batchCache.mustReturn = true;
  20165. return this._batchCache;
  20166. }
  20167. if (currentRenderId !== selfRenderId) {
  20168. this._batchCache.renderSelf[subMeshId] = false;
  20169. }
  20170. }
  20171. this._renderIdForInstances[subMeshId] = currentRenderId;
  20172. }
  20173. return this._batchCache;
  20174. };
  20175. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20176. var visibleInstances = batch.visibleInstances[subMesh._id];
  20177. var matricesCount = visibleInstances.length + 1;
  20178. var bufferSize = matricesCount * 16 * 4;
  20179. var currentInstancesBufferSize = this._instancesBufferSize;
  20180. var instancesBuffer = this._instancesBuffer;
  20181. while (this._instancesBufferSize < bufferSize) {
  20182. this._instancesBufferSize *= 2;
  20183. }
  20184. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20185. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20186. }
  20187. var offset = 0;
  20188. var instancesCount = 0;
  20189. var world = this.getWorldMatrix();
  20190. if (batch.renderSelf[subMesh._id]) {
  20191. world.copyToArray(this._instancesData, offset);
  20192. offset += 16;
  20193. instancesCount++;
  20194. }
  20195. if (visibleInstances) {
  20196. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20197. var instance = visibleInstances[instanceIndex];
  20198. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20199. offset += 16;
  20200. instancesCount++;
  20201. }
  20202. }
  20203. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20204. if (instancesBuffer) {
  20205. instancesBuffer.dispose();
  20206. }
  20207. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20208. this._instancesBuffer = instancesBuffer;
  20209. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20210. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20211. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20212. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20213. }
  20214. else {
  20215. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20216. }
  20217. this.geometry._bind(effect);
  20218. this._draw(subMesh, fillMode, instancesCount);
  20219. engine.unbindInstanceAttributes();
  20220. return this;
  20221. };
  20222. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20223. var scene = this.getScene();
  20224. var engine = scene.getEngine();
  20225. if (hardwareInstancedRendering) {
  20226. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20227. }
  20228. else {
  20229. if (batch.renderSelf[subMesh._id]) {
  20230. // Draw
  20231. if (onBeforeDraw) {
  20232. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20233. }
  20234. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20235. }
  20236. if (batch.visibleInstances[subMesh._id]) {
  20237. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20238. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20239. // World
  20240. var world = instance.getWorldMatrix();
  20241. if (onBeforeDraw) {
  20242. onBeforeDraw(true, world, effectiveMaterial);
  20243. }
  20244. // Draw
  20245. this._draw(subMesh, fillMode);
  20246. }
  20247. }
  20248. }
  20249. return this;
  20250. };
  20251. /**
  20252. * Triggers the draw call for the mesh.
  20253. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20254. * Returns the Mesh.
  20255. */
  20256. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20257. var scene = this.getScene();
  20258. // Managing instances
  20259. var batch = this._getInstancesRenderList(subMesh._id);
  20260. if (batch.mustReturn) {
  20261. return this;
  20262. }
  20263. // Checking geometry state
  20264. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20265. return this;
  20266. }
  20267. var callbackIndex;
  20268. this.onBeforeRenderObservable.notifyObservers(this);
  20269. var engine = scene.getEngine();
  20270. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20271. // Material
  20272. var effectiveMaterial = subMesh.getMaterial();
  20273. if (!effectiveMaterial) {
  20274. return this;
  20275. }
  20276. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20277. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20278. return this;
  20279. }
  20280. }
  20281. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20282. return this;
  20283. }
  20284. // Outline - step 1
  20285. var savedDepthWrite = engine.getDepthWrite();
  20286. if (this.renderOutline) {
  20287. engine.setDepthWrite(false);
  20288. scene.getOutlineRenderer().render(subMesh, batch);
  20289. engine.setDepthWrite(savedDepthWrite);
  20290. }
  20291. var effect;
  20292. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20293. effect = subMesh.effect;
  20294. }
  20295. else {
  20296. effect = effectiveMaterial.getEffect();
  20297. }
  20298. effectiveMaterial._preBind(effect);
  20299. // Bind
  20300. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20301. this._bind(subMesh, effect, fillMode);
  20302. var world = this.getWorldMatrix();
  20303. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20304. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20305. }
  20306. else {
  20307. effectiveMaterial.bind(world, this);
  20308. }
  20309. // Alpha mode
  20310. if (enableAlphaMode) {
  20311. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20312. }
  20313. // Draw
  20314. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20315. // Unbind
  20316. effectiveMaterial.unbind();
  20317. // Outline - step 2
  20318. if (this.renderOutline && savedDepthWrite) {
  20319. engine.setDepthWrite(true);
  20320. engine.setColorWrite(false);
  20321. scene.getOutlineRenderer().render(subMesh, batch);
  20322. engine.setColorWrite(true);
  20323. }
  20324. // Overlay
  20325. if (this.renderOverlay) {
  20326. var currentMode = engine.getAlphaMode();
  20327. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20328. scene.getOutlineRenderer().render(subMesh, batch, true);
  20329. engine.setAlphaMode(currentMode);
  20330. }
  20331. this.onAfterRenderObservable.notifyObservers(this);
  20332. return this;
  20333. };
  20334. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20335. if (isInstance) {
  20336. effectiveMaterial.bindOnlyWorldMatrix(world);
  20337. }
  20338. return this;
  20339. };
  20340. /**
  20341. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20342. */
  20343. Mesh.prototype.getEmittedParticleSystems = function () {
  20344. var results = new Array();
  20345. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20346. var particleSystem = this.getScene().particleSystems[index];
  20347. if (particleSystem.emitter === this) {
  20348. results.push(particleSystem);
  20349. }
  20350. }
  20351. return results;
  20352. };
  20353. /**
  20354. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20355. */
  20356. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20357. var results = new Array();
  20358. var descendants = this.getDescendants();
  20359. descendants.push(this);
  20360. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20361. var particleSystem = this.getScene().particleSystems[index];
  20362. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20363. results.push(particleSystem);
  20364. }
  20365. }
  20366. return results;
  20367. };
  20368. Mesh.prototype._checkDelayState = function () {
  20369. var scene = this.getScene();
  20370. if (this._geometry) {
  20371. this._geometry.load(scene);
  20372. }
  20373. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20374. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20375. this._queueLoad(this, scene);
  20376. }
  20377. return this;
  20378. };
  20379. Mesh.prototype._queueLoad = function (mesh, scene) {
  20380. var _this = this;
  20381. scene._addPendingData(mesh);
  20382. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20383. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20384. if (data instanceof ArrayBuffer) {
  20385. _this._delayLoadingFunction(data, _this);
  20386. }
  20387. else {
  20388. _this._delayLoadingFunction(JSON.parse(data), _this);
  20389. }
  20390. _this.instances.forEach(function (instance) {
  20391. instance._syncSubMeshes();
  20392. });
  20393. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20394. scene._removePendingData(_this);
  20395. }, function () { }, scene.database, getBinaryData);
  20396. return this;
  20397. };
  20398. /**
  20399. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20400. */
  20401. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20402. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20403. return false;
  20404. }
  20405. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20406. return false;
  20407. }
  20408. this._checkDelayState();
  20409. return true;
  20410. };
  20411. /**
  20412. * Sets the mesh material by the material or multiMaterial `id` property.
  20413. * The material `id` is a string identifying the material or the multiMaterial.
  20414. * This method returns the Mesh.
  20415. */
  20416. Mesh.prototype.setMaterialByID = function (id) {
  20417. var materials = this.getScene().materials;
  20418. var index;
  20419. for (index = materials.length - 1; index > -1; index--) {
  20420. if (materials[index].id === id) {
  20421. this.material = materials[index];
  20422. return this;
  20423. }
  20424. }
  20425. // Multi
  20426. var multiMaterials = this.getScene().multiMaterials;
  20427. for (index = multiMaterials.length - 1; index > -1; index--) {
  20428. if (multiMaterials[index].id === id) {
  20429. this.material = multiMaterials[index];
  20430. return this;
  20431. }
  20432. }
  20433. return this;
  20434. };
  20435. /**
  20436. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20437. */
  20438. Mesh.prototype.getAnimatables = function () {
  20439. var results = [];
  20440. if (this.material) {
  20441. results.push(this.material);
  20442. }
  20443. if (this.skeleton) {
  20444. results.push(this.skeleton);
  20445. }
  20446. return results;
  20447. };
  20448. /**
  20449. * Modifies the mesh geometry according to the passed transformation matrix.
  20450. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20451. * The mesh normals are modified accordingly the same transformation.
  20452. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20453. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20454. * Returns the Mesh.
  20455. */
  20456. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20457. // Position
  20458. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20459. return this;
  20460. }
  20461. var submeshes = this.subMeshes.splice(0);
  20462. this._resetPointsArrayCache();
  20463. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20464. var temp = [];
  20465. var index;
  20466. for (index = 0; index < data.length; index += 3) {
  20467. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20468. }
  20469. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20470. // Normals
  20471. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20472. return this;
  20473. }
  20474. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20475. temp = [];
  20476. for (index = 0; index < data.length; index += 3) {
  20477. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20478. }
  20479. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20480. // flip faces?
  20481. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20482. this.flipFaces();
  20483. }
  20484. // Restore submeshes
  20485. this.releaseSubMeshes();
  20486. this.subMeshes = submeshes;
  20487. return this;
  20488. };
  20489. /**
  20490. * Modifies the mesh geometry according to its own current World Matrix.
  20491. * The mesh World Matrix is then reset.
  20492. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20493. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20494. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20495. * Returns the Mesh.
  20496. */
  20497. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20498. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20499. this.scaling.copyFromFloats(1, 1, 1);
  20500. this.position.copyFromFloats(0, 0, 0);
  20501. this.rotation.copyFromFloats(0, 0, 0);
  20502. //only if quaternion is already set
  20503. if (this.rotationQuaternion) {
  20504. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20505. }
  20506. this._worldMatrix = BABYLON.Matrix.Identity();
  20507. return this;
  20508. };
  20509. Object.defineProperty(Mesh.prototype, "_positions", {
  20510. // Cache
  20511. get: function () {
  20512. if (this._geometry) {
  20513. return this._geometry._positions;
  20514. }
  20515. return null;
  20516. },
  20517. enumerable: true,
  20518. configurable: true
  20519. });
  20520. Mesh.prototype._resetPointsArrayCache = function () {
  20521. if (this._geometry) {
  20522. this._geometry._resetPointsArrayCache();
  20523. }
  20524. return this;
  20525. };
  20526. Mesh.prototype._generatePointsArray = function () {
  20527. if (this._geometry) {
  20528. return this._geometry._generatePointsArray();
  20529. }
  20530. return false;
  20531. };
  20532. /**
  20533. * Returns a new Mesh object generated from the current mesh properties.
  20534. * This method must not get confused with createInstance().
  20535. * The parameter `name` is a string, the name given to the new mesh.
  20536. * The optional parameter `newParent` can be any Node object (default `null`).
  20537. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20538. * 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.
  20539. */
  20540. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20541. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20542. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20543. };
  20544. /**
  20545. * Disposes the mesh.
  20546. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20547. */
  20548. Mesh.prototype.dispose = function (doNotRecurse) {
  20549. var _this = this;
  20550. this.morphTargetManager = undefined;
  20551. if (this._geometry) {
  20552. this._geometry.releaseForMesh(this, true);
  20553. }
  20554. // Sources
  20555. var meshes = this.getScene().meshes;
  20556. meshes.forEach(function (mesh) {
  20557. if (mesh._source && mesh._source === _this) {
  20558. mesh._source = null;
  20559. }
  20560. });
  20561. this._source = null;
  20562. // Instances
  20563. if (this._instancesBuffer) {
  20564. this._instancesBuffer.dispose();
  20565. this._instancesBuffer = null;
  20566. }
  20567. while (this.instances.length) {
  20568. this.instances[0].dispose();
  20569. }
  20570. // Highlight layers.
  20571. var highlightLayers = this.getScene().highlightLayers;
  20572. for (var i = 0; i < highlightLayers.length; i++) {
  20573. var highlightLayer = highlightLayers[i];
  20574. if (highlightLayer) {
  20575. highlightLayer.removeMesh(this);
  20576. highlightLayer.removeExcludedMesh(this);
  20577. }
  20578. }
  20579. _super.prototype.dispose.call(this, doNotRecurse);
  20580. };
  20581. /**
  20582. * Modifies the mesh geometry according to a displacement map.
  20583. * 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.
  20584. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20585. * This method returns nothing.
  20586. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20587. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20588. * 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.
  20589. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20590. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20591. *
  20592. * Returns the Mesh.
  20593. */
  20594. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20595. var _this = this;
  20596. var scene = this.getScene();
  20597. var onload = function (img) {
  20598. // Getting height map data
  20599. var canvas = document.createElement("canvas");
  20600. var context = canvas.getContext("2d");
  20601. var heightMapWidth = img.width;
  20602. var heightMapHeight = img.height;
  20603. canvas.width = heightMapWidth;
  20604. canvas.height = heightMapHeight;
  20605. context.drawImage(img, 0, 0);
  20606. // Create VertexData from map data
  20607. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20608. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20609. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20610. //execute success callback, if set
  20611. if (onSuccess) {
  20612. onSuccess(_this);
  20613. }
  20614. };
  20615. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20616. return this;
  20617. };
  20618. /**
  20619. * Modifies the mesh geometry according to a displacementMap buffer.
  20620. * 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.
  20621. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20622. * This method returns nothing.
  20623. * 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.
  20624. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20625. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20626. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20627. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20628. *
  20629. * Returns the Mesh.
  20630. */
  20631. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20632. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20633. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20634. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20635. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20636. return this;
  20637. }
  20638. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20639. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20640. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20641. var position = BABYLON.Vector3.Zero();
  20642. var normal = BABYLON.Vector3.Zero();
  20643. var uv = BABYLON.Vector2.Zero();
  20644. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20645. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20646. for (var index = 0; index < positions.length; index += 3) {
  20647. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20648. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20649. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20650. // Compute height
  20651. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20652. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20653. var pos = (u + v * heightMapWidth) * 4;
  20654. var r = buffer[pos] / 255.0;
  20655. var g = buffer[pos + 1] / 255.0;
  20656. var b = buffer[pos + 2] / 255.0;
  20657. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20658. normal.normalize();
  20659. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20660. position = position.add(normal);
  20661. position.toArray(positions, index);
  20662. }
  20663. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20664. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20665. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20666. return this;
  20667. };
  20668. /**
  20669. * Modify the mesh to get a flat shading rendering.
  20670. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20671. * This method returns the Mesh.
  20672. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20673. */
  20674. Mesh.prototype.convertToFlatShadedMesh = function () {
  20675. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20676. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20677. var kinds = this.getVerticesDataKinds();
  20678. var vbs = [];
  20679. var data = [];
  20680. var newdata = [];
  20681. var updatableNormals = false;
  20682. var kindIndex;
  20683. var kind;
  20684. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20685. kind = kinds[kindIndex];
  20686. var vertexBuffer = this.getVertexBuffer(kind);
  20687. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20688. updatableNormals = vertexBuffer.isUpdatable();
  20689. kinds.splice(kindIndex, 1);
  20690. kindIndex--;
  20691. continue;
  20692. }
  20693. vbs[kind] = vertexBuffer;
  20694. data[kind] = vbs[kind].getData();
  20695. newdata[kind] = [];
  20696. }
  20697. // Save previous submeshes
  20698. var previousSubmeshes = this.subMeshes.slice(0);
  20699. var indices = this.getIndices();
  20700. var totalIndices = this.getTotalIndices();
  20701. // Generating unique vertices per face
  20702. var index;
  20703. for (index = 0; index < totalIndices; index++) {
  20704. var vertexIndex = indices[index];
  20705. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20706. kind = kinds[kindIndex];
  20707. var stride = vbs[kind].getStrideSize();
  20708. for (var offset = 0; offset < stride; offset++) {
  20709. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20710. }
  20711. }
  20712. }
  20713. // Updating faces & normal
  20714. var normals = [];
  20715. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20716. for (index = 0; index < totalIndices; index += 3) {
  20717. indices[index] = index;
  20718. indices[index + 1] = index + 1;
  20719. indices[index + 2] = index + 2;
  20720. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20721. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20722. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20723. var p1p2 = p1.subtract(p2);
  20724. var p3p2 = p3.subtract(p2);
  20725. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20726. // Store same normals for every vertex
  20727. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20728. normals.push(normal.x);
  20729. normals.push(normal.y);
  20730. normals.push(normal.z);
  20731. }
  20732. }
  20733. this.setIndices(indices);
  20734. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20735. // Updating vertex buffers
  20736. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20737. kind = kinds[kindIndex];
  20738. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20739. }
  20740. // Updating submeshes
  20741. this.releaseSubMeshes();
  20742. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20743. var previousOne = previousSubmeshes[submeshIndex];
  20744. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20745. }
  20746. this.synchronizeInstances();
  20747. return this;
  20748. };
  20749. /**
  20750. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20751. * In other words, more vertices, no more indices and a single bigger VBO.
  20752. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20753. * Returns the Mesh.
  20754. */
  20755. Mesh.prototype.convertToUnIndexedMesh = function () {
  20756. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20757. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20758. var kinds = this.getVerticesDataKinds();
  20759. var vbs = [];
  20760. var data = [];
  20761. var newdata = [];
  20762. var updatableNormals = false;
  20763. var kindIndex;
  20764. var kind;
  20765. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20766. kind = kinds[kindIndex];
  20767. var vertexBuffer = this.getVertexBuffer(kind);
  20768. vbs[kind] = vertexBuffer;
  20769. data[kind] = vbs[kind].getData();
  20770. newdata[kind] = [];
  20771. }
  20772. // Save previous submeshes
  20773. var previousSubmeshes = this.subMeshes.slice(0);
  20774. var indices = this.getIndices();
  20775. var totalIndices = this.getTotalIndices();
  20776. // Generating unique vertices per face
  20777. var index;
  20778. for (index = 0; index < totalIndices; index++) {
  20779. var vertexIndex = indices[index];
  20780. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20781. kind = kinds[kindIndex];
  20782. var stride = vbs[kind].getStrideSize();
  20783. for (var offset = 0; offset < stride; offset++) {
  20784. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20785. }
  20786. }
  20787. }
  20788. // Updating indices
  20789. for (index = 0; index < totalIndices; index += 3) {
  20790. indices[index] = index;
  20791. indices[index + 1] = index + 1;
  20792. indices[index + 2] = index + 2;
  20793. }
  20794. this.setIndices(indices);
  20795. // Updating vertex buffers
  20796. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20797. kind = kinds[kindIndex];
  20798. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20799. }
  20800. // Updating submeshes
  20801. this.releaseSubMeshes();
  20802. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20803. var previousOne = previousSubmeshes[submeshIndex];
  20804. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20805. }
  20806. this._unIndexed = true;
  20807. this.synchronizeInstances();
  20808. return this;
  20809. };
  20810. /**
  20811. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20812. * This method returns the Mesh.
  20813. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20814. */
  20815. Mesh.prototype.flipFaces = function (flipNormals) {
  20816. if (flipNormals === void 0) { flipNormals = false; }
  20817. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20818. var i;
  20819. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20820. for (i = 0; i < vertex_data.normals.length; i++) {
  20821. vertex_data.normals[i] *= -1;
  20822. }
  20823. }
  20824. var temp;
  20825. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20826. // reassign indices
  20827. temp = vertex_data.indices[i + 1];
  20828. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20829. vertex_data.indices[i + 2] = temp;
  20830. }
  20831. vertex_data.applyToMesh(this);
  20832. return this;
  20833. };
  20834. // Instances
  20835. /**
  20836. * Creates a new InstancedMesh object from the mesh model.
  20837. * An instance shares the same properties and the same material than its model.
  20838. * Only these properties of each instance can then be set individually :
  20839. * - position
  20840. * - rotation
  20841. * - rotationQuaternion
  20842. * - setPivotMatrix
  20843. * - scaling
  20844. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20845. * Warning : this method is not supported for Line mesh and LineSystem
  20846. */
  20847. Mesh.prototype.createInstance = function (name) {
  20848. return new BABYLON.InstancedMesh(name, this);
  20849. };
  20850. /**
  20851. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20852. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20853. * This method returns the Mesh.
  20854. */
  20855. Mesh.prototype.synchronizeInstances = function () {
  20856. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20857. var instance = this.instances[instanceIndex];
  20858. instance._syncSubMeshes();
  20859. }
  20860. return this;
  20861. };
  20862. /**
  20863. * Simplify the mesh according to the given array of settings.
  20864. * Function will return immediately and will simplify async. It returns the Mesh.
  20865. * @param settings a collection of simplification settings.
  20866. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20867. * @param type the type of simplification to run.
  20868. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20869. */
  20870. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20871. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20872. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20873. this.getScene().simplificationQueue.addTask({
  20874. settings: settings,
  20875. parallelProcessing: parallelProcessing,
  20876. mesh: this,
  20877. simplificationType: simplificationType,
  20878. successCallback: successCallback
  20879. });
  20880. return this;
  20881. };
  20882. /**
  20883. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20884. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20885. * This should be used together with the simplification to avoid disappearing triangles.
  20886. * Returns the Mesh.
  20887. * @param successCallback an optional success callback to be called after the optimization finished.
  20888. */
  20889. Mesh.prototype.optimizeIndices = function (successCallback) {
  20890. var _this = this;
  20891. var indices = this.getIndices();
  20892. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20893. var vectorPositions = [];
  20894. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20895. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20896. }
  20897. var dupes = [];
  20898. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20899. var realPos = vectorPositions.length - 1 - iteration;
  20900. var testedPosition = vectorPositions[realPos];
  20901. for (var j = 0; j < realPos; ++j) {
  20902. var againstPosition = vectorPositions[j];
  20903. if (testedPosition.equals(againstPosition)) {
  20904. dupes[realPos] = j;
  20905. break;
  20906. }
  20907. }
  20908. }, function () {
  20909. for (var i = 0; i < indices.length; ++i) {
  20910. indices[i] = dupes[indices[i]] || indices[i];
  20911. }
  20912. //indices are now reordered
  20913. var originalSubMeshes = _this.subMeshes.slice(0);
  20914. _this.setIndices(indices);
  20915. _this.subMeshes = originalSubMeshes;
  20916. if (successCallback) {
  20917. successCallback(_this);
  20918. }
  20919. });
  20920. return this;
  20921. };
  20922. Mesh.prototype.serialize = function (serializationObject) {
  20923. serializationObject.name = this.name;
  20924. serializationObject.id = this.id;
  20925. serializationObject.type = this.getClassName();
  20926. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20927. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20928. }
  20929. serializationObject.position = this.position.asArray();
  20930. if (this.rotationQuaternion) {
  20931. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  20932. }
  20933. else if (this.rotation) {
  20934. serializationObject.rotation = this.rotation.asArray();
  20935. }
  20936. serializationObject.scaling = this.scaling.asArray();
  20937. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20938. serializationObject.isEnabled = this.isEnabled();
  20939. serializationObject.isVisible = this.isVisible;
  20940. serializationObject.infiniteDistance = this.infiniteDistance;
  20941. serializationObject.pickable = this.isPickable;
  20942. serializationObject.receiveShadows = this.receiveShadows;
  20943. serializationObject.billboardMode = this.billboardMode;
  20944. serializationObject.visibility = this.visibility;
  20945. serializationObject.checkCollisions = this.checkCollisions;
  20946. serializationObject.isBlocker = this.isBlocker;
  20947. // Parent
  20948. if (this.parent) {
  20949. serializationObject.parentId = this.parent.id;
  20950. }
  20951. // Geometry
  20952. var geometry = this._geometry;
  20953. if (geometry) {
  20954. var geometryId = geometry.id;
  20955. serializationObject.geometryId = geometryId;
  20956. // SubMeshes
  20957. serializationObject.subMeshes = [];
  20958. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20959. var subMesh = this.subMeshes[subIndex];
  20960. serializationObject.subMeshes.push({
  20961. materialIndex: subMesh.materialIndex,
  20962. verticesStart: subMesh.verticesStart,
  20963. verticesCount: subMesh.verticesCount,
  20964. indexStart: subMesh.indexStart,
  20965. indexCount: subMesh.indexCount
  20966. });
  20967. }
  20968. }
  20969. // Material
  20970. if (this.material) {
  20971. serializationObject.materialId = this.material.id;
  20972. }
  20973. else {
  20974. this.material = null;
  20975. }
  20976. // Morph targets
  20977. if (this.morphTargetManager) {
  20978. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  20979. }
  20980. // Skeleton
  20981. if (this.skeleton) {
  20982. serializationObject.skeletonId = this.skeleton.id;
  20983. }
  20984. // Physics
  20985. //TODO implement correct serialization for physics impostors.
  20986. if (this.getPhysicsImpostor()) {
  20987. var impostor = this.getPhysicsImpostor();
  20988. serializationObject.physicsMass = impostor.getParam("mass");
  20989. serializationObject.physicsFriction = impostor.getParam("friction");
  20990. serializationObject.physicsRestitution = impostor.getParam("mass");
  20991. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  20992. }
  20993. // Metadata
  20994. if (this.metadata) {
  20995. serializationObject.metadata = this.metadata;
  20996. }
  20997. // Instances
  20998. serializationObject.instances = [];
  20999. for (var index = 0; index < this.instances.length; index++) {
  21000. var instance = this.instances[index];
  21001. var serializationInstance = {
  21002. name: instance.name,
  21003. position: instance.position.asArray(),
  21004. scaling: instance.scaling.asArray()
  21005. };
  21006. if (instance.rotationQuaternion) {
  21007. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21008. }
  21009. else if (instance.rotation) {
  21010. serializationInstance.rotation = instance.rotation.asArray();
  21011. }
  21012. serializationObject.instances.push(serializationInstance);
  21013. // Animations
  21014. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21015. serializationInstance.ranges = instance.serializeAnimationRanges();
  21016. }
  21017. //
  21018. // Animations
  21019. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21020. serializationObject.ranges = this.serializeAnimationRanges();
  21021. // Layer mask
  21022. serializationObject.layerMask = this.layerMask;
  21023. // Alpha
  21024. serializationObject.alphaIndex = this.alphaIndex;
  21025. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21026. // Overlay
  21027. serializationObject.overlayAlpha = this.overlayAlpha;
  21028. serializationObject.overlayColor = this.overlayColor.asArray();
  21029. serializationObject.renderOverlay = this.renderOverlay;
  21030. // Fog
  21031. serializationObject.applyFog = this.applyFog;
  21032. // Action Manager
  21033. if (this.actionManager) {
  21034. serializationObject.actions = this.actionManager.serialize(this.name);
  21035. }
  21036. };
  21037. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21038. if (!this.geometry) {
  21039. return;
  21040. }
  21041. this._markSubMeshesAsAttributesDirty();
  21042. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21043. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21044. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21045. this.morphTargetManager = undefined;
  21046. return;
  21047. }
  21048. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21049. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21050. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21051. if (morphTarget.hasNormals) {
  21052. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21053. }
  21054. if (morphTarget.hasTangents) {
  21055. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21056. }
  21057. }
  21058. }
  21059. else {
  21060. var index = 0;
  21061. // Positions
  21062. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21063. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21064. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21065. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21066. }
  21067. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21068. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21069. }
  21070. index++;
  21071. }
  21072. }
  21073. };
  21074. // Statics
  21075. /**
  21076. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21077. * The parameter `parsedMesh` is the mesh to be copied.
  21078. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21079. */
  21080. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21081. var mesh;
  21082. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21083. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21084. }
  21085. else {
  21086. mesh = new Mesh(parsedMesh.name, scene);
  21087. }
  21088. mesh.id = parsedMesh.id;
  21089. if (BABYLON.Tags) {
  21090. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21091. }
  21092. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21093. if (parsedMesh.metadata !== undefined) {
  21094. mesh.metadata = parsedMesh.metadata;
  21095. }
  21096. if (parsedMesh.rotationQuaternion) {
  21097. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21098. }
  21099. else if (parsedMesh.rotation) {
  21100. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21101. }
  21102. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21103. if (parsedMesh.localMatrix) {
  21104. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21105. }
  21106. else if (parsedMesh.pivotMatrix) {
  21107. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21108. }
  21109. mesh.setEnabled(parsedMesh.isEnabled);
  21110. mesh.isVisible = parsedMesh.isVisible;
  21111. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21112. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21113. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21114. if (parsedMesh.applyFog !== undefined) {
  21115. mesh.applyFog = parsedMesh.applyFog;
  21116. }
  21117. if (parsedMesh.pickable !== undefined) {
  21118. mesh.isPickable = parsedMesh.pickable;
  21119. }
  21120. if (parsedMesh.alphaIndex !== undefined) {
  21121. mesh.alphaIndex = parsedMesh.alphaIndex;
  21122. }
  21123. mesh.receiveShadows = parsedMesh.receiveShadows;
  21124. mesh.billboardMode = parsedMesh.billboardMode;
  21125. if (parsedMesh.visibility !== undefined) {
  21126. mesh.visibility = parsedMesh.visibility;
  21127. }
  21128. mesh.checkCollisions = parsedMesh.checkCollisions;
  21129. if (parsedMesh.isBlocker !== undefined) {
  21130. mesh.isBlocker = parsedMesh.isBlocker;
  21131. }
  21132. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21133. // freezeWorldMatrix
  21134. if (parsedMesh.freezeWorldMatrix) {
  21135. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21136. }
  21137. // Parent
  21138. if (parsedMesh.parentId) {
  21139. mesh._waitingParentId = parsedMesh.parentId;
  21140. }
  21141. // Actions
  21142. if (parsedMesh.actions !== undefined) {
  21143. mesh._waitingActions = parsedMesh.actions;
  21144. }
  21145. // Overlay
  21146. if (parsedMesh.overlayAlpha !== undefined) {
  21147. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21148. }
  21149. if (parsedMesh.overlayColor !== undefined) {
  21150. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21151. }
  21152. if (parsedMesh.renderOverlay !== undefined) {
  21153. mesh.renderOverlay = parsedMesh.renderOverlay;
  21154. }
  21155. // Geometry
  21156. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21157. if (parsedMesh.delayLoadingFile) {
  21158. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21159. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21160. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21161. if (parsedMesh._binaryInfo) {
  21162. mesh._binaryInfo = parsedMesh._binaryInfo;
  21163. }
  21164. mesh._delayInfo = [];
  21165. if (parsedMesh.hasUVs) {
  21166. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21167. }
  21168. if (parsedMesh.hasUVs2) {
  21169. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21170. }
  21171. if (parsedMesh.hasUVs3) {
  21172. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21173. }
  21174. if (parsedMesh.hasUVs4) {
  21175. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21176. }
  21177. if (parsedMesh.hasUVs5) {
  21178. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21179. }
  21180. if (parsedMesh.hasUVs6) {
  21181. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21182. }
  21183. if (parsedMesh.hasColors) {
  21184. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21185. }
  21186. if (parsedMesh.hasMatricesIndices) {
  21187. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21188. }
  21189. if (parsedMesh.hasMatricesWeights) {
  21190. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21191. }
  21192. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21193. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21194. mesh._checkDelayState();
  21195. }
  21196. }
  21197. else {
  21198. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21199. }
  21200. // Material
  21201. if (parsedMesh.materialId) {
  21202. mesh.setMaterialByID(parsedMesh.materialId);
  21203. }
  21204. else {
  21205. mesh.material = null;
  21206. }
  21207. // Morph targets
  21208. if (parsedMesh.morphTargetManagerId > -1) {
  21209. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21210. }
  21211. // Skeleton
  21212. if (parsedMesh.skeletonId > -1) {
  21213. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21214. if (parsedMesh.numBoneInfluencers) {
  21215. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21216. }
  21217. }
  21218. // Animations
  21219. if (parsedMesh.animations) {
  21220. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21221. var parsedAnimation = parsedMesh.animations[animationIndex];
  21222. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21223. }
  21224. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21225. }
  21226. if (parsedMesh.autoAnimate) {
  21227. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21228. }
  21229. // Layer Mask
  21230. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21231. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21232. }
  21233. else {
  21234. mesh.layerMask = 0x0FFFFFFF;
  21235. }
  21236. // Physics
  21237. if (parsedMesh.physicsImpostor) {
  21238. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21239. mass: parsedMesh.physicsMass,
  21240. friction: parsedMesh.physicsFriction,
  21241. restitution: parsedMesh.physicsRestitution
  21242. }, scene);
  21243. }
  21244. // Instances
  21245. if (parsedMesh.instances) {
  21246. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21247. var parsedInstance = parsedMesh.instances[index];
  21248. var instance = mesh.createInstance(parsedInstance.name);
  21249. if (BABYLON.Tags) {
  21250. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21251. }
  21252. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21253. if (parsedInstance.parentId) {
  21254. instance._waitingParentId = parsedInstance.parentId;
  21255. }
  21256. if (parsedInstance.rotationQuaternion) {
  21257. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21258. }
  21259. else if (parsedInstance.rotation) {
  21260. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21261. }
  21262. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21263. instance.checkCollisions = mesh.checkCollisions;
  21264. if (parsedMesh.animations) {
  21265. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21266. parsedAnimation = parsedMesh.animations[animationIndex];
  21267. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21268. }
  21269. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21270. }
  21271. }
  21272. }
  21273. return mesh;
  21274. };
  21275. /**
  21276. * Creates a ribbon mesh.
  21277. * Please consider using the same method from the MeshBuilder class instead.
  21278. * 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.
  21279. *
  21280. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21281. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21282. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21283. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21284. * 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.
  21285. * 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.
  21286. * 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
  21287. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21288. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21289. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21290. */
  21291. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21292. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21293. pathArray: pathArray,
  21294. closeArray: closeArray,
  21295. closePath: closePath,
  21296. offset: offset,
  21297. updatable: updatable,
  21298. sideOrientation: sideOrientation,
  21299. instance: instance
  21300. }, scene);
  21301. };
  21302. /**
  21303. * Creates a plane polygonal mesh. By default, this is a disc.
  21304. * Please consider using the same method from the MeshBuilder class instead.
  21305. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21306. * 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.
  21307. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21308. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21309. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21310. */
  21311. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21312. var options = {
  21313. radius: radius,
  21314. tessellation: tessellation,
  21315. sideOrientation: sideOrientation,
  21316. updatable: updatable
  21317. };
  21318. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21319. };
  21320. /**
  21321. * Creates a box mesh.
  21322. * Please consider using the same method from the MeshBuilder class instead.
  21323. * The parameter `size` sets the size (float) of each box side (default 1).
  21324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21327. */
  21328. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21329. var options = {
  21330. size: size,
  21331. sideOrientation: sideOrientation,
  21332. updatable: updatable
  21333. };
  21334. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21335. };
  21336. /**
  21337. * Creates a sphere mesh.
  21338. * Please consider using the same method from the MeshBuilder class instead.
  21339. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21340. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21344. */
  21345. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21346. var options = {
  21347. segments: segments,
  21348. diameterX: diameter,
  21349. diameterY: diameter,
  21350. diameterZ: diameter,
  21351. sideOrientation: sideOrientation,
  21352. updatable: updatable
  21353. };
  21354. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21355. };
  21356. /**
  21357. * Creates a cylinder or a cone mesh.
  21358. * Please consider using the same method from the MeshBuilder class instead.
  21359. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21360. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21361. * 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.
  21362. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21363. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21367. */
  21368. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21369. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21370. if (scene !== undefined) {
  21371. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21372. updatable = scene;
  21373. }
  21374. scene = subdivisions;
  21375. subdivisions = 1;
  21376. }
  21377. var options = {
  21378. height: height,
  21379. diameterTop: diameterTop,
  21380. diameterBottom: diameterBottom,
  21381. tessellation: tessellation,
  21382. subdivisions: subdivisions,
  21383. sideOrientation: sideOrientation,
  21384. updatable: updatable
  21385. };
  21386. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21387. };
  21388. // Torus (Code from SharpDX.org)
  21389. /**
  21390. * Creates a torus mesh.
  21391. * Please consider using the same method from the MeshBuilder class instead.
  21392. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21393. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21394. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21395. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21396. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21397. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21398. */
  21399. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21400. var options = {
  21401. diameter: diameter,
  21402. thickness: thickness,
  21403. tessellation: tessellation,
  21404. sideOrientation: sideOrientation,
  21405. updatable: updatable
  21406. };
  21407. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21408. };
  21409. /**
  21410. * Creates a torus knot mesh.
  21411. * Please consider using the same method from the MeshBuilder class instead.
  21412. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21413. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21414. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21415. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21416. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21417. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21418. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21419. */
  21420. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21421. var options = {
  21422. radius: radius,
  21423. tube: tube,
  21424. radialSegments: radialSegments,
  21425. tubularSegments: tubularSegments,
  21426. p: p,
  21427. q: q,
  21428. sideOrientation: sideOrientation,
  21429. updatable: updatable
  21430. };
  21431. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21432. };
  21433. /**
  21434. * Creates a line mesh.
  21435. * Please consider using the same method from the MeshBuilder class instead.
  21436. * 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.
  21437. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21438. * The parameter `points` is an array successive Vector3.
  21439. * 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
  21440. * When updating an instance, remember that only point positions can change, not the number of points.
  21441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21442. */
  21443. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21444. var options = {
  21445. points: points,
  21446. updatable: updatable,
  21447. instance: instance
  21448. };
  21449. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21450. };
  21451. /**
  21452. * Creates a dashed line mesh.
  21453. * Please consider using the same method from the MeshBuilder class instead.
  21454. * 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.
  21455. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21456. * The parameter `points` is an array successive Vector3.
  21457. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21458. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21459. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21460. * 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
  21461. * When updating an instance, remember that only point positions can change, not the number of points.
  21462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21463. */
  21464. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21465. var options = {
  21466. points: points,
  21467. dashSize: dashSize,
  21468. gapSize: gapSize,
  21469. dashNb: dashNb,
  21470. updatable: updatable,
  21471. instance: instance
  21472. };
  21473. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21474. };
  21475. /**
  21476. * Creates a polygon mesh.
  21477. * Please consider using the same method from the MeshBuilder class instead.
  21478. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21479. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  21480. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21481. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21482. * Remember you can only change the shape positions, not their number when updating a polygon.
  21483. */
  21484. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21485. var options = {
  21486. shape: shape,
  21487. holes: holes,
  21488. updatable: updatable,
  21489. sideOrientation: sideOrientation
  21490. };
  21491. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21492. };
  21493. /**
  21494. * Creates an extruded polygon mesh, with depth in the Y direction.
  21495. * Please consider using the same method from the MeshBuilder class instead.
  21496. */
  21497. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21498. var options = {
  21499. shape: shape,
  21500. holes: holes,
  21501. depth: depth,
  21502. updatable: updatable,
  21503. sideOrientation: sideOrientation
  21504. };
  21505. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21506. };
  21507. /**
  21508. * Creates an extruded shape mesh.
  21509. * 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.
  21510. * Please consider using the same method from the MeshBuilder class instead.
  21511. *
  21512. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21513. * 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
  21514. * extruded along the Z axis.
  21515. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21516. * 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.
  21517. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21518. * 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
  21519. * 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
  21520. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21521. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21522. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21524. */
  21525. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21526. var options = {
  21527. shape: shape,
  21528. path: path,
  21529. scale: scale,
  21530. rotation: rotation,
  21531. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21532. sideOrientation: sideOrientation,
  21533. instance: instance,
  21534. updatable: updatable
  21535. };
  21536. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21537. };
  21538. /**
  21539. * Creates an custom extruded shape mesh.
  21540. * 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.
  21541. * Please consider using the same method from the MeshBuilder class instead.
  21542. *
  21543. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21544. * 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
  21545. * extruded along the Z axis.
  21546. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21547. * 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
  21548. * and the distance of this point from the begining of the path :
  21549. * ```javascript
  21550. * var rotationFunction = function(i, distance) {
  21551. * // do things
  21552. * return rotationValue; }
  21553. * ```
  21554. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21555. * 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
  21556. * and the distance of this point from the begining of the path :
  21557. * ```javascript
  21558. * var scaleFunction = function(i, distance) {
  21559. * // do things
  21560. * return scaleValue;}
  21561. * ```
  21562. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21563. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21564. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21565. * 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
  21566. * 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
  21567. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21571. */
  21572. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21573. var options = {
  21574. shape: shape,
  21575. path: path,
  21576. scaleFunction: scaleFunction,
  21577. rotationFunction: rotationFunction,
  21578. ribbonCloseArray: ribbonCloseArray,
  21579. ribbonClosePath: ribbonClosePath,
  21580. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21581. sideOrientation: sideOrientation,
  21582. instance: instance,
  21583. updatable: updatable
  21584. };
  21585. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21586. };
  21587. /**
  21588. * Creates lathe mesh.
  21589. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21590. * Please consider using the same method from the MeshBuilder class instead.
  21591. * 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
  21592. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21593. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21594. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21595. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21596. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21597. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21598. */
  21599. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21600. var options = {
  21601. shape: shape,
  21602. radius: radius,
  21603. tessellation: tessellation,
  21604. sideOrientation: sideOrientation,
  21605. updatable: updatable
  21606. };
  21607. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21608. };
  21609. /**
  21610. * Creates a plane mesh.
  21611. * Please consider using the same method from the MeshBuilder class instead.
  21612. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21613. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21614. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21616. */
  21617. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21618. var options = {
  21619. size: size,
  21620. width: size,
  21621. height: size,
  21622. sideOrientation: sideOrientation,
  21623. updatable: updatable
  21624. };
  21625. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21626. };
  21627. /**
  21628. * Creates a ground mesh.
  21629. * Please consider using the same method from the MeshBuilder class instead.
  21630. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21631. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21633. */
  21634. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21635. var options = {
  21636. width: width,
  21637. height: height,
  21638. subdivisions: subdivisions,
  21639. updatable: updatable
  21640. };
  21641. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21642. };
  21643. /**
  21644. * Creates a tiled ground mesh.
  21645. * Please consider using the same method from the MeshBuilder class instead.
  21646. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21647. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21648. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21649. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21650. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21651. * numbers of subdivisions on the ground width and height of each tile.
  21652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21653. */
  21654. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21655. var options = {
  21656. xmin: xmin,
  21657. zmin: zmin,
  21658. xmax: xmax,
  21659. zmax: zmax,
  21660. subdivisions: subdivisions,
  21661. precision: precision,
  21662. updatable: updatable
  21663. };
  21664. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21665. };
  21666. /**
  21667. * Creates a ground mesh from a height map.
  21668. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21669. * Please consider using the same method from the MeshBuilder class instead.
  21670. * The parameter `url` sets the URL of the height map image resource.
  21671. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21672. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21673. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21674. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21675. * 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).
  21676. * This function is passed the newly built mesh :
  21677. * ```javascript
  21678. * function(mesh) { // do things
  21679. * return; }
  21680. * ```
  21681. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21682. */
  21683. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21684. var options = {
  21685. width: width,
  21686. height: height,
  21687. subdivisions: subdivisions,
  21688. minHeight: minHeight,
  21689. maxHeight: maxHeight,
  21690. updatable: updatable,
  21691. onReady: onReady
  21692. };
  21693. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21694. };
  21695. /**
  21696. * Creates a tube mesh.
  21697. * 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.
  21698. * Please consider using the same method from the MeshBuilder class instead.
  21699. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21700. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21701. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21702. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21703. * 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.
  21704. * It must return a radius value (positive float) :
  21705. * ```javascript
  21706. * var radiusFunction = function(i, distance) {
  21707. * // do things
  21708. * return radius; }
  21709. * ```
  21710. * 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
  21711. * 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
  21712. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21713. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21715. */
  21716. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21717. var options = {
  21718. path: path,
  21719. radius: radius,
  21720. tessellation: tessellation,
  21721. radiusFunction: radiusFunction,
  21722. arc: 1,
  21723. cap: cap,
  21724. updatable: updatable,
  21725. sideOrientation: sideOrientation,
  21726. instance: instance
  21727. };
  21728. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21729. };
  21730. /**
  21731. * Creates a polyhedron mesh.
  21732. * Please consider using the same method from the MeshBuilder class instead.
  21733. * 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
  21734. * to choose the wanted type.
  21735. * The parameter `size` (positive float, default 1) sets the polygon size.
  21736. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21737. * 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`.
  21738. * 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
  21739. * 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)`).
  21740. * 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
  21741. * 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.
  21742. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21743. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21744. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21745. */
  21746. Mesh.CreatePolyhedron = function (name, options, scene) {
  21747. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21748. };
  21749. /**
  21750. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21751. * Please consider using the same method from the MeshBuilder class instead.
  21752. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21753. * 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`).
  21754. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21755. * 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.
  21756. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21757. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21758. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21759. */
  21760. Mesh.CreateIcoSphere = function (name, options, scene) {
  21761. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21762. };
  21763. /**
  21764. * Creates a decal mesh.
  21765. * Please consider using the same method from the MeshBuilder class instead.
  21766. * 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.
  21767. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21768. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21769. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21770. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21771. */
  21772. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21773. var options = {
  21774. position: position,
  21775. normal: normal,
  21776. size: size,
  21777. angle: angle
  21778. };
  21779. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21780. };
  21781. // Skeletons
  21782. /**
  21783. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21784. */
  21785. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21786. var source;
  21787. if (!this._sourcePositions) {
  21788. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21789. this._sourcePositions = new Float32Array(source);
  21790. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21791. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21792. }
  21793. }
  21794. return this._sourcePositions;
  21795. };
  21796. /**
  21797. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21798. */
  21799. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21800. var source;
  21801. if (!this._sourceNormals) {
  21802. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21803. this._sourceNormals = new Float32Array(source);
  21804. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21805. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21806. }
  21807. }
  21808. return this._sourceNormals;
  21809. };
  21810. /**
  21811. * Updates the vertex buffer by applying transformation from the bones.
  21812. * Returns the Mesh.
  21813. *
  21814. * @param {skeleton} skeleton to apply
  21815. */
  21816. Mesh.prototype.applySkeleton = function (skeleton) {
  21817. if (!this.geometry) {
  21818. return this;
  21819. }
  21820. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21821. return this;
  21822. }
  21823. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21824. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21825. return this;
  21826. }
  21827. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21828. return this;
  21829. }
  21830. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21831. return this;
  21832. }
  21833. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21834. return this;
  21835. }
  21836. if (!this._sourcePositions) {
  21837. var submeshes = this.subMeshes.slice();
  21838. this.setPositionsForCPUSkinning();
  21839. this.subMeshes = submeshes;
  21840. }
  21841. if (!this._sourceNormals) {
  21842. this.setNormalsForCPUSkinning();
  21843. }
  21844. // positionsData checks for not being Float32Array will only pass at most once
  21845. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21846. if (!(positionsData instanceof Float32Array)) {
  21847. positionsData = new Float32Array(positionsData);
  21848. }
  21849. // normalsData checks for not being Float32Array will only pass at most once
  21850. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21851. if (!(normalsData instanceof Float32Array)) {
  21852. normalsData = new Float32Array(normalsData);
  21853. }
  21854. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21855. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21856. var needExtras = this.numBoneInfluencers > 4;
  21857. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21858. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21859. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21860. var tempVector3 = BABYLON.Vector3.Zero();
  21861. var finalMatrix = new BABYLON.Matrix();
  21862. var tempMatrix = new BABYLON.Matrix();
  21863. var matWeightIdx = 0;
  21864. var inf;
  21865. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21866. var weight;
  21867. for (inf = 0; inf < 4; inf++) {
  21868. weight = matricesWeightsData[matWeightIdx + inf];
  21869. if (weight > 0) {
  21870. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21871. finalMatrix.addToSelf(tempMatrix);
  21872. }
  21873. else
  21874. break;
  21875. }
  21876. if (needExtras) {
  21877. for (inf = 0; inf < 4; inf++) {
  21878. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21879. if (weight > 0) {
  21880. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21881. finalMatrix.addToSelf(tempMatrix);
  21882. }
  21883. else
  21884. break;
  21885. }
  21886. }
  21887. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21888. tempVector3.toArray(positionsData, index);
  21889. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21890. tempVector3.toArray(normalsData, index);
  21891. finalMatrix.reset();
  21892. }
  21893. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21894. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21895. return this;
  21896. };
  21897. // Tools
  21898. /**
  21899. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21900. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21901. */
  21902. Mesh.MinMax = function (meshes) {
  21903. var minVector = null;
  21904. var maxVector = null;
  21905. meshes.forEach(function (mesh, index, array) {
  21906. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21907. if (!minVector) {
  21908. minVector = boundingBox.minimumWorld;
  21909. maxVector = boundingBox.maximumWorld;
  21910. }
  21911. else {
  21912. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21913. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21914. }
  21915. });
  21916. return {
  21917. min: minVector,
  21918. max: maxVector
  21919. };
  21920. };
  21921. /**
  21922. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21923. */
  21924. Mesh.Center = function (meshesOrMinMaxVector) {
  21925. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21926. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21927. };
  21928. /**
  21929. * Merge the array of meshes into a single mesh for performance reasons.
  21930. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21931. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21932. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21933. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21934. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  21935. */
  21936. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  21937. if (disposeSource === void 0) { disposeSource = true; }
  21938. var index;
  21939. if (!allow32BitsIndices) {
  21940. var totalVertices = 0;
  21941. // Counting vertices
  21942. for (index = 0; index < meshes.length; index++) {
  21943. if (meshes[index]) {
  21944. totalVertices += meshes[index].getTotalVertices();
  21945. if (totalVertices > 65536) {
  21946. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21947. return null;
  21948. }
  21949. }
  21950. }
  21951. }
  21952. // Merge
  21953. var vertexData;
  21954. var otherVertexData;
  21955. var indiceArray = new Array();
  21956. var source;
  21957. for (index = 0; index < meshes.length; index++) {
  21958. if (meshes[index]) {
  21959. meshes[index].computeWorldMatrix(true);
  21960. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21961. otherVertexData.transform(meshes[index].getWorldMatrix());
  21962. if (vertexData) {
  21963. vertexData.merge(otherVertexData);
  21964. }
  21965. else {
  21966. vertexData = otherVertexData;
  21967. source = meshes[index];
  21968. }
  21969. if (subdivideWithSubMeshes) {
  21970. indiceArray.push(meshes[index].getTotalIndices());
  21971. }
  21972. }
  21973. }
  21974. if (!meshSubclass) {
  21975. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21976. }
  21977. vertexData.applyToMesh(meshSubclass);
  21978. // Setting properties
  21979. meshSubclass.material = source.material;
  21980. meshSubclass.checkCollisions = source.checkCollisions;
  21981. // Cleaning
  21982. if (disposeSource) {
  21983. for (index = 0; index < meshes.length; index++) {
  21984. if (meshes[index]) {
  21985. meshes[index].dispose();
  21986. }
  21987. }
  21988. }
  21989. // Subdivide
  21990. if (subdivideWithSubMeshes) {
  21991. //-- Suppresions du submesh global
  21992. meshSubclass.releaseSubMeshes();
  21993. index = 0;
  21994. var offset = 0;
  21995. //-- aplique la subdivision en fonction du tableau d'indices
  21996. while (index < indiceArray.length) {
  21997. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  21998. offset += indiceArray[index];
  21999. index++;
  22000. }
  22001. }
  22002. return meshSubclass;
  22003. };
  22004. return Mesh;
  22005. }(BABYLON.AbstractMesh));
  22006. // Consts
  22007. Mesh._FRONTSIDE = 0;
  22008. Mesh._BACKSIDE = 1;
  22009. Mesh._DOUBLESIDE = 2;
  22010. Mesh._DEFAULTSIDE = 0;
  22011. Mesh._NO_CAP = 0;
  22012. Mesh._CAP_START = 1;
  22013. Mesh._CAP_END = 2;
  22014. Mesh._CAP_ALL = 3;
  22015. BABYLON.Mesh = Mesh;
  22016. })(BABYLON || (BABYLON = {}));
  22017. //# sourceMappingURL=babylon.mesh.js.map
  22018. var BABYLON;
  22019. (function (BABYLON) {
  22020. var SubMesh = (function () {
  22021. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22022. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22023. this.materialIndex = materialIndex;
  22024. this.verticesStart = verticesStart;
  22025. this.verticesCount = verticesCount;
  22026. this.indexStart = indexStart;
  22027. this.indexCount = indexCount;
  22028. this._renderId = 0;
  22029. this._mesh = mesh;
  22030. this._renderingMesh = renderingMesh || mesh;
  22031. mesh.subMeshes.push(this);
  22032. this._trianglePlanes = [];
  22033. this._id = mesh.subMeshes.length - 1;
  22034. if (createBoundingBox) {
  22035. this.refreshBoundingInfo();
  22036. mesh.computeWorldMatrix(true);
  22037. }
  22038. }
  22039. Object.defineProperty(SubMesh.prototype, "effect", {
  22040. get: function () {
  22041. return this._materialEffect;
  22042. },
  22043. enumerable: true,
  22044. configurable: true
  22045. });
  22046. SubMesh.prototype.setEffect = function (effect, defines) {
  22047. if (this._materialEffect === effect) {
  22048. return;
  22049. }
  22050. this._materialDefines = defines;
  22051. this._materialEffect = effect;
  22052. };
  22053. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22054. get: function () {
  22055. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22056. },
  22057. enumerable: true,
  22058. configurable: true
  22059. });
  22060. /**
  22061. * Returns the submesh BoudingInfo object.
  22062. */
  22063. SubMesh.prototype.getBoundingInfo = function () {
  22064. if (this.IsGlobal) {
  22065. return this._mesh.getBoundingInfo();
  22066. }
  22067. return this._boundingInfo;
  22068. };
  22069. /**
  22070. * Sets the submesh BoundingInfo.
  22071. * Return the SubMesh.
  22072. */
  22073. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22074. this._boundingInfo = boundingInfo;
  22075. return this;
  22076. };
  22077. /**
  22078. * Returns the mesh of the current submesh.
  22079. */
  22080. SubMesh.prototype.getMesh = function () {
  22081. return this._mesh;
  22082. };
  22083. /**
  22084. * Returns the rendering mesh of the submesh.
  22085. */
  22086. SubMesh.prototype.getRenderingMesh = function () {
  22087. return this._renderingMesh;
  22088. };
  22089. /**
  22090. * Returns the submesh material.
  22091. */
  22092. SubMesh.prototype.getMaterial = function () {
  22093. var rootMaterial = this._renderingMesh.material;
  22094. if (rootMaterial && rootMaterial.getSubMaterial) {
  22095. var multiMaterial = rootMaterial;
  22096. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22097. if (this._currentMaterial !== effectiveMaterial) {
  22098. this._currentMaterial = effectiveMaterial;
  22099. if (this._materialDefines) {
  22100. this._materialDefines.markAllAsDirty();
  22101. }
  22102. }
  22103. return effectiveMaterial;
  22104. }
  22105. if (!rootMaterial) {
  22106. return this._mesh.getScene().defaultMaterial;
  22107. }
  22108. return rootMaterial;
  22109. };
  22110. // Methods
  22111. /**
  22112. * Sets a new updated BoundingInfo object to the submesh.
  22113. * Returns the SubMesh.
  22114. */
  22115. SubMesh.prototype.refreshBoundingInfo = function () {
  22116. this._lastColliderWorldVertices = null;
  22117. if (this.IsGlobal) {
  22118. return;
  22119. }
  22120. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22121. if (!data) {
  22122. this._boundingInfo = this._mesh._boundingInfo;
  22123. return;
  22124. }
  22125. var indices = this._renderingMesh.getIndices();
  22126. var extend;
  22127. //is this the only submesh?
  22128. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22129. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22130. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22131. }
  22132. else {
  22133. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22134. }
  22135. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22136. return this;
  22137. };
  22138. SubMesh.prototype._checkCollision = function (collider) {
  22139. return this.getBoundingInfo()._checkCollision(collider);
  22140. };
  22141. /**
  22142. * Updates the submesh BoundingInfo.
  22143. * Returns the Submesh.
  22144. */
  22145. SubMesh.prototype.updateBoundingInfo = function (world) {
  22146. if (!this.getBoundingInfo()) {
  22147. this.refreshBoundingInfo();
  22148. }
  22149. this.getBoundingInfo().update(world);
  22150. return this;
  22151. };
  22152. /**
  22153. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22154. * Boolean returned.
  22155. */
  22156. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22157. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22158. };
  22159. /**
  22160. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22161. * Boolean returned.
  22162. */
  22163. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22164. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22165. };
  22166. /**
  22167. * Renders the submesh.
  22168. * Returns it.
  22169. */
  22170. SubMesh.prototype.render = function (enableAlphaMode) {
  22171. this._renderingMesh.render(this, enableAlphaMode);
  22172. return this;
  22173. };
  22174. /**
  22175. * Returns a new Index Buffer.
  22176. * Type returned : WebGLBuffer.
  22177. */
  22178. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22179. if (!this._linesIndexBuffer) {
  22180. var linesIndices = [];
  22181. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22182. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22183. }
  22184. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22185. this.linesIndexCount = linesIndices.length;
  22186. }
  22187. return this._linesIndexBuffer;
  22188. };
  22189. /**
  22190. * True is the passed Ray intersects the submesh bounding box.
  22191. * Boolean returned.
  22192. */
  22193. SubMesh.prototype.canIntersects = function (ray) {
  22194. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22195. };
  22196. /**
  22197. * Returns an object IntersectionInfo.
  22198. */
  22199. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22200. var intersectInfo = null;
  22201. // LineMesh first as it's also a Mesh...
  22202. if (this._mesh instanceof BABYLON.LinesMesh) {
  22203. var lineMesh = this._mesh;
  22204. // Line test
  22205. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22206. var p0 = positions[indices[index]];
  22207. var p1 = positions[indices[index + 1]];
  22208. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22209. if (length < 0) {
  22210. continue;
  22211. }
  22212. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22213. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22214. if (fastCheck) {
  22215. break;
  22216. }
  22217. }
  22218. }
  22219. }
  22220. else {
  22221. // Triangles test
  22222. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22223. var p0 = positions[indices[index]];
  22224. var p1 = positions[indices[index + 1]];
  22225. var p2 = positions[indices[index + 2]];
  22226. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22227. if (currentIntersectInfo) {
  22228. if (currentIntersectInfo.distance < 0) {
  22229. continue;
  22230. }
  22231. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22232. intersectInfo = currentIntersectInfo;
  22233. intersectInfo.faceId = index / 3;
  22234. if (fastCheck) {
  22235. break;
  22236. }
  22237. }
  22238. }
  22239. }
  22240. }
  22241. return intersectInfo;
  22242. };
  22243. // Clone
  22244. /**
  22245. * Creates a new Submesh from the passed Mesh.
  22246. */
  22247. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22248. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22249. if (!this.IsGlobal) {
  22250. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22251. }
  22252. return result;
  22253. };
  22254. // Dispose
  22255. /**
  22256. * Disposes the Submesh.
  22257. * Returns nothing.
  22258. */
  22259. SubMesh.prototype.dispose = function () {
  22260. if (this._linesIndexBuffer) {
  22261. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22262. this._linesIndexBuffer = null;
  22263. }
  22264. // Remove from mesh
  22265. var index = this._mesh.subMeshes.indexOf(this);
  22266. this._mesh.subMeshes.splice(index, 1);
  22267. };
  22268. // Statics
  22269. /**
  22270. * Creates a new Submesh from the passed parameters :
  22271. * - materialIndex (integer) : the index of the main mesh material.
  22272. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22273. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22274. * - mesh (Mesh) : the main mesh to create the submesh from.
  22275. * - renderingMesh (optional Mesh) : rendering mesh.
  22276. */
  22277. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22278. var minVertexIndex = Number.MAX_VALUE;
  22279. var maxVertexIndex = -Number.MAX_VALUE;
  22280. renderingMesh = renderingMesh || mesh;
  22281. var indices = renderingMesh.getIndices();
  22282. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22283. var vertexIndex = indices[index];
  22284. if (vertexIndex < minVertexIndex)
  22285. minVertexIndex = vertexIndex;
  22286. if (vertexIndex > maxVertexIndex)
  22287. maxVertexIndex = vertexIndex;
  22288. }
  22289. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22290. };
  22291. return SubMesh;
  22292. }());
  22293. BABYLON.SubMesh = SubMesh;
  22294. })(BABYLON || (BABYLON = {}));
  22295. //# sourceMappingURL=babylon.subMesh.js.map
  22296. var BABYLON;
  22297. (function (BABYLON) {
  22298. var EffectFallbacks = (function () {
  22299. function EffectFallbacks() {
  22300. this._defines = {};
  22301. this._currentRank = 32;
  22302. this._maxRank = -1;
  22303. }
  22304. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22305. if (!this._defines[rank]) {
  22306. if (rank < this._currentRank) {
  22307. this._currentRank = rank;
  22308. }
  22309. if (rank > this._maxRank) {
  22310. this._maxRank = rank;
  22311. }
  22312. this._defines[rank] = new Array();
  22313. }
  22314. this._defines[rank].push(define);
  22315. };
  22316. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22317. this._meshRank = rank;
  22318. this._mesh = mesh;
  22319. if (rank < this._currentRank) {
  22320. this._currentRank = rank;
  22321. }
  22322. if (rank > this._maxRank) {
  22323. this._maxRank = rank;
  22324. }
  22325. };
  22326. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22327. get: function () {
  22328. return this._currentRank <= this._maxRank;
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22334. // First we try to switch to CPU skinning
  22335. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22336. this._mesh.computeBonesUsingShaders = false;
  22337. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22338. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22339. var scene = this._mesh.getScene();
  22340. for (var index = 0; index < scene.meshes.length; index++) {
  22341. var otherMesh = scene.meshes[index];
  22342. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22343. otherMesh.computeBonesUsingShaders = false;
  22344. }
  22345. }
  22346. }
  22347. else {
  22348. var currentFallbacks = this._defines[this._currentRank];
  22349. if (currentFallbacks) {
  22350. for (var index = 0; index < currentFallbacks.length; index++) {
  22351. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22352. }
  22353. }
  22354. this._currentRank++;
  22355. }
  22356. return currentDefines;
  22357. };
  22358. return EffectFallbacks;
  22359. }());
  22360. BABYLON.EffectFallbacks = EffectFallbacks;
  22361. var EffectCreationOptions = (function () {
  22362. function EffectCreationOptions() {
  22363. }
  22364. return EffectCreationOptions;
  22365. }());
  22366. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22367. var Effect = (function () {
  22368. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22369. var _this = this;
  22370. this.uniqueId = 0;
  22371. this._uniformBuffersNames = {};
  22372. this._isReady = false;
  22373. this._compilationError = "";
  22374. this._valueCache = {};
  22375. this.name = baseName;
  22376. if (attributesNamesOrOptions.attributes) {
  22377. var options = attributesNamesOrOptions;
  22378. this._engine = uniformsNamesOrEngine;
  22379. this._attributesNames = options.attributes;
  22380. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22381. this._samplers = options.samplers;
  22382. this.defines = options.defines;
  22383. this.onError = options.onError;
  22384. this.onCompiled = options.onCompiled;
  22385. this._fallbacks = options.fallbacks;
  22386. this._indexParameters = options.indexParameters;
  22387. if (options.uniformBuffersNames) {
  22388. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22389. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22390. }
  22391. }
  22392. }
  22393. else {
  22394. this._engine = engine;
  22395. this.defines = defines;
  22396. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22397. this._samplers = samplers;
  22398. this._attributesNames = attributesNamesOrOptions;
  22399. this.onError = onError;
  22400. this.onCompiled = onCompiled;
  22401. this._indexParameters = indexParameters;
  22402. this._fallbacks = fallbacks;
  22403. }
  22404. this.uniqueId = Effect._uniqueIdSeed++;
  22405. var vertexSource;
  22406. var fragmentSource;
  22407. if (baseName.vertexElement) {
  22408. vertexSource = document.getElementById(baseName.vertexElement);
  22409. if (!vertexSource) {
  22410. vertexSource = baseName.vertexElement;
  22411. }
  22412. }
  22413. else {
  22414. vertexSource = baseName.vertex || baseName;
  22415. }
  22416. if (baseName.fragmentElement) {
  22417. fragmentSource = document.getElementById(baseName.fragmentElement);
  22418. if (!fragmentSource) {
  22419. fragmentSource = baseName.fragmentElement;
  22420. }
  22421. }
  22422. else {
  22423. fragmentSource = baseName.fragment || baseName;
  22424. }
  22425. this._loadVertexShader(vertexSource, function (vertexCode) {
  22426. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22427. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22428. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22429. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22430. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22431. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22432. });
  22433. });
  22434. });
  22435. });
  22436. });
  22437. });
  22438. }
  22439. Object.defineProperty(Effect.prototype, "key", {
  22440. get: function () {
  22441. return this._key;
  22442. },
  22443. enumerable: true,
  22444. configurable: true
  22445. });
  22446. // Properties
  22447. Effect.prototype.isReady = function () {
  22448. return this._isReady;
  22449. };
  22450. Effect.prototype.getProgram = function () {
  22451. return this._program;
  22452. };
  22453. Effect.prototype.getAttributesNames = function () {
  22454. return this._attributesNames;
  22455. };
  22456. Effect.prototype.getAttributeLocation = function (index) {
  22457. return this._attributes[index];
  22458. };
  22459. Effect.prototype.getAttributeLocationByName = function (name) {
  22460. var index = this._attributesNames.indexOf(name);
  22461. return this._attributes[index];
  22462. };
  22463. Effect.prototype.getAttributesCount = function () {
  22464. return this._attributes.length;
  22465. };
  22466. Effect.prototype.getUniformIndex = function (uniformName) {
  22467. return this._uniformsNames.indexOf(uniformName);
  22468. };
  22469. Effect.prototype.getUniform = function (uniformName) {
  22470. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22471. };
  22472. Effect.prototype.getSamplers = function () {
  22473. return this._samplers;
  22474. };
  22475. Effect.prototype.getCompilationError = function () {
  22476. return this._compilationError;
  22477. };
  22478. Effect.prototype.getVertexShaderSource = function () {
  22479. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22480. };
  22481. Effect.prototype.getFragmentShaderSource = function () {
  22482. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22483. };
  22484. // Methods
  22485. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22486. // DOM element ?
  22487. if (vertex instanceof HTMLElement) {
  22488. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22489. callback(vertexCode);
  22490. return;
  22491. }
  22492. // Base64 encoded ?
  22493. if (vertex.substr(0, 7) === "base64:") {
  22494. var vertexBinary = window.atob(vertex.substr(7));
  22495. callback(vertexBinary);
  22496. return;
  22497. }
  22498. // Is in local store ?
  22499. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22500. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22501. return;
  22502. }
  22503. var vertexShaderUrl;
  22504. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22505. vertexShaderUrl = vertex;
  22506. }
  22507. else {
  22508. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22509. }
  22510. // Vertex shader
  22511. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22512. };
  22513. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22514. // DOM element ?
  22515. if (fragment instanceof HTMLElement) {
  22516. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22517. callback(fragmentCode);
  22518. return;
  22519. }
  22520. // Base64 encoded ?
  22521. if (fragment.substr(0, 7) === "base64:") {
  22522. var fragmentBinary = window.atob(fragment.substr(7));
  22523. callback(fragmentBinary);
  22524. return;
  22525. }
  22526. // Is in local store ?
  22527. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22528. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22529. return;
  22530. }
  22531. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22532. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22533. return;
  22534. }
  22535. var fragmentShaderUrl;
  22536. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22537. fragmentShaderUrl = fragment;
  22538. }
  22539. else {
  22540. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22541. }
  22542. // Fragment shader
  22543. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22544. };
  22545. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22546. // Rebuild shaders source code
  22547. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22548. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22549. vertexCode = prefix + vertexCode;
  22550. fragmentCode = prefix + fragmentCode;
  22551. // Number lines of shaders source code
  22552. var i = 2;
  22553. var regex = /\n/gm;
  22554. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22555. i = 2;
  22556. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22557. // Dump shaders name and formatted source code
  22558. if (this.name.vertexElement) {
  22559. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22560. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22561. }
  22562. else if (this.name.vertex) {
  22563. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22564. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22565. }
  22566. else {
  22567. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22568. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22569. }
  22570. };
  22571. ;
  22572. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22573. var preparedSourceCode = this._processPrecision(sourceCode);
  22574. if (this._engine.webGLVersion == 1) {
  22575. callback(preparedSourceCode);
  22576. return;
  22577. }
  22578. // Already converted
  22579. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22580. callback(preparedSourceCode.replace("#version 300 es", ""));
  22581. return;
  22582. }
  22583. // Remove extensions
  22584. // #extension GL_OES_standard_derivatives : enable
  22585. // #extension GL_EXT_shader_texture_lod : enable
  22586. // #extension GL_EXT_frag_depth : enable
  22587. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22588. var result = preparedSourceCode.replace(regex, "");
  22589. // Migrate to GLSL v300
  22590. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22591. result = result.replace(/attribute[ \t]/g, "in ");
  22592. result = result.replace(/[ \t]attribute/g, " in");
  22593. if (isFragment) {
  22594. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22595. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22596. result = result.replace(/texture2D\(/g, "texture(");
  22597. result = result.replace(/textureCube\(/g, "texture(");
  22598. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22599. result = result.replace(/gl_FragColor/g, "glFragColor");
  22600. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22601. }
  22602. callback(result);
  22603. };
  22604. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22605. var _this = this;
  22606. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22607. var match = regex.exec(sourceCode);
  22608. var returnValue = new String(sourceCode);
  22609. while (match != null) {
  22610. var includeFile = match[1];
  22611. // Uniform declaration
  22612. if (includeFile.indexOf("__decl__") !== -1) {
  22613. includeFile = includeFile.replace(/__decl__/, "");
  22614. if (this._engine.webGLVersion != 1) {
  22615. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22616. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22617. }
  22618. includeFile = includeFile + "Declaration";
  22619. }
  22620. if (Effect.IncludesShadersStore[includeFile]) {
  22621. // Substitution
  22622. var includeContent = Effect.IncludesShadersStore[includeFile];
  22623. if (match[2]) {
  22624. var splits = match[3].split(",");
  22625. for (var index = 0; index < splits.length; index += 2) {
  22626. var source = new RegExp(splits[index], "g");
  22627. var dest = splits[index + 1];
  22628. includeContent = includeContent.replace(source, dest);
  22629. }
  22630. }
  22631. if (match[4]) {
  22632. var indexString = match[5];
  22633. if (indexString.indexOf("..") !== -1) {
  22634. var indexSplits = indexString.split("..");
  22635. var minIndex = parseInt(indexSplits[0]);
  22636. var maxIndex = parseInt(indexSplits[1]);
  22637. var sourceIncludeContent = includeContent.slice(0);
  22638. includeContent = "";
  22639. if (isNaN(maxIndex)) {
  22640. maxIndex = this._indexParameters[indexSplits[1]];
  22641. }
  22642. for (var i = minIndex; i < maxIndex; i++) {
  22643. if (this._engine.webGLVersion === 1) {
  22644. // Ubo replacement
  22645. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22646. return p1 + "{X}";
  22647. });
  22648. }
  22649. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22650. }
  22651. }
  22652. else {
  22653. if (this._engine.webGLVersion === 1) {
  22654. // Ubo replacement
  22655. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22656. return p1 + "{X}";
  22657. });
  22658. }
  22659. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22660. }
  22661. }
  22662. // Replace
  22663. returnValue = returnValue.replace(match[0], includeContent);
  22664. }
  22665. else {
  22666. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22667. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22668. Effect.IncludesShadersStore[includeFile] = fileContent;
  22669. _this._processIncludes(returnValue, callback);
  22670. });
  22671. return;
  22672. }
  22673. match = regex.exec(sourceCode);
  22674. }
  22675. callback(returnValue);
  22676. };
  22677. Effect.prototype._processPrecision = function (source) {
  22678. if (source.indexOf("precision highp float") === -1) {
  22679. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22680. source = "precision mediump float;\n" + source;
  22681. }
  22682. else {
  22683. source = "precision highp float;\n" + source;
  22684. }
  22685. }
  22686. else {
  22687. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22688. source = source.replace("precision highp float", "precision mediump float");
  22689. }
  22690. }
  22691. return source;
  22692. };
  22693. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22694. try {
  22695. var engine = this._engine;
  22696. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22697. if (engine.webGLVersion > 1) {
  22698. for (var name in this._uniformBuffersNames) {
  22699. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22700. }
  22701. }
  22702. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22703. this._attributes = engine.getAttributes(this._program, attributesNames);
  22704. var index;
  22705. for (index = 0; index < this._samplers.length; index++) {
  22706. var sampler = this.getUniform(this._samplers[index]);
  22707. if (sampler == null) {
  22708. this._samplers.splice(index, 1);
  22709. index--;
  22710. }
  22711. }
  22712. engine.bindSamplers(this);
  22713. this._compilationError = "";
  22714. this._isReady = true;
  22715. if (this.onCompiled) {
  22716. this.onCompiled(this);
  22717. }
  22718. }
  22719. catch (e) {
  22720. this._compilationError = e.message;
  22721. // Let's go through fallbacks then
  22722. BABYLON.Tools.Error("Unable to compile effect:");
  22723. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22724. return " " + uniform;
  22725. }));
  22726. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22727. return " " + attribute;
  22728. }));
  22729. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22730. BABYLON.Tools.Error("Error: " + this._compilationError);
  22731. if (fallbacks && fallbacks.isMoreFallbacks) {
  22732. BABYLON.Tools.Error("Trying next fallback.");
  22733. defines = fallbacks.reduce(defines);
  22734. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22735. }
  22736. else {
  22737. if (this.onError) {
  22738. this.onError(this, this._compilationError);
  22739. }
  22740. }
  22741. }
  22742. };
  22743. Object.defineProperty(Effect.prototype, "isSupported", {
  22744. get: function () {
  22745. return this._compilationError === "";
  22746. },
  22747. enumerable: true,
  22748. configurable: true
  22749. });
  22750. Effect.prototype._bindTexture = function (channel, texture) {
  22751. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22752. };
  22753. Effect.prototype.setTexture = function (channel, texture) {
  22754. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22755. };
  22756. Effect.prototype.setTextureArray = function (channel, textures) {
  22757. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22758. var initialPos = this._samplers.indexOf(channel);
  22759. for (var index = 1; index < textures.length; index++) {
  22760. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22761. }
  22762. }
  22763. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22764. };
  22765. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22766. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22767. };
  22768. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22769. var cache = this._valueCache[uniformName];
  22770. var flag = matrix.updateFlag;
  22771. if (cache !== undefined && cache === flag) {
  22772. return false;
  22773. }
  22774. this._valueCache[uniformName] = flag;
  22775. return true;
  22776. };
  22777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22778. var cache = this._valueCache[uniformName];
  22779. if (!cache) {
  22780. cache = [x, y];
  22781. this._valueCache[uniformName] = cache;
  22782. return true;
  22783. }
  22784. var changed = false;
  22785. if (cache[0] !== x) {
  22786. cache[0] = x;
  22787. changed = true;
  22788. }
  22789. if (cache[1] !== y) {
  22790. cache[1] = y;
  22791. changed = true;
  22792. }
  22793. return changed;
  22794. };
  22795. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22796. var cache = this._valueCache[uniformName];
  22797. if (!cache) {
  22798. cache = [x, y, z];
  22799. this._valueCache[uniformName] = cache;
  22800. return true;
  22801. }
  22802. var changed = false;
  22803. if (cache[0] !== x) {
  22804. cache[0] = x;
  22805. changed = true;
  22806. }
  22807. if (cache[1] !== y) {
  22808. cache[1] = y;
  22809. changed = true;
  22810. }
  22811. if (cache[2] !== z) {
  22812. cache[2] = z;
  22813. changed = true;
  22814. }
  22815. return changed;
  22816. };
  22817. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22818. var cache = this._valueCache[uniformName];
  22819. if (!cache) {
  22820. cache = [x, y, z, w];
  22821. this._valueCache[uniformName] = cache;
  22822. return true;
  22823. }
  22824. var changed = false;
  22825. if (cache[0] !== x) {
  22826. cache[0] = x;
  22827. changed = true;
  22828. }
  22829. if (cache[1] !== y) {
  22830. cache[1] = y;
  22831. changed = true;
  22832. }
  22833. if (cache[2] !== z) {
  22834. cache[2] = z;
  22835. changed = true;
  22836. }
  22837. if (cache[3] !== w) {
  22838. cache[3] = w;
  22839. changed = true;
  22840. }
  22841. return changed;
  22842. };
  22843. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22844. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22845. return;
  22846. }
  22847. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22848. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22849. };
  22850. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22851. this._engine.bindUniformBlock(this._program, blockName, index);
  22852. };
  22853. Effect.prototype.setIntArray = function (uniformName, array) {
  22854. this._valueCache[uniformName] = null;
  22855. this._engine.setIntArray(this.getUniform(uniformName), array);
  22856. return this;
  22857. };
  22858. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22859. this._valueCache[uniformName] = null;
  22860. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22861. return this;
  22862. };
  22863. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22864. this._valueCache[uniformName] = null;
  22865. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22866. return this;
  22867. };
  22868. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22869. this._valueCache[uniformName] = null;
  22870. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22871. return this;
  22872. };
  22873. Effect.prototype.setFloatArray = function (uniformName, array) {
  22874. this._valueCache[uniformName] = null;
  22875. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22876. return this;
  22877. };
  22878. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22879. this._valueCache[uniformName] = null;
  22880. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22881. return this;
  22882. };
  22883. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22884. this._valueCache[uniformName] = null;
  22885. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22886. return this;
  22887. };
  22888. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22889. this._valueCache[uniformName] = null;
  22890. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22891. return this;
  22892. };
  22893. Effect.prototype.setArray = function (uniformName, array) {
  22894. this._valueCache[uniformName] = null;
  22895. this._engine.setArray(this.getUniform(uniformName), array);
  22896. return this;
  22897. };
  22898. Effect.prototype.setArray2 = function (uniformName, array) {
  22899. this._valueCache[uniformName] = null;
  22900. this._engine.setArray2(this.getUniform(uniformName), array);
  22901. return this;
  22902. };
  22903. Effect.prototype.setArray3 = function (uniformName, array) {
  22904. this._valueCache[uniformName] = null;
  22905. this._engine.setArray3(this.getUniform(uniformName), array);
  22906. return this;
  22907. };
  22908. Effect.prototype.setArray4 = function (uniformName, array) {
  22909. this._valueCache[uniformName] = null;
  22910. this._engine.setArray4(this.getUniform(uniformName), array);
  22911. return this;
  22912. };
  22913. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22914. if (!matrices) {
  22915. return;
  22916. }
  22917. this._valueCache[uniformName] = null;
  22918. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22919. return this;
  22920. };
  22921. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22922. if (this._cacheMatrix(uniformName, matrix)) {
  22923. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22924. }
  22925. return this;
  22926. };
  22927. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22928. this._valueCache[uniformName] = null;
  22929. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22930. return this;
  22931. };
  22932. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  22933. this._valueCache[uniformName] = null;
  22934. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  22935. return this;
  22936. };
  22937. Effect.prototype.setFloat = function (uniformName, value) {
  22938. var cache = this._valueCache[uniformName];
  22939. if (cache !== undefined && cache === value)
  22940. return this;
  22941. this._valueCache[uniformName] = value;
  22942. this._engine.setFloat(this.getUniform(uniformName), value);
  22943. return this;
  22944. };
  22945. Effect.prototype.setBool = function (uniformName, bool) {
  22946. var cache = this._valueCache[uniformName];
  22947. if (cache !== undefined && cache === bool)
  22948. return this;
  22949. this._valueCache[uniformName] = bool;
  22950. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22951. return this;
  22952. };
  22953. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22954. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  22955. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22956. }
  22957. return this;
  22958. };
  22959. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22960. if (this._cacheFloat2(uniformName, x, y)) {
  22961. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22962. }
  22963. return this;
  22964. };
  22965. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22966. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  22967. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22968. }
  22969. return this;
  22970. };
  22971. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22972. if (this._cacheFloat3(uniformName, x, y, z)) {
  22973. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22974. }
  22975. return this;
  22976. };
  22977. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22978. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  22979. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22980. }
  22981. return this;
  22982. };
  22983. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22984. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  22985. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22986. }
  22987. return this;
  22988. };
  22989. Effect.prototype.setColor3 = function (uniformName, color3) {
  22990. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  22991. this._engine.setColor3(this.getUniform(uniformName), color3);
  22992. }
  22993. return this;
  22994. };
  22995. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22996. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  22997. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22998. }
  22999. return this;
  23000. };
  23001. Effect.prototype._recombineShader = function (node) {
  23002. if (node.define) {
  23003. if (node.condition) {
  23004. var defineIndex = this.defines.indexOf("#define " + node.define);
  23005. if (defineIndex === -1) {
  23006. return null;
  23007. }
  23008. var nextComma = this.defines.indexOf("\n", defineIndex);
  23009. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23010. var condition = defineValue + node.condition;
  23011. if (!eval(condition)) {
  23012. return null;
  23013. }
  23014. }
  23015. else if (node.ndef) {
  23016. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23017. return null;
  23018. }
  23019. }
  23020. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23021. return null;
  23022. }
  23023. }
  23024. var result = "";
  23025. for (var index = 0; index < node.children.length; index++) {
  23026. var line = node.children[index];
  23027. if (line.children) {
  23028. var combined = this._recombineShader(line);
  23029. if (combined !== null) {
  23030. result += combined + "\r\n";
  23031. }
  23032. continue;
  23033. }
  23034. if (line.length > 0) {
  23035. result += line + "\r\n";
  23036. }
  23037. }
  23038. return result;
  23039. };
  23040. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23041. var root = {
  23042. children: []
  23043. };
  23044. var currentNode = root;
  23045. var lines = shaderString.split("\n");
  23046. for (var index = 0; index < lines.length; index++) {
  23047. var line = lines[index].trim();
  23048. // #ifdef
  23049. var pos = line.indexOf("#ifdef ");
  23050. if (pos !== -1) {
  23051. var define = line.substr(pos + 7);
  23052. var newNode = {
  23053. condition: null,
  23054. ndef: false,
  23055. define: define,
  23056. children: [],
  23057. parent: currentNode
  23058. };
  23059. currentNode.children.push(newNode);
  23060. currentNode = newNode;
  23061. continue;
  23062. }
  23063. // #ifndef
  23064. var pos = line.indexOf("#ifndef ");
  23065. if (pos !== -1) {
  23066. var define = line.substr(pos + 8);
  23067. newNode = {
  23068. condition: null,
  23069. define: define,
  23070. ndef: true,
  23071. children: [],
  23072. parent: currentNode
  23073. };
  23074. currentNode.children.push(newNode);
  23075. currentNode = newNode;
  23076. continue;
  23077. }
  23078. // #if
  23079. var pos = line.indexOf("#if ");
  23080. if (pos !== -1) {
  23081. var define = line.substr(pos + 4).trim();
  23082. var conditionPos = define.indexOf(" ");
  23083. newNode = {
  23084. condition: define.substr(conditionPos + 1),
  23085. define: define.substr(0, conditionPos),
  23086. ndef: false,
  23087. children: [],
  23088. parent: currentNode
  23089. };
  23090. currentNode.children.push(newNode);
  23091. currentNode = newNode;
  23092. continue;
  23093. }
  23094. // #endif
  23095. pos = line.indexOf("#endif");
  23096. if (pos !== -1) {
  23097. currentNode = currentNode.parent;
  23098. continue;
  23099. }
  23100. currentNode.children.push(line);
  23101. }
  23102. // Recombine
  23103. return this._recombineShader(root);
  23104. };
  23105. return Effect;
  23106. }());
  23107. Effect._uniqueIdSeed = 0;
  23108. Effect._baseCache = {};
  23109. // Statics
  23110. Effect.ShadersStore = {};
  23111. Effect.IncludesShadersStore = {};
  23112. BABYLON.Effect = Effect;
  23113. })(BABYLON || (BABYLON = {}));
  23114. //# sourceMappingURL=babylon.effect.js.map
  23115. var BABYLON;
  23116. (function (BABYLON) {
  23117. var MaterialHelper = (function () {
  23118. function MaterialHelper() {
  23119. }
  23120. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23121. if (defines._areMiscDirty) {
  23122. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23123. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23124. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23125. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23126. }
  23127. };
  23128. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  23129. var changed = false;
  23130. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23131. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23132. changed = true;
  23133. }
  23134. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  23135. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23136. changed = true;
  23137. }
  23138. if (defines["INSTANCES"] !== useInstances) {
  23139. defines["INSTANCES"] = useInstances;
  23140. changed = true;
  23141. }
  23142. if (changed) {
  23143. defines.markAsUnprocessed();
  23144. }
  23145. };
  23146. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23147. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23148. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23149. return;
  23150. }
  23151. defines._normals = defines._needNormals;
  23152. defines._uvs = defines._needUVs;
  23153. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23154. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23155. defines["TANGENT"] = true;
  23156. }
  23157. if (defines._needUVs) {
  23158. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23159. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23160. }
  23161. else {
  23162. defines["UV1"] = false;
  23163. defines["UV2"] = false;
  23164. }
  23165. if (useVertexColor) {
  23166. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23167. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23168. }
  23169. if (useBones) {
  23170. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23171. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23172. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23173. }
  23174. else {
  23175. defines["NUM_BONE_INFLUENCERS"] = 0;
  23176. defines["BonesPerMesh"] = 0;
  23177. }
  23178. }
  23179. if (useMorphTargets) {
  23180. if (mesh.morphTargetManager) {
  23181. var manager = mesh.morphTargetManager;
  23182. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23183. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23184. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23185. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23186. }
  23187. else {
  23188. defines["MORPHTARGETS_TANGENT"] = false;
  23189. defines["MORPHTARGETS_NORMAL"] = false;
  23190. defines["MORPHTARGETS"] = false;
  23191. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23192. }
  23193. }
  23194. };
  23195. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23196. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23197. if (disableLighting === void 0) { disableLighting = false; }
  23198. if (!defines._areLightsDirty) {
  23199. return defines._needNormals;
  23200. }
  23201. var lightIndex = 0;
  23202. var needNormals = false;
  23203. var needRebuild = false;
  23204. var lightmapMode = false;
  23205. var shadowEnabled = false;
  23206. var specularEnabled = false;
  23207. if (scene.lightsEnabled && !disableLighting) {
  23208. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23209. var light = _a[_i];
  23210. needNormals = true;
  23211. if (defines["LIGHT" + lightIndex] === undefined) {
  23212. needRebuild = true;
  23213. }
  23214. defines["LIGHT" + lightIndex] = true;
  23215. defines["SPOTLIGHT" + lightIndex] = false;
  23216. defines["HEMILIGHT" + lightIndex] = false;
  23217. defines["POINTLIGHT" + lightIndex] = false;
  23218. defines["DIRLIGHT" + lightIndex] = false;
  23219. var type;
  23220. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23221. type = "SPOTLIGHT" + lightIndex;
  23222. }
  23223. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23224. type = "HEMILIGHT" + lightIndex;
  23225. }
  23226. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23227. type = "POINTLIGHT" + lightIndex;
  23228. }
  23229. else {
  23230. type = "DIRLIGHT" + lightIndex;
  23231. }
  23232. defines[type] = true;
  23233. // Specular
  23234. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23235. specularEnabled = true;
  23236. }
  23237. // Shadows
  23238. defines["SHADOW" + lightIndex] = false;
  23239. defines["SHADOWPCF" + lightIndex] = false;
  23240. defines["SHADOWESM" + lightIndex] = false;
  23241. defines["SHADOWCUBE" + lightIndex] = false;
  23242. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23243. var shadowGenerator = light.getShadowGenerator();
  23244. if (shadowGenerator) {
  23245. shadowEnabled = true;
  23246. shadowGenerator.prepareDefines(defines, lightIndex);
  23247. }
  23248. }
  23249. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23250. lightmapMode = true;
  23251. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23252. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23253. }
  23254. else {
  23255. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23256. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23257. }
  23258. lightIndex++;
  23259. if (lightIndex === maxSimultaneousLights)
  23260. break;
  23261. }
  23262. }
  23263. defines["SPECULARTERM"] = specularEnabled;
  23264. defines["SHADOWS"] = shadowEnabled;
  23265. // Resetting all other lights if any
  23266. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23267. if (defines["LIGHT" + index] !== undefined) {
  23268. defines["LIGHT" + index] = false;
  23269. }
  23270. }
  23271. var caps = scene.getEngine().getCaps();
  23272. if (defines["SHADOWFULLFLOAT"] === undefined) {
  23273. needRebuild = true;
  23274. }
  23275. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  23276. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23277. if (needRebuild) {
  23278. defines.rebuild();
  23279. }
  23280. return needNormals;
  23281. };
  23282. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23283. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23284. var uniformsList, uniformBuffersList, samplersList, defines;
  23285. if (uniformsListOrOptions.uniformsNames) {
  23286. var options = uniformsListOrOptions;
  23287. uniformsList = options.uniformsNames;
  23288. uniformBuffersList = options.uniformBuffersNames;
  23289. samplersList = options.samplers;
  23290. defines = options.defines;
  23291. maxSimultaneousLights = options.maxSimultaneousLights;
  23292. }
  23293. else {
  23294. uniformsList = uniformsListOrOptions;
  23295. }
  23296. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23297. if (!defines["LIGHT" + lightIndex]) {
  23298. break;
  23299. }
  23300. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23301. if (uniformBuffersList) {
  23302. uniformBuffersList.push("Light" + lightIndex);
  23303. }
  23304. samplersList.push("shadowSampler" + lightIndex);
  23305. }
  23306. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23307. uniformsList.push("morphTargetInfluences");
  23308. }
  23309. };
  23310. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23311. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23312. if (!defines["SHADOWS"]) {
  23313. return;
  23314. }
  23315. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23316. if (!defines["LIGHT" + lightIndex]) {
  23317. break;
  23318. }
  23319. if (lightIndex > 0) {
  23320. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23321. }
  23322. if (defines["SHADOW" + lightIndex]) {
  23323. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23324. }
  23325. if (defines["SHADOWPCF" + lightIndex]) {
  23326. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23327. }
  23328. if (defines["SHADOWESM" + lightIndex]) {
  23329. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23330. }
  23331. }
  23332. };
  23333. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23334. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23335. if (influencers > 0) {
  23336. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23337. var manager = mesh.morphTargetManager;
  23338. var normal = manager.supportsNormals && defines["NORMAL"];
  23339. var tangent = manager.supportsTangents && defines["TANGENT"];
  23340. for (var index = 0; index < influencers; index++) {
  23341. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23342. if (normal) {
  23343. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23344. }
  23345. if (tangent) {
  23346. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23347. }
  23348. if (attribs.length > maxAttributesCount) {
  23349. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23350. }
  23351. }
  23352. }
  23353. };
  23354. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23355. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23356. fallbacks.addCPUSkinningFallback(0, mesh);
  23357. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23358. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23359. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23360. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23361. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23362. }
  23363. }
  23364. };
  23365. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23366. if (defines["INSTANCES"]) {
  23367. attribs.push("world0");
  23368. attribs.push("world1");
  23369. attribs.push("world2");
  23370. attribs.push("world3");
  23371. }
  23372. };
  23373. // Bindings
  23374. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23375. if (light.shadowEnabled && mesh.receiveShadows) {
  23376. var shadowGenerator = light.getShadowGenerator();
  23377. if (shadowGenerator) {
  23378. depthValuesAlreadySet = shadowGenerator.bindShadowLight(lightIndex, effect, depthValuesAlreadySet);
  23379. }
  23380. }
  23381. return depthValuesAlreadySet;
  23382. };
  23383. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23384. light.transferToEffect(effect, lightIndex + "");
  23385. };
  23386. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23387. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23388. var lightIndex = 0;
  23389. var depthValuesAlreadySet = false;
  23390. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23391. var light = _a[_i];
  23392. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23393. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23394. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23395. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23396. if (defines["SPECULARTERM"]) {
  23397. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23398. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23399. }
  23400. // Shadows
  23401. if (scene.shadowsEnabled) {
  23402. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  23403. }
  23404. light._uniformBuffer.update();
  23405. lightIndex++;
  23406. if (lightIndex === maxSimultaneousLights)
  23407. break;
  23408. }
  23409. };
  23410. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23411. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23412. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23413. effect.setColor3("vFogColor", scene.fogColor);
  23414. }
  23415. };
  23416. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23417. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23418. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23419. if (matrices) {
  23420. effect.setMatrices("mBones", matrices);
  23421. }
  23422. }
  23423. };
  23424. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23425. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23426. return;
  23427. }
  23428. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23429. };
  23430. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23431. if (defines["LOGARITHMICDEPTH"]) {
  23432. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23433. }
  23434. };
  23435. MaterialHelper.BindClipPlane = function (effect, scene) {
  23436. if (scene.clipPlane) {
  23437. var clipPlane = scene.clipPlane;
  23438. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23439. }
  23440. };
  23441. return MaterialHelper;
  23442. }());
  23443. BABYLON.MaterialHelper = MaterialHelper;
  23444. })(BABYLON || (BABYLON = {}));
  23445. //# sourceMappingURL=babylon.materialHelper.js.map
  23446. var BABYLON;
  23447. (function (BABYLON) {
  23448. var MaterialDefines = (function () {
  23449. function MaterialDefines() {
  23450. this._isDirty = true;
  23451. this._areLightsDirty = true;
  23452. this._areAttributesDirty = true;
  23453. this._areTexturesDirty = true;
  23454. this._areFresnelDirty = true;
  23455. this._areMiscDirty = true;
  23456. this._normals = false;
  23457. this._uvs = false;
  23458. this._needNormals = false;
  23459. this._needUVs = false;
  23460. }
  23461. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23462. get: function () {
  23463. return this._isDirty;
  23464. },
  23465. enumerable: true,
  23466. configurable: true
  23467. });
  23468. MaterialDefines.prototype.markAsProcessed = function () {
  23469. this._isDirty = false;
  23470. this._areAttributesDirty = false;
  23471. this._areTexturesDirty = false;
  23472. this._areFresnelDirty = false;
  23473. this._areLightsDirty = false;
  23474. this._areMiscDirty = false;
  23475. };
  23476. MaterialDefines.prototype.markAsUnprocessed = function () {
  23477. this._isDirty = true;
  23478. };
  23479. MaterialDefines.prototype.markAllAsDirty = function () {
  23480. this._areTexturesDirty = true;
  23481. this._areAttributesDirty = true;
  23482. this._areLightsDirty = true;
  23483. this._areFresnelDirty = true;
  23484. this._areMiscDirty = true;
  23485. this._isDirty = true;
  23486. };
  23487. MaterialDefines.prototype.markAsLightDirty = function () {
  23488. this._areLightsDirty = true;
  23489. this._isDirty = true;
  23490. };
  23491. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23492. this._areAttributesDirty = true;
  23493. this._isDirty = true;
  23494. };
  23495. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23496. this._areTexturesDirty = true;
  23497. this._isDirty = true;
  23498. };
  23499. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23500. this._areFresnelDirty = true;
  23501. this._isDirty = true;
  23502. };
  23503. MaterialDefines.prototype.markAsMiscDirty = function () {
  23504. this._areMiscDirty = true;
  23505. this._isDirty = true;
  23506. };
  23507. MaterialDefines.prototype.rebuild = function () {
  23508. if (this._keys) {
  23509. delete this._keys;
  23510. }
  23511. this._keys = [];
  23512. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23513. var key = _a[_i];
  23514. if (key[0] === "_") {
  23515. continue;
  23516. }
  23517. this._keys.push(key);
  23518. }
  23519. };
  23520. MaterialDefines.prototype.isEqual = function (other) {
  23521. if (this._keys.length !== other._keys.length) {
  23522. return false;
  23523. }
  23524. for (var index = 0; index < this._keys.length; index++) {
  23525. var prop = this._keys[index];
  23526. if (this[prop] !== other[prop]) {
  23527. return false;
  23528. }
  23529. }
  23530. return true;
  23531. };
  23532. MaterialDefines.prototype.cloneTo = function (other) {
  23533. if (this._keys.length !== other._keys.length) {
  23534. other._keys = this._keys.slice(0);
  23535. }
  23536. for (var index = 0; index < this._keys.length; index++) {
  23537. var prop = this._keys[index];
  23538. other[prop] = this[prop];
  23539. }
  23540. };
  23541. MaterialDefines.prototype.reset = function () {
  23542. for (var index = 0; index < this._keys.length; index++) {
  23543. var prop = this._keys[index];
  23544. if (typeof (this[prop]) === "number") {
  23545. this[prop] = 0;
  23546. }
  23547. else {
  23548. this[prop] = false;
  23549. }
  23550. }
  23551. };
  23552. MaterialDefines.prototype.toString = function () {
  23553. var result = "";
  23554. for (var index = 0; index < this._keys.length; index++) {
  23555. var prop = this._keys[index];
  23556. var value = this[prop];
  23557. if (typeof (value) === "number") {
  23558. result += "#define " + prop + " " + this[prop] + "\n";
  23559. }
  23560. else if (value) {
  23561. result += "#define " + prop + "\n";
  23562. }
  23563. }
  23564. return result;
  23565. };
  23566. return MaterialDefines;
  23567. }());
  23568. BABYLON.MaterialDefines = MaterialDefines;
  23569. var Material = (function () {
  23570. function Material(name, scene, doNotAdd) {
  23571. this.checkReadyOnEveryCall = false;
  23572. this.checkReadyOnlyOnce = false;
  23573. this.state = "";
  23574. this.alpha = 1.0;
  23575. this._backFaceCulling = true;
  23576. this.doNotSerialize = false;
  23577. this.storeEffectOnSubMeshes = false;
  23578. /**
  23579. * An event triggered when the material is disposed.
  23580. * @type {BABYLON.Observable}
  23581. */
  23582. this.onDisposeObservable = new BABYLON.Observable();
  23583. /**
  23584. * An event triggered when the material is bound.
  23585. * @type {BABYLON.Observable}
  23586. */
  23587. this.onBindObservable = new BABYLON.Observable();
  23588. /**
  23589. * An event triggered when the material is unbound.
  23590. * @type {BABYLON.Observable}
  23591. */
  23592. this.onUnBindObservable = new BABYLON.Observable();
  23593. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23594. this.disableDepthWrite = false;
  23595. this._fogEnabled = true;
  23596. this.pointSize = 1.0;
  23597. this.zOffset = 0;
  23598. this._wasPreviouslyReady = false;
  23599. this._fillMode = Material.TriangleFillMode;
  23600. this.name = name;
  23601. this.id = name;
  23602. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23603. if (this._scene.useRightHandedSystem) {
  23604. this.sideOrientation = Material.ClockWiseSideOrientation;
  23605. }
  23606. else {
  23607. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23608. }
  23609. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23610. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23611. if (!doNotAdd) {
  23612. this._scene.materials.push(this);
  23613. }
  23614. }
  23615. Object.defineProperty(Material, "TriangleFillMode", {
  23616. get: function () {
  23617. return Material._TriangleFillMode;
  23618. },
  23619. enumerable: true,
  23620. configurable: true
  23621. });
  23622. Object.defineProperty(Material, "WireFrameFillMode", {
  23623. get: function () {
  23624. return Material._WireFrameFillMode;
  23625. },
  23626. enumerable: true,
  23627. configurable: true
  23628. });
  23629. Object.defineProperty(Material, "PointFillMode", {
  23630. get: function () {
  23631. return Material._PointFillMode;
  23632. },
  23633. enumerable: true,
  23634. configurable: true
  23635. });
  23636. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23637. get: function () {
  23638. return Material._ClockWiseSideOrientation;
  23639. },
  23640. enumerable: true,
  23641. configurable: true
  23642. });
  23643. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23644. get: function () {
  23645. return Material._CounterClockWiseSideOrientation;
  23646. },
  23647. enumerable: true,
  23648. configurable: true
  23649. });
  23650. Object.defineProperty(Material, "TextureDirtyFlag", {
  23651. get: function () {
  23652. return Material._TextureDirtyFlag;
  23653. },
  23654. enumerable: true,
  23655. configurable: true
  23656. });
  23657. Object.defineProperty(Material, "LightDirtyFlag", {
  23658. get: function () {
  23659. return Material._LightDirtyFlag;
  23660. },
  23661. enumerable: true,
  23662. configurable: true
  23663. });
  23664. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23665. get: function () {
  23666. return Material._FresnelDirtyFlag;
  23667. },
  23668. enumerable: true,
  23669. configurable: true
  23670. });
  23671. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23672. get: function () {
  23673. return Material._AttributesDirtyFlag;
  23674. },
  23675. enumerable: true,
  23676. configurable: true
  23677. });
  23678. Object.defineProperty(Material, "MiscDirtyFlag", {
  23679. get: function () {
  23680. return Material._MiscDirtyFlag;
  23681. },
  23682. enumerable: true,
  23683. configurable: true
  23684. });
  23685. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23686. get: function () {
  23687. return this._backFaceCulling;
  23688. },
  23689. set: function (value) {
  23690. if (this._backFaceCulling === value) {
  23691. return;
  23692. }
  23693. this._backFaceCulling = value;
  23694. this.markAsDirty(Material.TextureDirtyFlag);
  23695. },
  23696. enumerable: true,
  23697. configurable: true
  23698. });
  23699. Object.defineProperty(Material.prototype, "onDispose", {
  23700. set: function (callback) {
  23701. if (this._onDisposeObserver) {
  23702. this.onDisposeObservable.remove(this._onDisposeObserver);
  23703. }
  23704. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23705. },
  23706. enumerable: true,
  23707. configurable: true
  23708. });
  23709. Object.defineProperty(Material.prototype, "onBind", {
  23710. set: function (callback) {
  23711. if (this._onBindObserver) {
  23712. this.onBindObservable.remove(this._onBindObserver);
  23713. }
  23714. this._onBindObserver = this.onBindObservable.add(callback);
  23715. },
  23716. enumerable: true,
  23717. configurable: true
  23718. });
  23719. Object.defineProperty(Material.prototype, "fogEnabled", {
  23720. get: function () {
  23721. return this._fogEnabled;
  23722. },
  23723. set: function (value) {
  23724. if (this._fogEnabled === value) {
  23725. return;
  23726. }
  23727. this._fogEnabled = value;
  23728. this.markAsDirty(Material.MiscDirtyFlag);
  23729. },
  23730. enumerable: true,
  23731. configurable: true
  23732. });
  23733. Object.defineProperty(Material.prototype, "wireframe", {
  23734. get: function () {
  23735. return this._fillMode === Material.WireFrameFillMode;
  23736. },
  23737. set: function (value) {
  23738. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23739. },
  23740. enumerable: true,
  23741. configurable: true
  23742. });
  23743. Object.defineProperty(Material.prototype, "pointsCloud", {
  23744. get: function () {
  23745. return this._fillMode === Material.PointFillMode;
  23746. },
  23747. set: function (value) {
  23748. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23749. },
  23750. enumerable: true,
  23751. configurable: true
  23752. });
  23753. Object.defineProperty(Material.prototype, "fillMode", {
  23754. get: function () {
  23755. return this._fillMode;
  23756. },
  23757. set: function (value) {
  23758. if (this._fillMode === value) {
  23759. return;
  23760. }
  23761. this._fillMode = value;
  23762. this.markAsDirty(Material.MiscDirtyFlag);
  23763. },
  23764. enumerable: true,
  23765. configurable: true
  23766. });
  23767. /**
  23768. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23769. * subclasses should override adding information pertainent to themselves
  23770. */
  23771. Material.prototype.toString = function (fullDetails) {
  23772. var ret = "Name: " + this.name;
  23773. if (fullDetails) {
  23774. }
  23775. return ret;
  23776. };
  23777. /**
  23778. * Child classes can use it to update shaders
  23779. */
  23780. Material.prototype.markAsDirty = function (flag) {
  23781. };
  23782. Material.prototype.getClassName = function () {
  23783. return "Material";
  23784. };
  23785. Object.defineProperty(Material.prototype, "isFrozen", {
  23786. get: function () {
  23787. return this.checkReadyOnlyOnce;
  23788. },
  23789. enumerable: true,
  23790. configurable: true
  23791. });
  23792. Material.prototype.freeze = function () {
  23793. this.checkReadyOnlyOnce = true;
  23794. };
  23795. Material.prototype.unfreeze = function () {
  23796. this.checkReadyOnlyOnce = false;
  23797. };
  23798. Material.prototype.isReady = function (mesh, useInstances) {
  23799. return true;
  23800. };
  23801. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23802. return false;
  23803. };
  23804. Material.prototype.getEffect = function () {
  23805. return this._effect;
  23806. };
  23807. Material.prototype.getScene = function () {
  23808. return this._scene;
  23809. };
  23810. Material.prototype.needAlphaBlending = function () {
  23811. return (this.alpha < 1.0);
  23812. };
  23813. Material.prototype.needAlphaTesting = function () {
  23814. return false;
  23815. };
  23816. Material.prototype.getAlphaTestTexture = function () {
  23817. return null;
  23818. };
  23819. Material.prototype.markDirty = function () {
  23820. this._wasPreviouslyReady = false;
  23821. };
  23822. Material.prototype._preBind = function (effect) {
  23823. var engine = this._scene.getEngine();
  23824. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23825. engine.enableEffect(effect ? effect : this._effect);
  23826. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23827. };
  23828. Material.prototype.bind = function (world, mesh) {
  23829. };
  23830. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23831. };
  23832. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23833. };
  23834. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23835. sceneUbo.bindToEffect(effect, "Scene");
  23836. };
  23837. Material.prototype.bindView = function (effect) {
  23838. if (!this._useUBO) {
  23839. effect.setMatrix("view", this.getScene().getViewMatrix());
  23840. }
  23841. else {
  23842. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23843. }
  23844. };
  23845. Material.prototype.bindViewProjection = function (effect) {
  23846. if (!this._useUBO) {
  23847. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23848. }
  23849. else {
  23850. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23851. }
  23852. };
  23853. Material.prototype._afterBind = function (mesh) {
  23854. this._scene._cachedMaterial = this;
  23855. this.onBindObservable.notifyObservers(mesh);
  23856. if (this.disableDepthWrite) {
  23857. var engine = this._scene.getEngine();
  23858. this._cachedDepthWriteState = engine.getDepthWrite();
  23859. engine.setDepthWrite(false);
  23860. }
  23861. };
  23862. Material.prototype.unbind = function () {
  23863. this.onUnBindObservable.notifyObservers(this);
  23864. if (this.disableDepthWrite) {
  23865. var engine = this._scene.getEngine();
  23866. engine.setDepthWrite(this._cachedDepthWriteState);
  23867. }
  23868. };
  23869. Material.prototype.clone = function (name) {
  23870. return null;
  23871. };
  23872. Material.prototype.getBindedMeshes = function () {
  23873. var result = new Array();
  23874. for (var index = 0; index < this._scene.meshes.length; index++) {
  23875. var mesh = this._scene.meshes[index];
  23876. if (mesh.material === this) {
  23877. result.push(mesh);
  23878. }
  23879. }
  23880. return result;
  23881. };
  23882. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23883. // Animations
  23884. this.getScene().stopAnimation(this);
  23885. // Remove from scene
  23886. var index = this._scene.materials.indexOf(this);
  23887. if (index >= 0) {
  23888. this._scene.materials.splice(index, 1);
  23889. }
  23890. // Remove from meshes
  23891. for (index = 0; index < this._scene.meshes.length; index++) {
  23892. var mesh = this._scene.meshes[index];
  23893. if (mesh.material === this) {
  23894. mesh.material = null;
  23895. if (mesh.geometry) {
  23896. var geometry = mesh.geometry;
  23897. if (this.storeEffectOnSubMeshes) {
  23898. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  23899. var subMesh = _a[_i];
  23900. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  23901. }
  23902. }
  23903. else {
  23904. geometry._releaseVertexArrayObject(this._effect);
  23905. }
  23906. }
  23907. }
  23908. }
  23909. this._uniformBuffer.dispose();
  23910. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23911. if (forceDisposeEffect && this._effect) {
  23912. if (this.storeEffectOnSubMeshes) {
  23913. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23914. var subMesh = _c[_b];
  23915. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  23916. }
  23917. }
  23918. else {
  23919. this._scene.getEngine()._releaseEffect(this._effect);
  23920. }
  23921. this._effect = null;
  23922. }
  23923. // Callback
  23924. this.onDisposeObservable.notifyObservers(this);
  23925. this.onDisposeObservable.clear();
  23926. this.onBindObservable.clear();
  23927. this.onUnBindObservable.clear();
  23928. };
  23929. Material.prototype.serialize = function () {
  23930. return BABYLON.SerializationHelper.Serialize(this);
  23931. };
  23932. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23933. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23934. multiMaterial.id = parsedMultiMaterial.id;
  23935. if (BABYLON.Tags) {
  23936. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23937. }
  23938. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23939. var subMatId = parsedMultiMaterial.materials[matIndex];
  23940. if (subMatId) {
  23941. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23942. }
  23943. else {
  23944. multiMaterial.subMaterials.push(null);
  23945. }
  23946. }
  23947. return multiMaterial;
  23948. };
  23949. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23950. if (!parsedMaterial.customType) {
  23951. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23952. }
  23953. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && !parsedMaterial.overloadedAlbedo) {
  23954. parsedMaterial.customType === "BABYLON.legacyPBRMaterial";
  23955. if (!BABYLON.legacyPBRMaterial) {
  23956. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  23957. return;
  23958. }
  23959. }
  23960. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23961. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23962. ;
  23963. };
  23964. return Material;
  23965. }());
  23966. Material._TriangleFillMode = 0;
  23967. Material._WireFrameFillMode = 1;
  23968. Material._PointFillMode = 2;
  23969. Material._ClockWiseSideOrientation = 0;
  23970. Material._CounterClockWiseSideOrientation = 1;
  23971. Material._TextureDirtyFlag = 1;
  23972. Material._LightDirtyFlag = 2;
  23973. Material._FresnelDirtyFlag = 4;
  23974. Material._AttributesDirtyFlag = 8;
  23975. Material._MiscDirtyFlag = 16;
  23976. __decorate([
  23977. BABYLON.serialize()
  23978. ], Material.prototype, "id", void 0);
  23979. __decorate([
  23980. BABYLON.serialize()
  23981. ], Material.prototype, "name", void 0);
  23982. __decorate([
  23983. BABYLON.serialize()
  23984. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23985. __decorate([
  23986. BABYLON.serialize()
  23987. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23988. __decorate([
  23989. BABYLON.serialize()
  23990. ], Material.prototype, "state", void 0);
  23991. __decorate([
  23992. BABYLON.serialize()
  23993. ], Material.prototype, "alpha", void 0);
  23994. __decorate([
  23995. BABYLON.serialize("backFaceCulling")
  23996. ], Material.prototype, "_backFaceCulling", void 0);
  23997. __decorate([
  23998. BABYLON.serialize()
  23999. ], Material.prototype, "sideOrientation", void 0);
  24000. __decorate([
  24001. BABYLON.serialize()
  24002. ], Material.prototype, "alphaMode", void 0);
  24003. __decorate([
  24004. BABYLON.serialize()
  24005. ], Material.prototype, "disableDepthWrite", void 0);
  24006. __decorate([
  24007. BABYLON.serialize("fogEnabled")
  24008. ], Material.prototype, "_fogEnabled", void 0);
  24009. __decorate([
  24010. BABYLON.serialize()
  24011. ], Material.prototype, "pointSize", void 0);
  24012. __decorate([
  24013. BABYLON.serialize()
  24014. ], Material.prototype, "zOffset", void 0);
  24015. __decorate([
  24016. BABYLON.serialize()
  24017. ], Material.prototype, "wireframe", null);
  24018. __decorate([
  24019. BABYLON.serialize()
  24020. ], Material.prototype, "pointsCloud", null);
  24021. __decorate([
  24022. BABYLON.serialize()
  24023. ], Material.prototype, "fillMode", null);
  24024. BABYLON.Material = Material;
  24025. })(BABYLON || (BABYLON = {}));
  24026. //# sourceMappingURL=babylon.material.js.map
  24027. var BABYLON;
  24028. (function (BABYLON) {
  24029. var UniformBuffer = (function () {
  24030. /**
  24031. * Uniform buffer objects.
  24032. *
  24033. * Handles blocks of uniform on the GPU.
  24034. *
  24035. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24036. *
  24037. * For more information, please refer to :
  24038. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24039. */
  24040. function UniformBuffer(engine, data, dynamic) {
  24041. this._engine = engine;
  24042. this._noUBO = engine.webGLVersion === 1;
  24043. this._dynamic = dynamic;
  24044. this._data = data || [];
  24045. this._uniformLocations = {};
  24046. this._uniformSizes = {};
  24047. this._uniformLocationPointer = 0;
  24048. this._needSync = false;
  24049. if (this._noUBO) {
  24050. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24051. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24052. this.updateFloat = this._updateFloatForEffect;
  24053. this.updateFloat2 = this._updateFloat2ForEffect;
  24054. this.updateFloat3 = this._updateFloat3ForEffect;
  24055. this.updateFloat4 = this._updateFloat4ForEffect;
  24056. this.updateMatrix = this._updateMatrixForEffect;
  24057. this.updateVector3 = this._updateVector3ForEffect;
  24058. this.updateVector4 = this._updateVector4ForEffect;
  24059. this.updateColor3 = this._updateColor3ForEffect;
  24060. this.updateColor4 = this._updateColor4ForEffect;
  24061. }
  24062. else {
  24063. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24064. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24065. this.updateFloat = this._updateFloatForUniform;
  24066. this.updateFloat2 = this._updateFloat2ForUniform;
  24067. this.updateFloat3 = this._updateFloat3ForUniform;
  24068. this.updateFloat4 = this._updateFloat4ForUniform;
  24069. this.updateMatrix = this._updateMatrixForUniform;
  24070. this.updateVector3 = this._updateVector3ForUniform;
  24071. this.updateVector4 = this._updateVector4ForUniform;
  24072. this.updateColor3 = this._updateColor3ForUniform;
  24073. this.updateColor4 = this._updateColor4ForUniform;
  24074. }
  24075. }
  24076. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24077. // Properties
  24078. /**
  24079. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24080. * or just falling back on setUniformXXX calls.
  24081. */
  24082. get: function () {
  24083. return !this._noUBO;
  24084. },
  24085. enumerable: true,
  24086. configurable: true
  24087. });
  24088. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24089. /**
  24090. * Indicates if the WebGL underlying uniform buffer is in sync
  24091. * with the javascript cache data.
  24092. */
  24093. get: function () {
  24094. return !this._needSync;
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. /**
  24100. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24101. * Also, a dynamic UniformBuffer will disable cache verification and always
  24102. * update the underlying WebGL uniform buffer to the GPU.
  24103. */
  24104. UniformBuffer.prototype.isDynamic = function () {
  24105. return this._dynamic;
  24106. };
  24107. /**
  24108. * The data cache on JS side.
  24109. */
  24110. UniformBuffer.prototype.getData = function () {
  24111. return this._bufferData;
  24112. };
  24113. /**
  24114. * The underlying WebGL Uniform buffer.
  24115. */
  24116. UniformBuffer.prototype.getBuffer = function () {
  24117. return this._buffer;
  24118. };
  24119. /**
  24120. * std140 layout specifies how to align data within an UBO structure.
  24121. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24122. * for specs.
  24123. */
  24124. UniformBuffer.prototype._fillAlignment = function (size) {
  24125. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24126. // and 4x4 matrices
  24127. // TODO : change if other types are used
  24128. var alignment;
  24129. if (size <= 2) {
  24130. alignment = size;
  24131. }
  24132. else {
  24133. alignment = 4;
  24134. }
  24135. if ((this._uniformLocationPointer % alignment) !== 0) {
  24136. var oldPointer = this._uniformLocationPointer;
  24137. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24138. var diff = this._uniformLocationPointer - oldPointer;
  24139. for (var i = 0; i < diff; i++) {
  24140. this._data.push(0);
  24141. }
  24142. }
  24143. };
  24144. /**
  24145. * Adds an uniform in the buffer.
  24146. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24147. * for the layout to be correct !
  24148. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24149. * @param {number|number[]} size Data size, or data directly.
  24150. */
  24151. UniformBuffer.prototype.addUniform = function (name, size) {
  24152. if (this._noUBO) {
  24153. return;
  24154. }
  24155. if (this._uniformLocations[name] !== undefined) {
  24156. // Already existing uniform
  24157. return;
  24158. }
  24159. // This function must be called in the order of the shader layout !
  24160. // size can be the size of the uniform, or data directly
  24161. var data;
  24162. if (size instanceof Array) {
  24163. data = size;
  24164. size = data.length;
  24165. }
  24166. else {
  24167. size = size;
  24168. data = [];
  24169. // Fill with zeros
  24170. for (var i = 0; i < size; i++) {
  24171. data.push(0);
  24172. }
  24173. }
  24174. this._fillAlignment(size);
  24175. this._uniformSizes[name] = size;
  24176. this._uniformLocations[name] = this._uniformLocationPointer;
  24177. this._uniformLocationPointer += size;
  24178. for (var i = 0; i < size; i++) {
  24179. this._data.push(data[i]);
  24180. }
  24181. this._needSync = true;
  24182. };
  24183. /**
  24184. * Wrapper for addUniform.
  24185. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24186. * @param {Matrix} mat A 4x4 matrix.
  24187. */
  24188. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24189. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24190. };
  24191. /**
  24192. * Wrapper for addUniform.
  24193. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24194. * @param {number} x
  24195. * @param {number} y
  24196. */
  24197. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24198. var temp = [x, y];
  24199. this.addUniform(name, temp);
  24200. };
  24201. /**
  24202. * Wrapper for addUniform.
  24203. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24204. * @param {number} x
  24205. * @param {number} y
  24206. * @param {number} z
  24207. */
  24208. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24209. var temp = [x, y, z];
  24210. this.addUniform(name, temp);
  24211. };
  24212. /**
  24213. * Wrapper for addUniform.
  24214. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24215. * @param {Color3} color
  24216. */
  24217. UniformBuffer.prototype.addColor3 = function (name, color) {
  24218. var temp = [];
  24219. color.toArray(temp);
  24220. this.addUniform(name, temp);
  24221. };
  24222. /**
  24223. * Wrapper for addUniform.
  24224. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24225. * @param {Color3} color
  24226. * @param {number} alpha
  24227. */
  24228. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24229. var temp = [];
  24230. color.toArray(temp);
  24231. temp.push(alpha);
  24232. this.addUniform(name, temp);
  24233. };
  24234. /**
  24235. * Wrapper for addUniform.
  24236. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24237. * @param {Vector3} vector
  24238. */
  24239. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24240. var temp = [];
  24241. vector.toArray(temp);
  24242. this.addUniform(name, temp);
  24243. };
  24244. /**
  24245. * Wrapper for addUniform.
  24246. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24247. */
  24248. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24249. this.addUniform(name, 12);
  24250. };
  24251. /**
  24252. * Wrapper for addUniform.
  24253. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24254. */
  24255. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24256. this.addUniform(name, 8);
  24257. };
  24258. /**
  24259. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24260. */
  24261. UniformBuffer.prototype.create = function () {
  24262. if (this._noUBO) {
  24263. return;
  24264. }
  24265. if (this._buffer) {
  24266. return; // nothing to do
  24267. }
  24268. // See spec, alignment must be filled as a vec4
  24269. this._fillAlignment(4);
  24270. this._bufferData = new Float32Array(this._data);
  24271. if (this._dynamic) {
  24272. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24273. }
  24274. else {
  24275. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24276. }
  24277. this._needSync = true;
  24278. };
  24279. /**
  24280. * Updates the WebGL Uniform Buffer on the GPU.
  24281. * If the `dynamic` flag is set to true, no cache comparison is done.
  24282. * Otherwise, the buffer will be updated only if the cache differs.
  24283. */
  24284. UniformBuffer.prototype.update = function () {
  24285. if (!this._buffer) {
  24286. this.create();
  24287. return;
  24288. }
  24289. if (!this._dynamic && !this._needSync) {
  24290. return;
  24291. }
  24292. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24293. this._needSync = false;
  24294. };
  24295. /**
  24296. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24297. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24298. * @param {number[]|Float32Array} data Flattened data
  24299. * @param {number} size Size of the data.
  24300. */
  24301. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24302. var location = this._uniformLocations[uniformName];
  24303. if (location === undefined) {
  24304. if (this._buffer) {
  24305. // Cannot add an uniform if the buffer is already created
  24306. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24307. return;
  24308. }
  24309. this.addUniform(uniformName, size);
  24310. location = this._uniformLocations[uniformName];
  24311. }
  24312. if (!this._buffer) {
  24313. this.create();
  24314. }
  24315. if (!this._dynamic) {
  24316. // Cache for static uniform buffers
  24317. var changed = false;
  24318. for (var i = 0; i < size; i++) {
  24319. if (this._bufferData[location + i] !== data[i]) {
  24320. changed = true;
  24321. this._bufferData[location + i] = data[i];
  24322. }
  24323. }
  24324. this._needSync = this._needSync || changed;
  24325. }
  24326. else {
  24327. // No cache for dynamic
  24328. for (var i = 0; i < size; i++) {
  24329. this._bufferData[location + i] = data[i];
  24330. }
  24331. }
  24332. };
  24333. // Update methods
  24334. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24335. // To match std140, matrix must be realigned
  24336. for (var i = 0; i < 3; i++) {
  24337. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24338. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24339. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24340. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24341. }
  24342. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24343. };
  24344. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24345. this._currentEffect.setMatrix3x3(name, matrix);
  24346. };
  24347. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24348. this._currentEffect.setMatrix2x2(name, matrix);
  24349. };
  24350. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24351. // To match std140, matrix must be realigned
  24352. for (var i = 0; i < 2; i++) {
  24353. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24354. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24355. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24356. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24357. }
  24358. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24359. };
  24360. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24361. this._currentEffect.setFloat(name, x);
  24362. };
  24363. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24364. UniformBuffer._tempBuffer[0] = x;
  24365. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24366. };
  24367. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  24368. this._currentEffect.setFloat2(name, x, y);
  24369. };
  24370. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  24371. UniformBuffer._tempBuffer[0] = x;
  24372. UniformBuffer._tempBuffer[1] = y;
  24373. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24374. };
  24375. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24376. if (suffix === void 0) { suffix = ""; }
  24377. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24378. };
  24379. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24380. if (suffix === void 0) { suffix = ""; }
  24381. UniformBuffer._tempBuffer[0] = x;
  24382. UniformBuffer._tempBuffer[1] = y;
  24383. UniformBuffer._tempBuffer[2] = z;
  24384. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24385. };
  24386. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24387. if (suffix === void 0) { suffix = ""; }
  24388. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24389. };
  24390. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24391. if (suffix === void 0) { suffix = ""; }
  24392. UniformBuffer._tempBuffer[0] = x;
  24393. UniformBuffer._tempBuffer[1] = y;
  24394. UniformBuffer._tempBuffer[2] = z;
  24395. UniformBuffer._tempBuffer[3] = w;
  24396. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24397. };
  24398. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24399. this._currentEffect.setMatrix(name, mat);
  24400. };
  24401. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24402. this.updateUniform(name, mat.toArray(), 16);
  24403. };
  24404. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24405. this._currentEffect.setVector3(name, vector);
  24406. };
  24407. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24408. vector.toArray(UniformBuffer._tempBuffer);
  24409. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24410. };
  24411. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24412. this._currentEffect.setVector4(name, vector);
  24413. };
  24414. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24415. vector.toArray(UniformBuffer._tempBuffer);
  24416. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24417. };
  24418. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24419. if (suffix === void 0) { suffix = ""; }
  24420. this._currentEffect.setColor3(name + suffix, color);
  24421. };
  24422. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24423. if (suffix === void 0) { suffix = ""; }
  24424. color.toArray(UniformBuffer._tempBuffer);
  24425. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24426. };
  24427. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24428. if (suffix === void 0) { suffix = ""; }
  24429. this._currentEffect.setColor4(name + suffix, color, alpha);
  24430. };
  24431. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24432. if (suffix === void 0) { suffix = ""; }
  24433. color.toArray(UniformBuffer._tempBuffer);
  24434. UniformBuffer._tempBuffer[3] = alpha;
  24435. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24436. };
  24437. /**
  24438. * Sets a sampler uniform on the effect.
  24439. * @param {string} name Name of the sampler.
  24440. * @param {Texture} texture
  24441. */
  24442. UniformBuffer.prototype.setTexture = function (name, texture) {
  24443. this._currentEffect.setTexture(name, texture);
  24444. };
  24445. /**
  24446. * Directly updates the value of the uniform in the cache AND on the GPU.
  24447. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24448. * @param {number[]|Float32Array} data Flattened data
  24449. */
  24450. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24451. this.updateUniform(uniformName, data, data.length);
  24452. this.update();
  24453. };
  24454. /**
  24455. * Binds this uniform buffer to an effect.
  24456. * @param {Effect} effect
  24457. * @param {string} name Name of the uniform block in the shader.
  24458. */
  24459. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24460. this._currentEffect = effect;
  24461. if (this._noUBO) {
  24462. return;
  24463. }
  24464. effect.bindUniformBuffer(this._buffer, name);
  24465. };
  24466. /**
  24467. * Disposes the uniform buffer.
  24468. */
  24469. UniformBuffer.prototype.dispose = function () {
  24470. if (!this._buffer) {
  24471. return;
  24472. }
  24473. if (this._engine._releaseBuffer(this._buffer)) {
  24474. this._buffer = null;
  24475. }
  24476. };
  24477. return UniformBuffer;
  24478. }());
  24479. // Pool for avoiding memory leaks
  24480. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24481. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24482. BABYLON.UniformBuffer = UniformBuffer;
  24483. })(BABYLON || (BABYLON = {}));
  24484. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24485. var BABYLON;
  24486. (function (BABYLON) {
  24487. var PushMaterial = (function (_super) {
  24488. __extends(PushMaterial, _super);
  24489. function PushMaterial(name, scene) {
  24490. var _this = _super.call(this, name, scene) || this;
  24491. _this.storeEffectOnSubMeshes = true;
  24492. return _this;
  24493. }
  24494. PushMaterial.prototype.getEffect = function () {
  24495. return this._activeEffect;
  24496. };
  24497. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24498. if (!mesh) {
  24499. return false;
  24500. }
  24501. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24502. return true;
  24503. }
  24504. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24505. };
  24506. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24507. this._activeEffect.setMatrix("world", world);
  24508. };
  24509. PushMaterial.prototype.bind = function (world, mesh) {
  24510. if (!mesh) {
  24511. return;
  24512. }
  24513. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24514. };
  24515. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24516. _super.prototype._afterBind.call(this, mesh);
  24517. this.getScene()._cachedEffect = effect;
  24518. };
  24519. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24520. if (visibility === void 0) { visibility = 0; }
  24521. return scene.isCachedMaterialValid(this, effect, visibility);
  24522. };
  24523. PushMaterial.prototype.markAsDirty = function (flag) {
  24524. if (flag & BABYLON.Material.TextureDirtyFlag) {
  24525. this._markAllSubMeshesAsTexturesDirty();
  24526. }
  24527. if (flag & BABYLON.Material.LightDirtyFlag) {
  24528. this._markAllSubMeshesAsLightsDirty();
  24529. }
  24530. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  24531. this._markAllSubMeshesAsFresnelDirty();
  24532. }
  24533. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  24534. this._markAllSubMeshesAsAttributesDirty();
  24535. }
  24536. if (flag & BABYLON.Material.MiscDirtyFlag) {
  24537. this._markAllSubMeshesAsMiscDirty();
  24538. }
  24539. };
  24540. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  24541. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24542. var mesh = _a[_i];
  24543. if (!mesh.subMeshes) {
  24544. continue;
  24545. }
  24546. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24547. var subMesh = _c[_b];
  24548. if (subMesh.getMaterial() !== this) {
  24549. continue;
  24550. }
  24551. if (!subMesh._materialDefines) {
  24552. return;
  24553. }
  24554. func(subMesh._materialDefines);
  24555. }
  24556. }
  24557. };
  24558. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24559. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24560. };
  24561. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24562. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24563. };
  24564. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  24565. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24566. };
  24567. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24568. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24569. };
  24570. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  24571. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24572. };
  24573. return PushMaterial;
  24574. }(BABYLON.Material));
  24575. BABYLON.PushMaterial = PushMaterial;
  24576. })(BABYLON || (BABYLON = {}));
  24577. //# sourceMappingURL=babylon.pushMaterial.js.map
  24578. var BABYLON;
  24579. (function (BABYLON) {
  24580. var VertexData = (function () {
  24581. function VertexData() {
  24582. }
  24583. VertexData.prototype.set = function (data, kind) {
  24584. switch (kind) {
  24585. case BABYLON.VertexBuffer.PositionKind:
  24586. this.positions = data;
  24587. break;
  24588. case BABYLON.VertexBuffer.NormalKind:
  24589. this.normals = data;
  24590. break;
  24591. case BABYLON.VertexBuffer.TangentKind:
  24592. this.tangents = data;
  24593. break;
  24594. case BABYLON.VertexBuffer.UVKind:
  24595. this.uvs = data;
  24596. break;
  24597. case BABYLON.VertexBuffer.UV2Kind:
  24598. this.uvs2 = data;
  24599. break;
  24600. case BABYLON.VertexBuffer.UV3Kind:
  24601. this.uvs3 = data;
  24602. break;
  24603. case BABYLON.VertexBuffer.UV4Kind:
  24604. this.uvs4 = data;
  24605. break;
  24606. case BABYLON.VertexBuffer.UV5Kind:
  24607. this.uvs5 = data;
  24608. break;
  24609. case BABYLON.VertexBuffer.UV6Kind:
  24610. this.uvs6 = data;
  24611. break;
  24612. case BABYLON.VertexBuffer.ColorKind:
  24613. this.colors = data;
  24614. break;
  24615. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24616. this.matricesIndices = data;
  24617. break;
  24618. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24619. this.matricesWeights = data;
  24620. break;
  24621. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24622. this.matricesIndicesExtra = data;
  24623. break;
  24624. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24625. this.matricesWeightsExtra = data;
  24626. break;
  24627. }
  24628. };
  24629. /**
  24630. * Associates the vertexData to the passed Mesh.
  24631. * Sets it as updatable or not (default `false`).
  24632. * Returns the VertexData.
  24633. */
  24634. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24635. this._applyTo(mesh, updatable);
  24636. return this;
  24637. };
  24638. /**
  24639. * Associates the vertexData to the passed Geometry.
  24640. * Sets it as updatable or not (default `false`).
  24641. * Returns the VertexData.
  24642. */
  24643. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24644. this._applyTo(geometry, updatable);
  24645. return this;
  24646. };
  24647. /**
  24648. * Updates the associated mesh.
  24649. * Returns the VertexData.
  24650. */
  24651. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24652. this._update(mesh);
  24653. return this;
  24654. };
  24655. /**
  24656. * Updates the associated geometry.
  24657. * Returns the VertexData.
  24658. */
  24659. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24660. this._update(geometry);
  24661. return this;
  24662. };
  24663. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24664. if (this.positions) {
  24665. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24666. }
  24667. if (this.normals) {
  24668. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24669. }
  24670. if (this.tangents) {
  24671. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24672. }
  24673. if (this.uvs) {
  24674. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24675. }
  24676. if (this.uvs2) {
  24677. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24678. }
  24679. if (this.uvs3) {
  24680. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24681. }
  24682. if (this.uvs4) {
  24683. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24684. }
  24685. if (this.uvs5) {
  24686. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24687. }
  24688. if (this.uvs6) {
  24689. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24690. }
  24691. if (this.colors) {
  24692. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24693. }
  24694. if (this.matricesIndices) {
  24695. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24696. }
  24697. if (this.matricesWeights) {
  24698. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24699. }
  24700. if (this.matricesIndicesExtra) {
  24701. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24702. }
  24703. if (this.matricesWeightsExtra) {
  24704. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24705. }
  24706. if (this.indices) {
  24707. meshOrGeometry.setIndices(this.indices);
  24708. }
  24709. return this;
  24710. };
  24711. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24712. if (this.positions) {
  24713. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24714. }
  24715. if (this.normals) {
  24716. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24717. }
  24718. if (this.tangents) {
  24719. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24720. }
  24721. if (this.uvs) {
  24722. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24723. }
  24724. if (this.uvs2) {
  24725. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24726. }
  24727. if (this.uvs3) {
  24728. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24729. }
  24730. if (this.uvs4) {
  24731. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24732. }
  24733. if (this.uvs5) {
  24734. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24735. }
  24736. if (this.uvs6) {
  24737. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24738. }
  24739. if (this.colors) {
  24740. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24741. }
  24742. if (this.matricesIndices) {
  24743. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24744. }
  24745. if (this.matricesWeights) {
  24746. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24747. }
  24748. if (this.matricesIndicesExtra) {
  24749. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24750. }
  24751. if (this.matricesWeightsExtra) {
  24752. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24753. }
  24754. if (this.indices) {
  24755. meshOrGeometry.setIndices(this.indices);
  24756. }
  24757. return this;
  24758. };
  24759. /**
  24760. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24761. * Returns the VertexData.
  24762. */
  24763. VertexData.prototype.transform = function (matrix) {
  24764. var transformed = BABYLON.Vector3.Zero();
  24765. var index;
  24766. if (this.positions) {
  24767. var position = BABYLON.Vector3.Zero();
  24768. for (index = 0; index < this.positions.length; index += 3) {
  24769. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24770. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24771. this.positions[index] = transformed.x;
  24772. this.positions[index + 1] = transformed.y;
  24773. this.positions[index + 2] = transformed.z;
  24774. }
  24775. }
  24776. if (this.normals) {
  24777. var normal = BABYLON.Vector3.Zero();
  24778. for (index = 0; index < this.normals.length; index += 3) {
  24779. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24780. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24781. this.normals[index] = transformed.x;
  24782. this.normals[index + 1] = transformed.y;
  24783. this.normals[index + 2] = transformed.z;
  24784. }
  24785. }
  24786. if (this.tangents) {
  24787. var tangent = BABYLON.Vector4.Zero();
  24788. var tangentTransformed = BABYLON.Vector4.Zero();
  24789. for (index = 0; index < this.tangents.length; index += 4) {
  24790. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24791. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24792. this.tangents[index] = tangentTransformed.x;
  24793. this.tangents[index + 1] = tangentTransformed.y;
  24794. this.tangents[index + 2] = tangentTransformed.z;
  24795. this.tangents[index + 3] = tangentTransformed.w;
  24796. }
  24797. }
  24798. return this;
  24799. };
  24800. /**
  24801. * Merges the passed VertexData into the current one.
  24802. * Returns the modified VertexData.
  24803. */
  24804. VertexData.prototype.merge = function (other) {
  24805. if (other.indices) {
  24806. if (!this.indices) {
  24807. this.indices = [];
  24808. }
  24809. var offset = this.positions ? this.positions.length / 3 : 0;
  24810. for (var index = 0; index < other.indices.length; index++) {
  24811. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24812. this.indices.push(other.indices[index] + offset);
  24813. }
  24814. }
  24815. this.positions = this._mergeElement(this.positions, other.positions);
  24816. this.normals = this._mergeElement(this.normals, other.normals);
  24817. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24818. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24819. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24820. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24821. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24822. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24823. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24824. this.colors = this._mergeElement(this.colors, other.colors);
  24825. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24826. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24827. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24828. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24829. return this;
  24830. };
  24831. VertexData.prototype._mergeElement = function (source, other) {
  24832. if (!other)
  24833. return source;
  24834. if (!source)
  24835. return other;
  24836. var len = other.length + source.length;
  24837. var isSrcTypedArray = source instanceof Float32Array;
  24838. var isOthTypedArray = other instanceof Float32Array;
  24839. // use non-loop method when the source is Float32Array
  24840. if (isSrcTypedArray) {
  24841. var ret32 = new Float32Array(len);
  24842. ret32.set(source);
  24843. ret32.set(other, source.length);
  24844. return ret32;
  24845. // source is number[], when other is also use concat
  24846. }
  24847. else if (!isOthTypedArray) {
  24848. return source.concat(other);
  24849. // source is a number[], but other is a Float32Array, loop required
  24850. }
  24851. else {
  24852. var ret = source.slice(0); // copy source to a separate array
  24853. for (var i = 0, len = other.length; i < len; i++) {
  24854. ret.push(other[i]);
  24855. }
  24856. return ret;
  24857. }
  24858. };
  24859. /**
  24860. * Serializes the VertexData.
  24861. * Returns a serialized object.
  24862. */
  24863. VertexData.prototype.serialize = function () {
  24864. var serializationObject = this.serialize();
  24865. if (this.positions) {
  24866. serializationObject.positions = this.positions;
  24867. }
  24868. if (this.normals) {
  24869. serializationObject.normals = this.normals;
  24870. }
  24871. if (this.tangents) {
  24872. serializationObject.tangents = this.tangents;
  24873. }
  24874. if (this.uvs) {
  24875. serializationObject.uvs = this.uvs;
  24876. }
  24877. if (this.uvs2) {
  24878. serializationObject.uvs2 = this.uvs2;
  24879. }
  24880. if (this.uvs3) {
  24881. serializationObject.uvs3 = this.uvs3;
  24882. }
  24883. if (this.uvs4) {
  24884. serializationObject.uvs4 = this.uvs4;
  24885. }
  24886. if (this.uvs5) {
  24887. serializationObject.uvs5 = this.uvs5;
  24888. }
  24889. if (this.uvs6) {
  24890. serializationObject.uvs6 = this.uvs6;
  24891. }
  24892. if (this.colors) {
  24893. serializationObject.colors = this.colors;
  24894. }
  24895. if (this.matricesIndices) {
  24896. serializationObject.matricesIndices = this.matricesIndices;
  24897. serializationObject.matricesIndices._isExpanded = true;
  24898. }
  24899. if (this.matricesWeights) {
  24900. serializationObject.matricesWeights = this.matricesWeights;
  24901. }
  24902. if (this.matricesIndicesExtra) {
  24903. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24904. serializationObject.matricesIndicesExtra._isExpanded = true;
  24905. }
  24906. if (this.matricesWeightsExtra) {
  24907. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24908. }
  24909. serializationObject.indices = this.indices;
  24910. return serializationObject;
  24911. };
  24912. // Statics
  24913. /**
  24914. * Returns the object VertexData associated to the passed mesh.
  24915. */
  24916. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  24917. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  24918. };
  24919. /**
  24920. * Returns the object VertexData associated to the passed geometry.
  24921. */
  24922. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  24923. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  24924. };
  24925. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  24926. var result = new VertexData();
  24927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24928. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  24929. }
  24930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24931. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  24932. }
  24933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24934. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  24935. }
  24936. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24937. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  24938. }
  24939. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24940. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  24941. }
  24942. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24943. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  24944. }
  24945. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24946. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  24947. }
  24948. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24949. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  24950. }
  24951. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24952. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  24953. }
  24954. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24955. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  24956. }
  24957. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24958. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  24959. }
  24960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24961. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  24962. }
  24963. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24964. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  24965. }
  24966. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24967. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  24968. }
  24969. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24970. return result;
  24971. };
  24972. /**
  24973. * Creates the vertexData of the Ribbon.
  24974. */
  24975. VertexData.CreateRibbon = function (options) {
  24976. var pathArray = options.pathArray;
  24977. var closeArray = options.closeArray || false;
  24978. var closePath = options.closePath || false;
  24979. var invertUV = options.invertUV || false;
  24980. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24981. var offset = options.offset || defaultOffset;
  24982. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24983. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24984. var customUV = options.uvs;
  24985. var customColors = options.colors;
  24986. var positions = [];
  24987. var indices = [];
  24988. var normals = [];
  24989. var uvs = [];
  24990. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24991. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24992. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24993. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24994. var minlg; // minimal length among all paths from pathArray
  24995. var lg = []; // array of path lengths : nb of vertex per path
  24996. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24997. var p; // path iterator
  24998. var i; // point iterator
  24999. var j; // point iterator
  25000. // if single path in pathArray
  25001. if (pathArray.length < 2) {
  25002. var ar1 = [];
  25003. var ar2 = [];
  25004. for (i = 0; i < pathArray[0].length - offset; i++) {
  25005. ar1.push(pathArray[0][i]);
  25006. ar2.push(pathArray[0][i + offset]);
  25007. }
  25008. pathArray = [ar1, ar2];
  25009. }
  25010. // positions and horizontal distances (u)
  25011. var idc = 0;
  25012. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25013. var path;
  25014. var l;
  25015. minlg = pathArray[0].length;
  25016. var vectlg;
  25017. var dist;
  25018. for (p = 0; p < pathArray.length; p++) {
  25019. uTotalDistance[p] = 0;
  25020. us[p] = [0];
  25021. path = pathArray[p];
  25022. l = path.length;
  25023. minlg = (minlg < l) ? minlg : l;
  25024. j = 0;
  25025. while (j < l) {
  25026. positions.push(path[j].x, path[j].y, path[j].z);
  25027. if (j > 0) {
  25028. vectlg = path[j].subtract(path[j - 1]).length();
  25029. dist = vectlg + uTotalDistance[p];
  25030. us[p].push(dist);
  25031. uTotalDistance[p] = dist;
  25032. }
  25033. j++;
  25034. }
  25035. if (closePath) {
  25036. j--;
  25037. positions.push(path[0].x, path[0].y, path[0].z);
  25038. vectlg = path[j].subtract(path[0]).length();
  25039. dist = vectlg + uTotalDistance[p];
  25040. us[p].push(dist);
  25041. uTotalDistance[p] = dist;
  25042. }
  25043. lg[p] = l + closePathCorr;
  25044. idx[p] = idc;
  25045. idc += (l + closePathCorr);
  25046. }
  25047. // vertical distances (v)
  25048. var path1;
  25049. var path2;
  25050. var vertex1;
  25051. var vertex2;
  25052. for (i = 0; i < minlg + closePathCorr; i++) {
  25053. vTotalDistance[i] = 0;
  25054. vs[i] = [0];
  25055. for (p = 0; p < pathArray.length - 1; p++) {
  25056. path1 = pathArray[p];
  25057. path2 = pathArray[p + 1];
  25058. if (i === minlg) {
  25059. vertex1 = path1[0];
  25060. vertex2 = path2[0];
  25061. }
  25062. else {
  25063. vertex1 = path1[i];
  25064. vertex2 = path2[i];
  25065. }
  25066. vectlg = vertex2.subtract(vertex1).length();
  25067. dist = vectlg + vTotalDistance[i];
  25068. vs[i].push(dist);
  25069. vTotalDistance[i] = dist;
  25070. }
  25071. if (closeArray) {
  25072. path1 = pathArray[p];
  25073. path2 = pathArray[0];
  25074. if (i === minlg) {
  25075. vertex2 = path2[0];
  25076. }
  25077. vectlg = vertex2.subtract(vertex1).length();
  25078. dist = vectlg + vTotalDistance[i];
  25079. vTotalDistance[i] = dist;
  25080. }
  25081. }
  25082. // uvs
  25083. var u;
  25084. var v;
  25085. if (customUV) {
  25086. for (p = 0; p < customUV.length; p++) {
  25087. uvs.push(customUV[p].x, customUV[p].y);
  25088. }
  25089. }
  25090. else {
  25091. for (p = 0; p < pathArray.length; p++) {
  25092. for (i = 0; i < minlg + closePathCorr; i++) {
  25093. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25094. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25095. if (invertUV) {
  25096. uvs.push(v, u);
  25097. }
  25098. else {
  25099. uvs.push(u, v);
  25100. }
  25101. }
  25102. }
  25103. }
  25104. // indices
  25105. p = 0; // path index
  25106. var pi = 0; // positions array index
  25107. var l1 = lg[p] - 1; // path1 length
  25108. var l2 = lg[p + 1] - 1; // path2 length
  25109. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25110. var shft = idx[1] - idx[0]; // shift
  25111. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25112. while (pi <= min && p < path1nb) {
  25113. // 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
  25114. indices.push(pi, pi + shft, pi + 1);
  25115. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25116. pi += 1;
  25117. if (pi === min) {
  25118. p++;
  25119. if (p === lg.length - 1) {
  25120. shft = idx[0] - idx[p];
  25121. l1 = lg[p] - 1;
  25122. l2 = lg[0] - 1;
  25123. }
  25124. else {
  25125. shft = idx[p + 1] - idx[p];
  25126. l1 = lg[p] - 1;
  25127. l2 = lg[p + 1] - 1;
  25128. }
  25129. pi = idx[p];
  25130. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25131. }
  25132. }
  25133. // normals
  25134. VertexData.ComputeNormals(positions, indices, normals);
  25135. if (closePath) {
  25136. var indexFirst = 0;
  25137. var indexLast = 0;
  25138. for (p = 0; p < pathArray.length; p++) {
  25139. indexFirst = idx[p] * 3;
  25140. if (p + 1 < pathArray.length) {
  25141. indexLast = (idx[p + 1] - 1) * 3;
  25142. }
  25143. else {
  25144. indexLast = normals.length - 3;
  25145. }
  25146. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25147. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25148. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25149. normals[indexLast] = normals[indexFirst];
  25150. normals[indexLast + 1] = normals[indexFirst + 1];
  25151. normals[indexLast + 2] = normals[indexFirst + 2];
  25152. }
  25153. }
  25154. // sides
  25155. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25156. // Colors
  25157. if (customColors) {
  25158. var colors = new Float32Array(customColors.length * 4);
  25159. for (var c = 0; c < customColors.length; c++) {
  25160. colors[c * 4] = customColors[c].r;
  25161. colors[c * 4 + 1] = customColors[c].g;
  25162. colors[c * 4 + 2] = customColors[c].b;
  25163. colors[c * 4 + 3] = customColors[c].a;
  25164. }
  25165. }
  25166. // Result
  25167. var vertexData = new VertexData();
  25168. var positions32 = new Float32Array(positions);
  25169. var normals32 = new Float32Array(normals);
  25170. var uvs32 = new Float32Array(uvs);
  25171. vertexData.indices = indices;
  25172. vertexData.positions = positions32;
  25173. vertexData.normals = normals32;
  25174. vertexData.uvs = uvs32;
  25175. if (customColors) {
  25176. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25177. }
  25178. if (closePath) {
  25179. vertexData._idx = idx;
  25180. }
  25181. return vertexData;
  25182. };
  25183. /**
  25184. * Creates the VertexData of the Box.
  25185. */
  25186. VertexData.CreateBox = function (options) {
  25187. var normalsSource = [
  25188. new BABYLON.Vector3(0, 0, 1),
  25189. new BABYLON.Vector3(0, 0, -1),
  25190. new BABYLON.Vector3(1, 0, 0),
  25191. new BABYLON.Vector3(-1, 0, 0),
  25192. new BABYLON.Vector3(0, 1, 0),
  25193. new BABYLON.Vector3(0, -1, 0)
  25194. ];
  25195. var indices = [];
  25196. var positions = [];
  25197. var normals = [];
  25198. var uvs = [];
  25199. var width = options.width || options.size || 1;
  25200. var height = options.height || options.size || 1;
  25201. var depth = options.depth || options.size || 1;
  25202. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25203. var faceUV = options.faceUV || new Array(6);
  25204. var faceColors = options.faceColors;
  25205. var colors = [];
  25206. // default face colors and UV if undefined
  25207. for (var f = 0; f < 6; f++) {
  25208. if (faceUV[f] === undefined) {
  25209. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25210. }
  25211. if (faceColors && faceColors[f] === undefined) {
  25212. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25213. }
  25214. }
  25215. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25216. // Create each face in turn.
  25217. for (var index = 0; index < normalsSource.length; index++) {
  25218. var normal = normalsSource[index];
  25219. // Get two vectors perpendicular to the face normal and to each other.
  25220. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25221. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25222. // Six indices (two triangles) per face.
  25223. var verticesLength = positions.length / 3;
  25224. indices.push(verticesLength);
  25225. indices.push(verticesLength + 1);
  25226. indices.push(verticesLength + 2);
  25227. indices.push(verticesLength);
  25228. indices.push(verticesLength + 2);
  25229. indices.push(verticesLength + 3);
  25230. // Four vertices per face.
  25231. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25232. positions.push(vertex.x, vertex.y, vertex.z);
  25233. normals.push(normal.x, normal.y, normal.z);
  25234. uvs.push(faceUV[index].z, faceUV[index].w);
  25235. if (faceColors) {
  25236. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25237. }
  25238. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25239. positions.push(vertex.x, vertex.y, vertex.z);
  25240. normals.push(normal.x, normal.y, normal.z);
  25241. uvs.push(faceUV[index].x, faceUV[index].w);
  25242. if (faceColors) {
  25243. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25244. }
  25245. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25246. positions.push(vertex.x, vertex.y, vertex.z);
  25247. normals.push(normal.x, normal.y, normal.z);
  25248. uvs.push(faceUV[index].x, faceUV[index].y);
  25249. if (faceColors) {
  25250. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25251. }
  25252. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25253. positions.push(vertex.x, vertex.y, vertex.z);
  25254. normals.push(normal.x, normal.y, normal.z);
  25255. uvs.push(faceUV[index].z, faceUV[index].y);
  25256. if (faceColors) {
  25257. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25258. }
  25259. }
  25260. // sides
  25261. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25262. // Result
  25263. var vertexData = new VertexData();
  25264. vertexData.indices = indices;
  25265. vertexData.positions = positions;
  25266. vertexData.normals = normals;
  25267. vertexData.uvs = uvs;
  25268. if (faceColors) {
  25269. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25270. vertexData.colors = totalColors;
  25271. }
  25272. return vertexData;
  25273. };
  25274. /**
  25275. * Creates the VertexData of the Sphere.
  25276. */
  25277. VertexData.CreateSphere = function (options) {
  25278. var segments = options.segments || 32;
  25279. var diameterX = options.diameterX || options.diameter || 1;
  25280. var diameterY = options.diameterY || options.diameter || 1;
  25281. var diameterZ = options.diameterZ || options.diameter || 1;
  25282. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25283. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25284. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25285. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25286. var totalZRotationSteps = 2 + segments;
  25287. var totalYRotationSteps = 2 * totalZRotationSteps;
  25288. var indices = [];
  25289. var positions = [];
  25290. var normals = [];
  25291. var uvs = [];
  25292. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25293. var normalizedZ = zRotationStep / totalZRotationSteps;
  25294. var angleZ = normalizedZ * Math.PI * slice;
  25295. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25296. var normalizedY = yRotationStep / totalYRotationSteps;
  25297. var angleY = normalizedY * Math.PI * 2 * arc;
  25298. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25299. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25300. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25301. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25302. var vertex = complete.multiply(radius);
  25303. var normal = complete.divide(radius).normalize();
  25304. positions.push(vertex.x, vertex.y, vertex.z);
  25305. normals.push(normal.x, normal.y, normal.z);
  25306. uvs.push(normalizedY, normalizedZ);
  25307. }
  25308. if (zRotationStep > 0) {
  25309. var verticesCount = positions.length / 3;
  25310. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25311. indices.push((firstIndex));
  25312. indices.push((firstIndex + 1));
  25313. indices.push(firstIndex + totalYRotationSteps + 1);
  25314. indices.push((firstIndex + totalYRotationSteps + 1));
  25315. indices.push((firstIndex + 1));
  25316. indices.push((firstIndex + totalYRotationSteps + 2));
  25317. }
  25318. }
  25319. }
  25320. // Sides
  25321. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25322. // Result
  25323. var vertexData = new VertexData();
  25324. vertexData.indices = indices;
  25325. vertexData.positions = positions;
  25326. vertexData.normals = normals;
  25327. vertexData.uvs = uvs;
  25328. return vertexData;
  25329. };
  25330. /**
  25331. * Creates the VertexData of the Cylinder or Cone.
  25332. */
  25333. VertexData.CreateCylinder = function (options) {
  25334. var height = options.height || 2;
  25335. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25336. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25337. var tessellation = options.tessellation || 24;
  25338. var subdivisions = options.subdivisions || 1;
  25339. var hasRings = options.hasRings;
  25340. var enclose = options.enclose;
  25341. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25342. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25343. var faceUV = options.faceUV || new Array(3);
  25344. var faceColors = options.faceColors;
  25345. // default face colors and UV if undefined
  25346. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25347. var ringNb = (hasRings) ? subdivisions : 1;
  25348. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25349. var f;
  25350. for (f = 0; f < surfaceNb; f++) {
  25351. if (faceColors && faceColors[f] === undefined) {
  25352. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25353. }
  25354. }
  25355. for (f = 0; f < surfaceNb; f++) {
  25356. if (faceUV && faceUV[f] === undefined) {
  25357. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25358. }
  25359. }
  25360. var indices = [];
  25361. var positions = [];
  25362. var normals = [];
  25363. var uvs = [];
  25364. var colors = [];
  25365. var angle_step = Math.PI * 2 * arc / tessellation;
  25366. var angle;
  25367. var h;
  25368. var radius;
  25369. var tan = (diameterBottom - diameterTop) / 2 / height;
  25370. var ringVertex = BABYLON.Vector3.Zero();
  25371. var ringNormal = BABYLON.Vector3.Zero();
  25372. var ringFirstVertex = BABYLON.Vector3.Zero();
  25373. var ringFirstNormal = BABYLON.Vector3.Zero();
  25374. var quadNormal = BABYLON.Vector3.Zero();
  25375. var Y = BABYLON.Axis.Y;
  25376. // positions, normals, uvs
  25377. var i;
  25378. var j;
  25379. var r;
  25380. var ringIdx = 1;
  25381. var s = 1; // surface index
  25382. var cs = 0;
  25383. var v = 0;
  25384. for (i = 0; i <= subdivisions; i++) {
  25385. h = i / subdivisions;
  25386. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25387. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25388. for (r = 0; r < ringIdx; r++) {
  25389. if (hasRings) {
  25390. s += r;
  25391. }
  25392. if (enclose) {
  25393. s += 2 * r;
  25394. }
  25395. for (j = 0; j <= tessellation; j++) {
  25396. angle = j * angle_step;
  25397. // position
  25398. ringVertex.x = Math.cos(-angle) * radius;
  25399. ringVertex.y = -height / 2 + h * height;
  25400. ringVertex.z = Math.sin(-angle) * radius;
  25401. // normal
  25402. if (diameterTop === 0 && i === subdivisions) {
  25403. // if no top cap, reuse former normals
  25404. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25405. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25406. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25407. }
  25408. else {
  25409. ringNormal.x = ringVertex.x;
  25410. ringNormal.z = ringVertex.z;
  25411. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25412. ringNormal.normalize();
  25413. }
  25414. // keep first ring vertex values for enclose
  25415. if (j === 0) {
  25416. ringFirstVertex.copyFrom(ringVertex);
  25417. ringFirstNormal.copyFrom(ringNormal);
  25418. }
  25419. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25420. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25421. if (hasRings) {
  25422. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25423. }
  25424. else {
  25425. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25426. }
  25427. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25428. if (faceColors) {
  25429. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25430. }
  25431. }
  25432. // if enclose, add four vertices and their dedicated normals
  25433. if (arc !== 1 && enclose) {
  25434. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25435. positions.push(0, ringVertex.y, 0);
  25436. positions.push(0, ringVertex.y, 0);
  25437. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25438. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25439. quadNormal.normalize();
  25440. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25441. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25442. quadNormal.normalize();
  25443. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25444. if (hasRings) {
  25445. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25446. }
  25447. else {
  25448. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25449. }
  25450. uvs.push(faceUV[s + 1].x, v);
  25451. uvs.push(faceUV[s + 1].z, v);
  25452. if (hasRings) {
  25453. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25454. }
  25455. else {
  25456. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25457. }
  25458. uvs.push(faceUV[s + 2].x, v);
  25459. uvs.push(faceUV[s + 2].z, v);
  25460. if (faceColors) {
  25461. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25462. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25463. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25464. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25465. }
  25466. }
  25467. if (cs !== s) {
  25468. cs = s;
  25469. }
  25470. }
  25471. }
  25472. // indices
  25473. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25474. var s;
  25475. i = 0;
  25476. for (s = 0; s < subdivisions; s++) {
  25477. for (j = 0; j < tessellation; j++) {
  25478. var i0 = i * (e + 1) + j;
  25479. var i1 = (i + 1) * (e + 1) + j;
  25480. var i2 = i * (e + 1) + (j + 1);
  25481. var i3 = (i + 1) * (e + 1) + (j + 1);
  25482. indices.push(i0, i1, i2);
  25483. indices.push(i3, i2, i1);
  25484. }
  25485. if (arc !== 1 && enclose) {
  25486. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25487. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25488. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25489. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25490. }
  25491. i = (hasRings) ? (i + 2) : (i + 1);
  25492. }
  25493. // Caps
  25494. var createCylinderCap = function (isTop) {
  25495. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25496. if (radius === 0) {
  25497. return;
  25498. }
  25499. // Cap positions, normals & uvs
  25500. var angle;
  25501. var circleVector;
  25502. var i;
  25503. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25504. var c;
  25505. if (faceColors) {
  25506. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25507. }
  25508. // cap center
  25509. var vbase = positions.length / 3;
  25510. var offset = isTop ? height / 2 : -height / 2;
  25511. var center = new BABYLON.Vector3(0, offset, 0);
  25512. positions.push(center.x, center.y, center.z);
  25513. normals.push(0, isTop ? 1 : -1, 0);
  25514. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25515. if (faceColors) {
  25516. colors.push(c.r, c.g, c.b, c.a);
  25517. }
  25518. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25519. for (i = 0; i <= tessellation; i++) {
  25520. angle = Math.PI * 2 * i * arc / tessellation;
  25521. var cos = Math.cos(-angle);
  25522. var sin = Math.sin(-angle);
  25523. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25524. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25525. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25526. normals.push(0, isTop ? 1 : -1, 0);
  25527. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25528. if (faceColors) {
  25529. colors.push(c.r, c.g, c.b, c.a);
  25530. }
  25531. }
  25532. // Cap indices
  25533. for (i = 0; i < tessellation; i++) {
  25534. if (!isTop) {
  25535. indices.push(vbase);
  25536. indices.push(vbase + (i + 1));
  25537. indices.push(vbase + (i + 2));
  25538. }
  25539. else {
  25540. indices.push(vbase);
  25541. indices.push(vbase + (i + 2));
  25542. indices.push(vbase + (i + 1));
  25543. }
  25544. }
  25545. };
  25546. // add caps to geometry
  25547. createCylinderCap(false);
  25548. createCylinderCap(true);
  25549. // Sides
  25550. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25551. var vertexData = new VertexData();
  25552. vertexData.indices = indices;
  25553. vertexData.positions = positions;
  25554. vertexData.normals = normals;
  25555. vertexData.uvs = uvs;
  25556. if (faceColors) {
  25557. vertexData.colors = colors;
  25558. }
  25559. return vertexData;
  25560. };
  25561. /**
  25562. * Creates the VertexData of the Torus.
  25563. */
  25564. VertexData.CreateTorus = function (options) {
  25565. var indices = [];
  25566. var positions = [];
  25567. var normals = [];
  25568. var uvs = [];
  25569. var diameter = options.diameter || 1;
  25570. var thickness = options.thickness || 0.5;
  25571. var tessellation = options.tessellation || 16;
  25572. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25573. var stride = tessellation + 1;
  25574. for (var i = 0; i <= tessellation; i++) {
  25575. var u = i / tessellation;
  25576. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25577. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25578. for (var j = 0; j <= tessellation; j++) {
  25579. var v = 1 - j / tessellation;
  25580. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25581. var dx = Math.cos(innerAngle);
  25582. var dy = Math.sin(innerAngle);
  25583. // Create a vertex.
  25584. var normal = new BABYLON.Vector3(dx, dy, 0);
  25585. var position = normal.scale(thickness / 2);
  25586. var textureCoordinate = new BABYLON.Vector2(u, v);
  25587. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25588. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25589. positions.push(position.x, position.y, position.z);
  25590. normals.push(normal.x, normal.y, normal.z);
  25591. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25592. // And create indices for two triangles.
  25593. var nextI = (i + 1) % stride;
  25594. var nextJ = (j + 1) % stride;
  25595. indices.push(i * stride + j);
  25596. indices.push(i * stride + nextJ);
  25597. indices.push(nextI * stride + j);
  25598. indices.push(i * stride + nextJ);
  25599. indices.push(nextI * stride + nextJ);
  25600. indices.push(nextI * stride + j);
  25601. }
  25602. }
  25603. // Sides
  25604. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25605. // Result
  25606. var vertexData = new VertexData();
  25607. vertexData.indices = indices;
  25608. vertexData.positions = positions;
  25609. vertexData.normals = normals;
  25610. vertexData.uvs = uvs;
  25611. return vertexData;
  25612. };
  25613. /**
  25614. * Creates the VertexData of the LineSystem.
  25615. */
  25616. VertexData.CreateLineSystem = function (options) {
  25617. var indices = [];
  25618. var positions = [];
  25619. var lines = options.lines;
  25620. var idx = 0;
  25621. for (var l = 0; l < lines.length; l++) {
  25622. var points = lines[l];
  25623. for (var index = 0; index < points.length; index++) {
  25624. positions.push(points[index].x, points[index].y, points[index].z);
  25625. if (index > 0) {
  25626. indices.push(idx - 1);
  25627. indices.push(idx);
  25628. }
  25629. idx++;
  25630. }
  25631. }
  25632. var vertexData = new VertexData();
  25633. vertexData.indices = indices;
  25634. vertexData.positions = positions;
  25635. return vertexData;
  25636. };
  25637. /**
  25638. * Create the VertexData of the DashedLines.
  25639. */
  25640. VertexData.CreateDashedLines = function (options) {
  25641. var dashSize = options.dashSize || 3;
  25642. var gapSize = options.gapSize || 1;
  25643. var dashNb = options.dashNb || 200;
  25644. var points = options.points;
  25645. var positions = new Array();
  25646. var indices = new Array();
  25647. var curvect = BABYLON.Vector3.Zero();
  25648. var lg = 0;
  25649. var nb = 0;
  25650. var shft = 0;
  25651. var dashshft = 0;
  25652. var curshft = 0;
  25653. var idx = 0;
  25654. var i = 0;
  25655. for (i = 0; i < points.length - 1; i++) {
  25656. points[i + 1].subtractToRef(points[i], curvect);
  25657. lg += curvect.length();
  25658. }
  25659. shft = lg / dashNb;
  25660. dashshft = dashSize * shft / (dashSize + gapSize);
  25661. for (i = 0; i < points.length - 1; i++) {
  25662. points[i + 1].subtractToRef(points[i], curvect);
  25663. nb = Math.floor(curvect.length() / shft);
  25664. curvect.normalize();
  25665. for (var j = 0; j < nb; j++) {
  25666. curshft = shft * j;
  25667. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25668. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25669. indices.push(idx, idx + 1);
  25670. idx += 2;
  25671. }
  25672. }
  25673. // Result
  25674. var vertexData = new VertexData();
  25675. vertexData.positions = positions;
  25676. vertexData.indices = indices;
  25677. return vertexData;
  25678. };
  25679. /**
  25680. * Creates the VertexData of the Ground.
  25681. */
  25682. VertexData.CreateGround = function (options) {
  25683. var indices = [];
  25684. var positions = [];
  25685. var normals = [];
  25686. var uvs = [];
  25687. var row, col;
  25688. var width = options.width || 1;
  25689. var height = options.height || 1;
  25690. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25691. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25692. for (row = 0; row <= subdivisionsY; row++) {
  25693. for (col = 0; col <= subdivisionsX; col++) {
  25694. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25695. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25696. positions.push(position.x, position.y, position.z);
  25697. normals.push(normal.x, normal.y, normal.z);
  25698. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25699. }
  25700. }
  25701. for (row = 0; row < subdivisionsY; row++) {
  25702. for (col = 0; col < subdivisionsX; col++) {
  25703. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25704. indices.push(col + 1 + row * (subdivisionsX + 1));
  25705. indices.push(col + row * (subdivisionsX + 1));
  25706. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25707. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25708. indices.push(col + row * (subdivisionsX + 1));
  25709. }
  25710. }
  25711. // Result
  25712. var vertexData = new VertexData();
  25713. vertexData.indices = indices;
  25714. vertexData.positions = positions;
  25715. vertexData.normals = normals;
  25716. vertexData.uvs = uvs;
  25717. return vertexData;
  25718. };
  25719. /**
  25720. * Creates the VertexData of the TiledGround.
  25721. */
  25722. VertexData.CreateTiledGround = function (options) {
  25723. var xmin = options.xmin || -1.0;
  25724. var zmin = options.zmin || -1.0;
  25725. var xmax = options.xmax || 1.0;
  25726. var zmax = options.zmax || 1.0;
  25727. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25728. var precision = options.precision || { w: 1, h: 1 };
  25729. var indices = [];
  25730. var positions = [];
  25731. var normals = [];
  25732. var uvs = [];
  25733. var row, col, tileRow, tileCol;
  25734. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25735. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25736. precision.w = (precision.w < 1) ? 1 : precision.w;
  25737. precision.h = (precision.h < 1) ? 1 : precision.h;
  25738. var tileSize = {
  25739. 'w': (xmax - xmin) / subdivisions.w,
  25740. 'h': (zmax - zmin) / subdivisions.h
  25741. };
  25742. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25743. // Indices
  25744. var base = positions.length / 3;
  25745. var rowLength = precision.w + 1;
  25746. for (row = 0; row < precision.h; row++) {
  25747. for (col = 0; col < precision.w; col++) {
  25748. var square = [
  25749. base + col + row * rowLength,
  25750. base + (col + 1) + row * rowLength,
  25751. base + (col + 1) + (row + 1) * rowLength,
  25752. base + col + (row + 1) * rowLength
  25753. ];
  25754. indices.push(square[1]);
  25755. indices.push(square[2]);
  25756. indices.push(square[3]);
  25757. indices.push(square[0]);
  25758. indices.push(square[1]);
  25759. indices.push(square[3]);
  25760. }
  25761. }
  25762. // Position, normals and uvs
  25763. var position = BABYLON.Vector3.Zero();
  25764. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25765. for (row = 0; row <= precision.h; row++) {
  25766. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25767. for (col = 0; col <= precision.w; col++) {
  25768. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25769. position.y = 0;
  25770. positions.push(position.x, position.y, position.z);
  25771. normals.push(normal.x, normal.y, normal.z);
  25772. uvs.push(col / precision.w, row / precision.h);
  25773. }
  25774. }
  25775. }
  25776. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25777. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25778. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25779. }
  25780. }
  25781. // Result
  25782. var vertexData = new VertexData();
  25783. vertexData.indices = indices;
  25784. vertexData.positions = positions;
  25785. vertexData.normals = normals;
  25786. vertexData.uvs = uvs;
  25787. return vertexData;
  25788. };
  25789. /**
  25790. * Creates the VertexData of the Ground designed from a heightmap.
  25791. */
  25792. VertexData.CreateGroundFromHeightMap = function (options) {
  25793. var indices = [];
  25794. var positions = [];
  25795. var normals = [];
  25796. var uvs = [];
  25797. var row, col;
  25798. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25799. // Vertices
  25800. for (row = 0; row <= options.subdivisions; row++) {
  25801. for (col = 0; col <= options.subdivisions; col++) {
  25802. 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));
  25803. // Compute height
  25804. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25805. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25806. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25807. var r = options.buffer[pos] / 255.0;
  25808. var g = options.buffer[pos + 1] / 255.0;
  25809. var b = options.buffer[pos + 2] / 255.0;
  25810. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25811. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25812. // Add vertex
  25813. positions.push(position.x, position.y, position.z);
  25814. normals.push(0, 0, 0);
  25815. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25816. }
  25817. }
  25818. // Indices
  25819. for (row = 0; row < options.subdivisions; row++) {
  25820. for (col = 0; col < options.subdivisions; col++) {
  25821. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25822. indices.push(col + 1 + row * (options.subdivisions + 1));
  25823. indices.push(col + row * (options.subdivisions + 1));
  25824. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25825. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25826. indices.push(col + row * (options.subdivisions + 1));
  25827. }
  25828. }
  25829. // Normals
  25830. VertexData.ComputeNormals(positions, indices, normals);
  25831. // Result
  25832. var vertexData = new VertexData();
  25833. vertexData.indices = indices;
  25834. vertexData.positions = positions;
  25835. vertexData.normals = normals;
  25836. vertexData.uvs = uvs;
  25837. return vertexData;
  25838. };
  25839. /**
  25840. * Creates the VertexData of the Plane.
  25841. */
  25842. VertexData.CreatePlane = function (options) {
  25843. var indices = [];
  25844. var positions = [];
  25845. var normals = [];
  25846. var uvs = [];
  25847. var width = options.width || options.size || 1;
  25848. var height = options.height || options.size || 1;
  25849. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25850. // Vertices
  25851. var halfWidth = width / 2.0;
  25852. var halfHeight = height / 2.0;
  25853. positions.push(-halfWidth, -halfHeight, 0);
  25854. normals.push(0, 0, -1.0);
  25855. uvs.push(0.0, 0.0);
  25856. positions.push(halfWidth, -halfHeight, 0);
  25857. normals.push(0, 0, -1.0);
  25858. uvs.push(1.0, 0.0);
  25859. positions.push(halfWidth, halfHeight, 0);
  25860. normals.push(0, 0, -1.0);
  25861. uvs.push(1.0, 1.0);
  25862. positions.push(-halfWidth, halfHeight, 0);
  25863. normals.push(0, 0, -1.0);
  25864. uvs.push(0.0, 1.0);
  25865. // Indices
  25866. indices.push(0);
  25867. indices.push(1);
  25868. indices.push(2);
  25869. indices.push(0);
  25870. indices.push(2);
  25871. indices.push(3);
  25872. // Sides
  25873. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25874. // Result
  25875. var vertexData = new VertexData();
  25876. vertexData.indices = indices;
  25877. vertexData.positions = positions;
  25878. vertexData.normals = normals;
  25879. vertexData.uvs = uvs;
  25880. return vertexData;
  25881. };
  25882. /**
  25883. * Creates the VertexData of the Disc or regular Polygon.
  25884. */
  25885. VertexData.CreateDisc = function (options) {
  25886. var positions = [];
  25887. var indices = [];
  25888. var normals = [];
  25889. var uvs = [];
  25890. var radius = options.radius || 0.5;
  25891. var tessellation = options.tessellation || 64;
  25892. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25893. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25894. // positions and uvs
  25895. positions.push(0, 0, 0); // disc center first
  25896. uvs.push(0.5, 0.5);
  25897. var theta = Math.PI * 2 * arc;
  25898. var step = theta / tessellation;
  25899. for (var a = 0; a < theta; a += step) {
  25900. var x = Math.cos(a);
  25901. var y = Math.sin(a);
  25902. var u = (x + 1) / 2;
  25903. var v = (1 - y) / 2;
  25904. positions.push(radius * x, radius * y, 0);
  25905. uvs.push(u, v);
  25906. }
  25907. if (arc === 1) {
  25908. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25909. uvs.push(uvs[2], uvs[3]);
  25910. }
  25911. //indices
  25912. var vertexNb = positions.length / 3;
  25913. for (var i = 1; i < vertexNb - 1; i++) {
  25914. indices.push(i + 1, 0, i);
  25915. }
  25916. // result
  25917. VertexData.ComputeNormals(positions, indices, normals);
  25918. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25919. var vertexData = new VertexData();
  25920. vertexData.indices = indices;
  25921. vertexData.positions = positions;
  25922. vertexData.normals = normals;
  25923. vertexData.uvs = uvs;
  25924. return vertexData;
  25925. };
  25926. /**
  25927. * Re-creates the VertexData of the Polygon for sideOrientation.
  25928. */
  25929. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  25930. var faceUV = fUV || new Array(3);
  25931. var faceColors = fColors;
  25932. var colors = [];
  25933. // default face colors and UV if undefined
  25934. for (var f = 0; f < 3; f++) {
  25935. if (faceUV[f] === undefined) {
  25936. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25937. }
  25938. if (faceColors && faceColors[f] === undefined) {
  25939. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25940. }
  25941. }
  25942. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25943. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25944. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25945. var indices = polygon.getIndices();
  25946. // set face colours and textures
  25947. var idx = 0;
  25948. var face = 0;
  25949. for (var index = 0; index < normals.length; index += 3) {
  25950. //Edge Face no. 1
  25951. if (Math.abs(normals[index + 1]) == 0) {
  25952. face = 1;
  25953. }
  25954. //Top Face no. 0
  25955. if (normals[index + 1] == 1) {
  25956. face = 0;
  25957. }
  25958. //Bottom Face no. 2
  25959. if (normals[index + 1] == -1) {
  25960. face = 2;
  25961. }
  25962. idx = index / 3;
  25963. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  25964. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  25965. if (faceColors) {
  25966. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  25967. }
  25968. }
  25969. // sides
  25970. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  25971. // Result
  25972. var vertexData = new VertexData();
  25973. vertexData.indices = indices;
  25974. vertexData.positions = positions;
  25975. vertexData.normals = normals;
  25976. vertexData.uvs = uvs;
  25977. if (faceColors) {
  25978. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25979. vertexData.colors = totalColors;
  25980. }
  25981. return vertexData;
  25982. };
  25983. /**
  25984. * Creates the VertexData of the IcoSphere.
  25985. */
  25986. VertexData.CreateIcoSphere = function (options) {
  25987. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25988. var radius = options.radius || 1;
  25989. var flat = (options.flat === undefined) ? true : options.flat;
  25990. var subdivisions = options.subdivisions || 4;
  25991. var radiusX = options.radiusX || radius;
  25992. var radiusY = options.radiusY || radius;
  25993. var radiusZ = options.radiusZ || radius;
  25994. var t = (1 + Math.sqrt(5)) / 2;
  25995. // 12 vertex x,y,z
  25996. var ico_vertices = [
  25997. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25998. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25999. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26000. ];
  26001. // index of 3 vertex makes a face of icopshere
  26002. var ico_indices = [
  26003. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26004. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26005. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26006. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26007. ];
  26008. // vertex for uv have aliased position, not for UV
  26009. var vertices_unalias_id = [
  26010. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26011. // vertex alias
  26012. 0,
  26013. 2,
  26014. 3,
  26015. 3,
  26016. 3,
  26017. 4,
  26018. 7,
  26019. 8,
  26020. 9,
  26021. 9,
  26022. 10,
  26023. 11 // 23: B + 12
  26024. ];
  26025. // uv as integer step (not pixels !)
  26026. var ico_vertexuv = [
  26027. 5, 1, 3, 1, 6, 4, 0, 0,
  26028. 5, 3, 4, 2, 2, 2, 4, 0,
  26029. 2, 0, 1, 1, 6, 0, 6, 2,
  26030. // vertex alias (for same vertex on different faces)
  26031. 0, 4,
  26032. 3, 3,
  26033. 4, 4,
  26034. 3, 1,
  26035. 4, 2,
  26036. 4, 4,
  26037. 0, 2,
  26038. 1, 1,
  26039. 2, 2,
  26040. 3, 3,
  26041. 1, 3,
  26042. 2, 4 // 23: B + 12
  26043. ];
  26044. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26045. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26046. // First island of uv mapping
  26047. // v = 4h 3+ 2
  26048. // v = 3h 9+ 4
  26049. // v = 2h 9+ 5 B
  26050. // v = 1h 9 1 0
  26051. // v = 0h 3 8 7 A
  26052. // u = 0 1 2 3 4 5 6 *a
  26053. // Second island of uv mapping
  26054. // v = 4h 0+ B+ 4+
  26055. // v = 3h A+ 2+
  26056. // v = 2h 7+ 6 3+
  26057. // v = 1h 8+ 3+
  26058. // v = 0h
  26059. // u = 0 1 2 3 4 5 6 *a
  26060. // Face layout on texture UV mapping
  26061. // ============
  26062. // \ 4 /\ 16 / ======
  26063. // \ / \ / /\ 11 /
  26064. // \/ 7 \/ / \ /
  26065. // ======= / 10 \/
  26066. // /\ 17 /\ =======
  26067. // / \ / \ \ 15 /\
  26068. // / 8 \/ 12 \ \ / \
  26069. // ============ \/ 6 \
  26070. // \ 18 /\ ============
  26071. // \ / \ \ 5 /\ 0 /
  26072. // \/ 13 \ \ / \ /
  26073. // ======= \/ 1 \/
  26074. // =============
  26075. // /\ 19 /\ 2 /\
  26076. // / \ / \ / \
  26077. // / 14 \/ 9 \/ 3 \
  26078. // ===================
  26079. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26080. var ustep = 138 / 1024;
  26081. var vstep = 239 / 1024;
  26082. var uoffset = 60 / 1024;
  26083. var voffset = 26 / 1024;
  26084. // Second island should have margin, not to touch the first island
  26085. // avoid any borderline artefact in pixel rounding
  26086. var island_u_offset = -40 / 1024;
  26087. var island_v_offset = +20 / 1024;
  26088. // face is either island 0 or 1 :
  26089. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26090. var island = [
  26091. 0, 0, 0, 0, 1,
  26092. 0, 0, 1, 1, 0,
  26093. 0, 0, 1, 1, 0,
  26094. 0, 1, 1, 1, 0 // 15 - 19
  26095. ];
  26096. var indices = [];
  26097. var positions = [];
  26098. var normals = [];
  26099. var uvs = [];
  26100. var current_indice = 0;
  26101. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26102. var face_vertex_pos = new Array(3);
  26103. var face_vertex_uv = new Array(3);
  26104. var v012;
  26105. for (v012 = 0; v012 < 3; v012++) {
  26106. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26107. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26108. }
  26109. // create all with normals
  26110. for (var face = 0; face < 20; face++) {
  26111. // 3 vertex per face
  26112. for (v012 = 0; v012 < 3; v012++) {
  26113. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26114. var v_id = ico_indices[3 * face + v012];
  26115. // vertex have 3D position (x,y,z)
  26116. 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]);
  26117. // Normalize to get normal, then scale to radius
  26118. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26119. // uv Coordinates from vertex ID
  26120. 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);
  26121. }
  26122. // Subdivide the face (interpolate pos, norm, uv)
  26123. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26124. // - norm is linear interpolation of vertex corner normal
  26125. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26126. // - uv is linear interpolation
  26127. //
  26128. // Topology is as below for sub-divide by 2
  26129. // vertex shown as v0,v1,v2
  26130. // interp index is i1 to progress in range [v0,v1[
  26131. // interp index is i2 to progress in range [v0,v2[
  26132. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26133. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26134. //
  26135. //
  26136. // i2 v2
  26137. // ^ ^
  26138. // / / \
  26139. // / / \
  26140. // / / \
  26141. // / / (0,1) \
  26142. // / #---------\
  26143. // / / \ (0,0)'/ \
  26144. // / / \ / \
  26145. // / / \ / \
  26146. // / / (0,0) \ / (1,0) \
  26147. // / #---------#---------\
  26148. // v0 v1
  26149. //
  26150. // --------------------> i1
  26151. //
  26152. // interp of (i1,i2):
  26153. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26154. // along i1 : lerp(x0,x1, i1/(S-i2))
  26155. //
  26156. // centroid of triangle is needed to get help normal computation
  26157. // (c1,c2) are used for centroid location
  26158. var interp_vertex = function (i1, i2, c1, c2) {
  26159. // vertex is interpolated from
  26160. // - face_vertex_pos[0..2]
  26161. // - face_vertex_uv[0..2]
  26162. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26163. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26164. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26165. pos_interp.normalize();
  26166. var vertex_normal;
  26167. if (flat) {
  26168. // in flat mode, recalculate normal as face centroid normal
  26169. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26170. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26171. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26172. }
  26173. else {
  26174. // in smooth mode, recalculate normal from each single vertex position
  26175. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26176. }
  26177. // Vertex normal need correction due to X,Y,Z radius scaling
  26178. vertex_normal.x /= radiusX;
  26179. vertex_normal.y /= radiusY;
  26180. vertex_normal.z /= radiusZ;
  26181. vertex_normal.normalize();
  26182. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26183. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26184. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26185. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26186. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26187. uvs.push(uv_interp.x, uv_interp.y);
  26188. // push each vertex has member of a face
  26189. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26190. indices.push(current_indice);
  26191. current_indice++;
  26192. };
  26193. for (var i2 = 0; i2 < subdivisions; i2++) {
  26194. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26195. // face : (i1,i2) for /\ :
  26196. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26197. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26198. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26199. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26200. if (i1 + i2 + 1 < subdivisions) {
  26201. // face : (i1,i2)' for \/ :
  26202. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26203. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26204. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26205. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26206. }
  26207. }
  26208. }
  26209. }
  26210. // Sides
  26211. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26212. // Result
  26213. var vertexData = new VertexData();
  26214. vertexData.indices = indices;
  26215. vertexData.positions = positions;
  26216. vertexData.normals = normals;
  26217. vertexData.uvs = uvs;
  26218. return vertexData;
  26219. };
  26220. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26221. /**
  26222. * Creates the VertexData of the Polyhedron.
  26223. */
  26224. VertexData.CreatePolyhedron = function (options) {
  26225. // provided polyhedron types :
  26226. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26227. // 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)
  26228. var polyhedra = [];
  26229. 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]] };
  26230. 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]] };
  26231. polyhedra[2] = {
  26232. 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]],
  26233. 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]]
  26234. };
  26235. polyhedra[3] = {
  26236. 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]],
  26237. 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]]
  26238. };
  26239. polyhedra[4] = {
  26240. 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]],
  26241. 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]]
  26242. };
  26243. 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]] };
  26244. 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]] };
  26245. 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]] };
  26246. 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]] };
  26247. 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]] };
  26248. 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]] };
  26249. 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]] };
  26250. 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]] };
  26251. 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]] };
  26252. polyhedra[14] = {
  26253. 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]],
  26254. 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]]
  26255. };
  26256. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26257. var size = options.size;
  26258. var sizeX = options.sizeX || size || 1;
  26259. var sizeY = options.sizeY || size || 1;
  26260. var sizeZ = options.sizeZ || size || 1;
  26261. var data = options.custom || polyhedra[type];
  26262. var nbfaces = data.face.length;
  26263. var faceUV = options.faceUV || new Array(nbfaces);
  26264. var faceColors = options.faceColors;
  26265. var flat = (options.flat === undefined) ? true : options.flat;
  26266. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26267. var positions = [];
  26268. var indices = [];
  26269. var normals = [];
  26270. var uvs = [];
  26271. var colors = [];
  26272. var index = 0;
  26273. var faceIdx = 0; // face cursor in the array "indexes"
  26274. var indexes = [];
  26275. var i = 0;
  26276. var f = 0;
  26277. var u, v, ang, x, y, tmp;
  26278. // default face colors and UV if undefined
  26279. if (flat) {
  26280. for (f = 0; f < nbfaces; f++) {
  26281. if (faceColors && faceColors[f] === undefined) {
  26282. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26283. }
  26284. if (faceUV && faceUV[f] === undefined) {
  26285. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26286. }
  26287. }
  26288. }
  26289. if (!flat) {
  26290. for (i = 0; i < data.vertex.length; i++) {
  26291. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26292. uvs.push(0, 0);
  26293. }
  26294. for (f = 0; f < nbfaces; f++) {
  26295. for (i = 0; i < data.face[f].length - 2; i++) {
  26296. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26297. }
  26298. }
  26299. }
  26300. else {
  26301. for (f = 0; f < nbfaces; f++) {
  26302. var fl = data.face[f].length; // number of vertices of the current face
  26303. ang = 2 * Math.PI / fl;
  26304. x = 0.5 * Math.tan(ang / 2);
  26305. y = 0.5;
  26306. // positions, uvs, colors
  26307. for (i = 0; i < fl; i++) {
  26308. // positions
  26309. 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);
  26310. indexes.push(index);
  26311. index++;
  26312. // uvs
  26313. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26314. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26315. uvs.push(u, v);
  26316. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26317. y = x * Math.sin(ang) + y * Math.cos(ang);
  26318. x = tmp;
  26319. // colors
  26320. if (faceColors) {
  26321. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26322. }
  26323. }
  26324. // indices from indexes
  26325. for (i = 0; i < fl - 2; i++) {
  26326. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26327. }
  26328. faceIdx += fl;
  26329. }
  26330. }
  26331. VertexData.ComputeNormals(positions, indices, normals);
  26332. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26333. var vertexData = new VertexData();
  26334. vertexData.positions = positions;
  26335. vertexData.indices = indices;
  26336. vertexData.normals = normals;
  26337. vertexData.uvs = uvs;
  26338. if (faceColors && flat) {
  26339. vertexData.colors = colors;
  26340. }
  26341. return vertexData;
  26342. };
  26343. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26344. /**
  26345. * Creates the VertexData of the Torus Knot.
  26346. */
  26347. VertexData.CreateTorusKnot = function (options) {
  26348. var indices = [];
  26349. var positions = [];
  26350. var normals = [];
  26351. var uvs = [];
  26352. var radius = options.radius || 2;
  26353. var tube = options.tube || 0.5;
  26354. var radialSegments = options.radialSegments || 32;
  26355. var tubularSegments = options.tubularSegments || 32;
  26356. var p = options.p || 2;
  26357. var q = options.q || 3;
  26358. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26359. // Helper
  26360. var getPos = function (angle) {
  26361. var cu = Math.cos(angle);
  26362. var su = Math.sin(angle);
  26363. var quOverP = q / p * angle;
  26364. var cs = Math.cos(quOverP);
  26365. var tx = radius * (2 + cs) * 0.5 * cu;
  26366. var ty = radius * (2 + cs) * su * 0.5;
  26367. var tz = radius * Math.sin(quOverP) * 0.5;
  26368. return new BABYLON.Vector3(tx, ty, tz);
  26369. };
  26370. // Vertices
  26371. var i;
  26372. var j;
  26373. for (i = 0; i <= radialSegments; i++) {
  26374. var modI = i % radialSegments;
  26375. var u = modI / radialSegments * 2 * p * Math.PI;
  26376. var p1 = getPos(u);
  26377. var p2 = getPos(u + 0.01);
  26378. var tang = p2.subtract(p1);
  26379. var n = p2.add(p1);
  26380. var bitan = BABYLON.Vector3.Cross(tang, n);
  26381. n = BABYLON.Vector3.Cross(bitan, tang);
  26382. bitan.normalize();
  26383. n.normalize();
  26384. for (j = 0; j < tubularSegments; j++) {
  26385. var modJ = j % tubularSegments;
  26386. var v = modJ / tubularSegments * 2 * Math.PI;
  26387. var cx = -tube * Math.cos(v);
  26388. var cy = tube * Math.sin(v);
  26389. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26390. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26391. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26392. uvs.push(i / radialSegments);
  26393. uvs.push(j / tubularSegments);
  26394. }
  26395. }
  26396. for (i = 0; i < radialSegments; i++) {
  26397. for (j = 0; j < tubularSegments; j++) {
  26398. var jNext = (j + 1) % tubularSegments;
  26399. var a = i * tubularSegments + j;
  26400. var b = (i + 1) * tubularSegments + j;
  26401. var c = (i + 1) * tubularSegments + jNext;
  26402. var d = i * tubularSegments + jNext;
  26403. indices.push(d);
  26404. indices.push(b);
  26405. indices.push(a);
  26406. indices.push(d);
  26407. indices.push(c);
  26408. indices.push(b);
  26409. }
  26410. }
  26411. // Normals
  26412. VertexData.ComputeNormals(positions, indices, normals);
  26413. // Sides
  26414. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26415. // Result
  26416. var vertexData = new VertexData();
  26417. vertexData.indices = indices;
  26418. vertexData.positions = positions;
  26419. vertexData.normals = normals;
  26420. vertexData.uvs = uvs;
  26421. return vertexData;
  26422. };
  26423. // Tools
  26424. /**
  26425. * @param {any} - positions (number[] or Float32Array)
  26426. * @param {any} - indices (number[] or Uint16Array)
  26427. * @param {any} - normals (number[] or Float32Array)
  26428. * options (optional) :
  26429. * facetPositions : optional array of facet positions (vector3)
  26430. * facetNormals : optional array of facet normals (vector3)
  26431. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26432. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26433. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26434. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26435. * bInfo : optional bounding info, required for facetPartitioning computation
  26436. */
  26437. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26438. // temporary scalar variables
  26439. var index = 0; // facet index
  26440. var p1p2x = 0.0; // p1p2 vector x coordinate
  26441. var p1p2y = 0.0; // p1p2 vector y coordinate
  26442. var p1p2z = 0.0; // p1p2 vector z coordinate
  26443. var p3p2x = 0.0; // p3p2 vector x coordinate
  26444. var p3p2y = 0.0; // p3p2 vector y coordinate
  26445. var p3p2z = 0.0; // p3p2 vector z coordinate
  26446. var faceNormalx = 0.0; // facet normal x coordinate
  26447. var faceNormaly = 0.0; // facet normal y coordinate
  26448. var faceNormalz = 0.0; // facet normal z coordinate
  26449. var length = 0.0; // facet normal length before normalization
  26450. var v1x = 0; // vector1 x index in the positions array
  26451. var v1y = 0; // vector1 y index in the positions array
  26452. var v1z = 0; // vector1 z index in the positions array
  26453. var v2x = 0; // vector2 x index in the positions array
  26454. var v2y = 0; // vector2 y index in the positions array
  26455. var v2z = 0; // vector2 z index in the positions array
  26456. var v3x = 0; // vector3 x index in the positions array
  26457. var v3y = 0; // vector3 y index in the positions array
  26458. var v3z = 0; // vector3 z index in the positions array
  26459. var computeFacetNormals = false;
  26460. var computeFacetPositions = false;
  26461. var computeFacetPartitioning = false;
  26462. var faceNormalSign = 1;
  26463. if (options) {
  26464. computeFacetNormals = (options.facetNormals) ? true : false;
  26465. computeFacetPositions = (options.facetPositions) ? true : false;
  26466. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26467. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26468. }
  26469. // facetPartitioning reinit if needed
  26470. if (computeFacetPartitioning) {
  26471. var ox = 0; // X partitioning index for facet position
  26472. var oy = 0; // Y partinioning index for facet position
  26473. var oz = 0; // Z partinioning index for facet position
  26474. var b1x = 0; // X partitioning index for facet v1 vertex
  26475. var b1y = 0; // Y partitioning index for facet v1 vertex
  26476. var b1z = 0; // z partitioning index for facet v1 vertex
  26477. var b2x = 0; // X partitioning index for facet v2 vertex
  26478. var b2y = 0; // Y partitioning index for facet v2 vertex
  26479. var b2z = 0; // Z partitioning index for facet v2 vertex
  26480. var b3x = 0; // X partitioning index for facet v3 vertex
  26481. var b3y = 0; // Y partitioning index for facet v3 vertex
  26482. var b3z = 0; // Z partitioning index for facet v3 vertex
  26483. var block_idx_o = 0; // facet barycenter block index
  26484. var block_idx_v1 = 0; // v1 vertex block index
  26485. var block_idx_v2 = 0; // v2 vertex block index
  26486. var block_idx_v3 = 0; // v3 vertex block index
  26487. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26488. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26489. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26490. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26491. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26492. var subSq = options.subDiv.max * options.subDiv.max;
  26493. options.facetPartitioning.length = 0;
  26494. }
  26495. // reset the normals
  26496. for (index = 0; index < positions.length; index++) {
  26497. normals[index] = 0.0;
  26498. }
  26499. // Loop : 1 indice triplet = 1 facet
  26500. var nbFaces = indices.length / 3;
  26501. for (index = 0; index < nbFaces; index++) {
  26502. // get the indexes of the coordinates of each vertex of the facet
  26503. v1x = indices[index * 3] * 3;
  26504. v1y = v1x + 1;
  26505. v1z = v1x + 2;
  26506. v2x = indices[index * 3 + 1] * 3;
  26507. v2y = v2x + 1;
  26508. v2z = v2x + 2;
  26509. v3x = indices[index * 3 + 2] * 3;
  26510. v3y = v3x + 1;
  26511. v3z = v3x + 2;
  26512. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26513. p1p2y = positions[v1y] - positions[v2y];
  26514. p1p2z = positions[v1z] - positions[v2z];
  26515. p3p2x = positions[v3x] - positions[v2x];
  26516. p3p2y = positions[v3y] - positions[v2y];
  26517. p3p2z = positions[v3z] - positions[v2z];
  26518. // compute the face normal with the cross product
  26519. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26520. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26521. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26522. // normalize this normal and store it in the array facetData
  26523. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26524. length = (length === 0) ? 1.0 : length;
  26525. faceNormalx /= length;
  26526. faceNormaly /= length;
  26527. faceNormalz /= length;
  26528. if (computeFacetNormals) {
  26529. options.facetNormals[index].x = faceNormalx;
  26530. options.facetNormals[index].y = faceNormaly;
  26531. options.facetNormals[index].z = faceNormalz;
  26532. }
  26533. if (computeFacetPositions) {
  26534. // compute and the facet barycenter coordinates in the array facetPositions
  26535. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26536. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26537. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26538. }
  26539. if (computeFacetPartitioning) {
  26540. // store the facet indexes in arrays in the main facetPartitioning array :
  26541. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26542. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26543. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26544. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26545. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26546. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26547. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26548. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26549. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26550. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26551. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26552. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26553. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26554. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26555. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26556. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26557. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26558. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26559. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26560. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26561. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26562. // push each facet index in each block containing the vertex
  26563. options.facetPartitioning[block_idx_v1].push(index);
  26564. if (block_idx_v2 != block_idx_v1) {
  26565. options.facetPartitioning[block_idx_v2].push(index);
  26566. }
  26567. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26568. options.facetPartitioning[block_idx_v3].push(index);
  26569. }
  26570. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26571. options.facetPartitioning[block_idx_o].push(index);
  26572. }
  26573. }
  26574. // compute the normals anyway
  26575. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26576. normals[v1y] += faceNormaly;
  26577. normals[v1z] += faceNormalz;
  26578. normals[v2x] += faceNormalx;
  26579. normals[v2y] += faceNormaly;
  26580. normals[v2z] += faceNormalz;
  26581. normals[v3x] += faceNormalx;
  26582. normals[v3y] += faceNormaly;
  26583. normals[v3z] += faceNormalz;
  26584. }
  26585. // last normalization of each normal
  26586. for (index = 0; index < normals.length / 3; index++) {
  26587. faceNormalx = normals[index * 3];
  26588. faceNormaly = normals[index * 3 + 1];
  26589. faceNormalz = normals[index * 3 + 2];
  26590. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26591. length = (length === 0) ? 1.0 : length;
  26592. faceNormalx /= length;
  26593. faceNormaly /= length;
  26594. faceNormalz /= length;
  26595. normals[index * 3] = faceNormalx;
  26596. normals[index * 3 + 1] = faceNormaly;
  26597. normals[index * 3 + 2] = faceNormalz;
  26598. }
  26599. };
  26600. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26601. var li = indices.length;
  26602. var ln = normals.length;
  26603. var i;
  26604. var n;
  26605. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26606. switch (sideOrientation) {
  26607. case BABYLON.Mesh.FRONTSIDE:
  26608. // nothing changed
  26609. break;
  26610. case BABYLON.Mesh.BACKSIDE:
  26611. var tmp;
  26612. // indices
  26613. for (i = 0; i < li; i += 3) {
  26614. tmp = indices[i];
  26615. indices[i] = indices[i + 2];
  26616. indices[i + 2] = tmp;
  26617. }
  26618. // normals
  26619. for (n = 0; n < ln; n++) {
  26620. normals[n] = -normals[n];
  26621. }
  26622. break;
  26623. case BABYLON.Mesh.DOUBLESIDE:
  26624. // positions
  26625. var lp = positions.length;
  26626. var l = lp / 3;
  26627. for (var p = 0; p < lp; p++) {
  26628. positions[lp + p] = positions[p];
  26629. }
  26630. // indices
  26631. for (i = 0; i < li; i += 3) {
  26632. indices[i + li] = indices[i + 2] + l;
  26633. indices[i + 1 + li] = indices[i + 1] + l;
  26634. indices[i + 2 + li] = indices[i] + l;
  26635. }
  26636. // normals
  26637. for (n = 0; n < ln; n++) {
  26638. normals[ln + n] = -normals[n];
  26639. }
  26640. // uvs
  26641. var lu = uvs.length;
  26642. var u = 0;
  26643. for (u = 0; u < lu; u++) {
  26644. uvs[u + lu] = uvs[u];
  26645. }
  26646. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26647. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26648. u = 0;
  26649. for (i = 0; i < lu / 2; i++) {
  26650. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26651. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26652. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26653. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26654. u += 2;
  26655. }
  26656. break;
  26657. }
  26658. };
  26659. /**
  26660. * Creates a new VertexData from the imported parameters.
  26661. */
  26662. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26663. var vertexData = new VertexData();
  26664. // positions
  26665. var positions = parsedVertexData.positions;
  26666. if (positions) {
  26667. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26668. }
  26669. // normals
  26670. var normals = parsedVertexData.normals;
  26671. if (normals) {
  26672. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26673. }
  26674. // tangents
  26675. var tangents = parsedVertexData.tangents;
  26676. if (tangents) {
  26677. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26678. }
  26679. // uvs
  26680. var uvs = parsedVertexData.uvs;
  26681. if (uvs) {
  26682. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26683. }
  26684. // uv2s
  26685. var uv2s = parsedVertexData.uv2s;
  26686. if (uv2s) {
  26687. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26688. }
  26689. // uv3s
  26690. var uv3s = parsedVertexData.uv3s;
  26691. if (uv3s) {
  26692. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26693. }
  26694. // uv4s
  26695. var uv4s = parsedVertexData.uv4s;
  26696. if (uv4s) {
  26697. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26698. }
  26699. // uv5s
  26700. var uv5s = parsedVertexData.uv5s;
  26701. if (uv5s) {
  26702. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26703. }
  26704. // uv6s
  26705. var uv6s = parsedVertexData.uv6s;
  26706. if (uv6s) {
  26707. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26708. }
  26709. // colors
  26710. var colors = parsedVertexData.colors;
  26711. if (colors) {
  26712. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26713. }
  26714. // matricesIndices
  26715. var matricesIndices = parsedVertexData.matricesIndices;
  26716. if (matricesIndices) {
  26717. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26718. }
  26719. // matricesWeights
  26720. var matricesWeights = parsedVertexData.matricesWeights;
  26721. if (matricesWeights) {
  26722. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26723. }
  26724. // indices
  26725. var indices = parsedVertexData.indices;
  26726. if (indices) {
  26727. vertexData.indices = indices;
  26728. }
  26729. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26730. };
  26731. return VertexData;
  26732. }());
  26733. BABYLON.VertexData = VertexData;
  26734. })(BABYLON || (BABYLON = {}));
  26735. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26736. var BABYLON;
  26737. (function (BABYLON) {
  26738. var Geometry = (function () {
  26739. function Geometry(id, scene, vertexData, updatable, mesh) {
  26740. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26741. this._totalVertices = 0;
  26742. this._isDisposed = false;
  26743. this.id = id;
  26744. this._engine = scene.getEngine();
  26745. this._meshes = [];
  26746. this._scene = scene;
  26747. //Init vertex buffer cache
  26748. this._vertexBuffers = {};
  26749. this._indices = [];
  26750. // vertexData
  26751. if (vertexData) {
  26752. this.setAllVerticesData(vertexData, updatable);
  26753. }
  26754. else {
  26755. this._totalVertices = 0;
  26756. this._indices = [];
  26757. }
  26758. if (this._engine.getCaps().vertexArrayObject) {
  26759. this._vertexArrayObjects = {};
  26760. }
  26761. // applyToMesh
  26762. if (mesh) {
  26763. if (mesh.getClassName() === "LinesMesh") {
  26764. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26765. this.updateExtend();
  26766. }
  26767. this.applyToMesh(mesh);
  26768. mesh.computeWorldMatrix(true);
  26769. }
  26770. }
  26771. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26772. /**
  26773. * 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
  26774. * @returns The Bias Vector
  26775. */
  26776. get: function () {
  26777. return this._boundingBias;
  26778. },
  26779. set: function (value) {
  26780. if (this._boundingBias && this._boundingBias.equals(value)) {
  26781. return;
  26782. }
  26783. this._boundingBias = value.clone();
  26784. this.updateBoundingInfo(true, null);
  26785. },
  26786. enumerable: true,
  26787. configurable: true
  26788. });
  26789. Object.defineProperty(Geometry.prototype, "extend", {
  26790. get: function () {
  26791. return this._extend;
  26792. },
  26793. enumerable: true,
  26794. configurable: true
  26795. });
  26796. Geometry.prototype.getScene = function () {
  26797. return this._scene;
  26798. };
  26799. Geometry.prototype.getEngine = function () {
  26800. return this._engine;
  26801. };
  26802. Geometry.prototype.isReady = function () {
  26803. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26804. };
  26805. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26806. get: function () {
  26807. for (var index = 0; index < this._meshes.length; index++) {
  26808. if (!this._meshes[index].doNotSerialize) {
  26809. return false;
  26810. }
  26811. }
  26812. return true;
  26813. },
  26814. enumerable: true,
  26815. configurable: true
  26816. });
  26817. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26818. vertexData.applyToGeometry(this, updatable);
  26819. this.notifyUpdate();
  26820. };
  26821. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26822. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26823. this.setVerticesBuffer(buffer);
  26824. };
  26825. Geometry.prototype.removeVerticesData = function (kind) {
  26826. if (this._vertexBuffers[kind]) {
  26827. this._vertexBuffers[kind].dispose();
  26828. delete this._vertexBuffers[kind];
  26829. }
  26830. };
  26831. Geometry.prototype.setVerticesBuffer = function (buffer) {
  26832. var kind = buffer.getKind();
  26833. if (this._vertexBuffers[kind]) {
  26834. this._vertexBuffers[kind].dispose();
  26835. }
  26836. this._vertexBuffers[kind] = buffer;
  26837. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26838. var data = buffer.getData();
  26839. var stride = buffer.getStrideSize();
  26840. this._totalVertices = data.length / stride;
  26841. this.updateExtend(data, stride);
  26842. this._resetPointsArrayCache();
  26843. var meshes = this._meshes;
  26844. var numOfMeshes = meshes.length;
  26845. for (var index = 0; index < numOfMeshes; index++) {
  26846. var mesh = meshes[index];
  26847. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26848. mesh._createGlobalSubMesh();
  26849. mesh.computeWorldMatrix(true);
  26850. }
  26851. }
  26852. this.notifyUpdate(kind);
  26853. if (this._vertexArrayObjects) {
  26854. this._disposeVertexArrayObjects();
  26855. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26856. }
  26857. };
  26858. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26859. var vertexBuffer = this.getVertexBuffer(kind);
  26860. if (!vertexBuffer) {
  26861. return;
  26862. }
  26863. vertexBuffer.updateDirectly(data, offset);
  26864. this.notifyUpdate(kind);
  26865. };
  26866. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26867. var vertexBuffer = this.getVertexBuffer(kind);
  26868. if (!vertexBuffer) {
  26869. return;
  26870. }
  26871. vertexBuffer.update(data);
  26872. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26873. var stride = vertexBuffer.getStrideSize();
  26874. this._totalVertices = data.length / stride;
  26875. this.updateBoundingInfo(updateExtends, data);
  26876. }
  26877. this.notifyUpdate(kind);
  26878. };
  26879. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26880. if (updateExtends) {
  26881. this.updateExtend(data);
  26882. }
  26883. var meshes = this._meshes;
  26884. var numOfMeshes = meshes.length;
  26885. this._resetPointsArrayCache();
  26886. for (var index = 0; index < numOfMeshes; index++) {
  26887. var mesh = meshes[index];
  26888. if (updateExtends) {
  26889. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26890. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26891. var subMesh = mesh.subMeshes[subIndex];
  26892. subMesh.refreshBoundingInfo();
  26893. }
  26894. }
  26895. }
  26896. };
  26897. Geometry.prototype._bind = function (effect, indexToBind) {
  26898. if (indexToBind === void 0) { indexToBind = undefined; }
  26899. if (indexToBind === undefined) {
  26900. indexToBind = this._indexBuffer;
  26901. }
  26902. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  26903. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  26904. return;
  26905. }
  26906. // Using VAO
  26907. if (!this._vertexArrayObjects[effect.key]) {
  26908. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  26909. }
  26910. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  26911. };
  26912. Geometry.prototype.getTotalVertices = function () {
  26913. if (!this.isReady()) {
  26914. return 0;
  26915. }
  26916. return this._totalVertices;
  26917. };
  26918. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26919. var vertexBuffer = this.getVertexBuffer(kind);
  26920. if (!vertexBuffer) {
  26921. return null;
  26922. }
  26923. var orig = vertexBuffer.getData();
  26924. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  26925. return orig;
  26926. }
  26927. else {
  26928. var len = orig.length;
  26929. var copy = [];
  26930. for (var i = 0; i < len; i++) {
  26931. copy.push(orig[i]);
  26932. }
  26933. return copy;
  26934. }
  26935. };
  26936. Geometry.prototype.getVertexBuffer = function (kind) {
  26937. if (!this.isReady()) {
  26938. return null;
  26939. }
  26940. return this._vertexBuffers[kind];
  26941. };
  26942. Geometry.prototype.getVertexBuffers = function () {
  26943. if (!this.isReady()) {
  26944. return null;
  26945. }
  26946. return this._vertexBuffers;
  26947. };
  26948. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26949. if (!this._vertexBuffers) {
  26950. if (this._delayInfo) {
  26951. return this._delayInfo.indexOf(kind) !== -1;
  26952. }
  26953. return false;
  26954. }
  26955. return this._vertexBuffers[kind] !== undefined;
  26956. };
  26957. Geometry.prototype.getVerticesDataKinds = function () {
  26958. var result = [];
  26959. var kind;
  26960. if (!this._vertexBuffers && this._delayInfo) {
  26961. for (kind in this._delayInfo) {
  26962. result.push(kind);
  26963. }
  26964. }
  26965. else {
  26966. for (kind in this._vertexBuffers) {
  26967. result.push(kind);
  26968. }
  26969. }
  26970. return result;
  26971. };
  26972. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26973. if (this._indexBuffer) {
  26974. this._engine._releaseBuffer(this._indexBuffer);
  26975. }
  26976. this._disposeVertexArrayObjects();
  26977. this._indices = indices;
  26978. if (this._meshes.length !== 0 && this._indices) {
  26979. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26980. }
  26981. if (totalVertices !== undefined) {
  26982. this._totalVertices = totalVertices;
  26983. }
  26984. var meshes = this._meshes;
  26985. var numOfMeshes = meshes.length;
  26986. for (var index = 0; index < numOfMeshes; index++) {
  26987. meshes[index]._createGlobalSubMesh();
  26988. }
  26989. this.notifyUpdate();
  26990. };
  26991. Geometry.prototype.getTotalIndices = function () {
  26992. if (!this.isReady()) {
  26993. return 0;
  26994. }
  26995. return this._indices.length;
  26996. };
  26997. Geometry.prototype.getIndices = function (copyWhenShared) {
  26998. if (!this.isReady()) {
  26999. return null;
  27000. }
  27001. var orig = this._indices;
  27002. if (!copyWhenShared || this._meshes.length === 1) {
  27003. return orig;
  27004. }
  27005. else {
  27006. var len = orig.length;
  27007. var copy = [];
  27008. for (var i = 0; i < len; i++) {
  27009. copy.push(orig[i]);
  27010. }
  27011. return copy;
  27012. }
  27013. };
  27014. Geometry.prototype.getIndexBuffer = function () {
  27015. if (!this.isReady()) {
  27016. return null;
  27017. }
  27018. return this._indexBuffer;
  27019. };
  27020. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27021. if (!effect || !this._vertexArrayObjects) {
  27022. return;
  27023. }
  27024. if (this._vertexArrayObjects[effect.key]) {
  27025. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27026. delete this._vertexArrayObjects[effect.key];
  27027. }
  27028. };
  27029. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27030. var meshes = this._meshes;
  27031. var index = meshes.indexOf(mesh);
  27032. if (index === -1) {
  27033. return;
  27034. }
  27035. meshes.splice(index, 1);
  27036. mesh._geometry = null;
  27037. if (meshes.length === 0 && shouldDispose) {
  27038. this.dispose();
  27039. }
  27040. };
  27041. Geometry.prototype.applyToMesh = function (mesh) {
  27042. if (mesh._geometry === this) {
  27043. return;
  27044. }
  27045. var previousGeometry = mesh._geometry;
  27046. if (previousGeometry) {
  27047. previousGeometry.releaseForMesh(mesh);
  27048. }
  27049. var meshes = this._meshes;
  27050. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27051. mesh._geometry = this;
  27052. this._scene.pushGeometry(this);
  27053. meshes.push(mesh);
  27054. if (this.isReady()) {
  27055. this._applyToMesh(mesh);
  27056. }
  27057. else {
  27058. mesh._boundingInfo = this._boundingInfo;
  27059. }
  27060. };
  27061. Geometry.prototype.updateExtend = function (data, stride) {
  27062. if (data === void 0) { data = null; }
  27063. if (!data) {
  27064. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27065. }
  27066. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27067. };
  27068. Geometry.prototype._applyToMesh = function (mesh) {
  27069. var numOfMeshes = this._meshes.length;
  27070. // vertexBuffers
  27071. for (var kind in this._vertexBuffers) {
  27072. if (numOfMeshes === 1) {
  27073. this._vertexBuffers[kind].create();
  27074. }
  27075. var buffer = this._vertexBuffers[kind].getBuffer();
  27076. if (buffer)
  27077. buffer.references = numOfMeshes;
  27078. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27079. if (!this._extend) {
  27080. this.updateExtend(this._vertexBuffers[kind].getData());
  27081. }
  27082. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27083. mesh._createGlobalSubMesh();
  27084. //bounding info was just created again, world matrix should be applied again.
  27085. mesh._updateBoundingInfo();
  27086. }
  27087. }
  27088. // indexBuffer
  27089. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27090. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27091. }
  27092. if (this._indexBuffer) {
  27093. this._indexBuffer.references = numOfMeshes;
  27094. }
  27095. };
  27096. Geometry.prototype.notifyUpdate = function (kind) {
  27097. if (this.onGeometryUpdated) {
  27098. this.onGeometryUpdated(this, kind);
  27099. }
  27100. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27101. var mesh = _a[_i];
  27102. mesh._markSubMeshesAsAttributesDirty();
  27103. }
  27104. };
  27105. Geometry.prototype.load = function (scene, onLoaded) {
  27106. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27107. return;
  27108. }
  27109. if (this.isReady()) {
  27110. if (onLoaded) {
  27111. onLoaded();
  27112. }
  27113. return;
  27114. }
  27115. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27116. this._queueLoad(scene, onLoaded);
  27117. };
  27118. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27119. var _this = this;
  27120. scene._addPendingData(this);
  27121. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27122. _this._delayLoadingFunction(JSON.parse(data), _this);
  27123. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27124. _this._delayInfo = [];
  27125. scene._removePendingData(_this);
  27126. var meshes = _this._meshes;
  27127. var numOfMeshes = meshes.length;
  27128. for (var index = 0; index < numOfMeshes; index++) {
  27129. _this._applyToMesh(meshes[index]);
  27130. }
  27131. if (onLoaded) {
  27132. onLoaded();
  27133. }
  27134. }, function () { }, scene.database);
  27135. };
  27136. /**
  27137. * Invert the geometry to move from a right handed system to a left handed one.
  27138. */
  27139. Geometry.prototype.toLeftHanded = function () {
  27140. // Flip faces
  27141. var tIndices = this.getIndices(false);
  27142. if (tIndices != null && tIndices.length > 0) {
  27143. for (var i = 0; i < tIndices.length; i += 3) {
  27144. var tTemp = tIndices[i + 0];
  27145. tIndices[i + 0] = tIndices[i + 2];
  27146. tIndices[i + 2] = tTemp;
  27147. }
  27148. this.setIndices(tIndices);
  27149. }
  27150. // Negate position.z
  27151. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27152. if (tPositions != null && tPositions.length > 0) {
  27153. for (var i = 0; i < tPositions.length; i += 3) {
  27154. tPositions[i + 2] = -tPositions[i + 2];
  27155. }
  27156. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27157. }
  27158. // Negate normal.z
  27159. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27160. if (tNormals != null && tNormals.length > 0) {
  27161. for (var i = 0; i < tNormals.length; i += 3) {
  27162. tNormals[i + 2] = -tNormals[i + 2];
  27163. }
  27164. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27165. }
  27166. };
  27167. // Cache
  27168. Geometry.prototype._resetPointsArrayCache = function () {
  27169. this._positions = null;
  27170. };
  27171. Geometry.prototype._generatePointsArray = function () {
  27172. if (this._positions)
  27173. return true;
  27174. this._positions = [];
  27175. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27176. if (!data) {
  27177. return false;
  27178. }
  27179. for (var index = 0; index < data.length; index += 3) {
  27180. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27181. }
  27182. return true;
  27183. };
  27184. Geometry.prototype.isDisposed = function () {
  27185. return this._isDisposed;
  27186. };
  27187. Geometry.prototype._disposeVertexArrayObjects = function () {
  27188. if (this._vertexArrayObjects) {
  27189. for (var kind in this._vertexArrayObjects) {
  27190. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27191. }
  27192. this._vertexArrayObjects = {};
  27193. }
  27194. };
  27195. Geometry.prototype.dispose = function () {
  27196. var meshes = this._meshes;
  27197. var numOfMeshes = meshes.length;
  27198. var index;
  27199. for (index = 0; index < numOfMeshes; index++) {
  27200. this.releaseForMesh(meshes[index]);
  27201. }
  27202. this._meshes = [];
  27203. this._disposeVertexArrayObjects();
  27204. for (var kind in this._vertexBuffers) {
  27205. this._vertexBuffers[kind].dispose();
  27206. }
  27207. this._vertexBuffers = {};
  27208. this._totalVertices = 0;
  27209. if (this._indexBuffer) {
  27210. this._engine._releaseBuffer(this._indexBuffer);
  27211. }
  27212. this._indexBuffer = null;
  27213. this._indices = [];
  27214. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27215. this.delayLoadingFile = null;
  27216. this._delayLoadingFunction = null;
  27217. this._delayInfo = [];
  27218. this._boundingInfo = null;
  27219. this._scene.removeGeometry(this);
  27220. this._isDisposed = true;
  27221. };
  27222. Geometry.prototype.copy = function (id) {
  27223. var vertexData = new BABYLON.VertexData();
  27224. vertexData.indices = [];
  27225. var indices = this.getIndices();
  27226. for (var index = 0; index < indices.length; index++) {
  27227. vertexData.indices.push(indices[index]);
  27228. }
  27229. var updatable = false;
  27230. var stopChecking = false;
  27231. var kind;
  27232. for (kind in this._vertexBuffers) {
  27233. // using slice() to make a copy of the array and not just reference it
  27234. var data = this.getVerticesData(kind);
  27235. if (data instanceof Float32Array) {
  27236. vertexData.set(new Float32Array(data), kind);
  27237. }
  27238. else {
  27239. vertexData.set(data.slice(0), kind);
  27240. }
  27241. if (!stopChecking) {
  27242. updatable = this.getVertexBuffer(kind).isUpdatable();
  27243. stopChecking = !updatable;
  27244. }
  27245. }
  27246. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27247. geometry.delayLoadState = this.delayLoadState;
  27248. geometry.delayLoadingFile = this.delayLoadingFile;
  27249. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27250. for (kind in this._delayInfo) {
  27251. geometry._delayInfo = geometry._delayInfo || [];
  27252. geometry._delayInfo.push(kind);
  27253. }
  27254. // Bounding info
  27255. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27256. return geometry;
  27257. };
  27258. Geometry.prototype.serialize = function () {
  27259. var serializationObject = {};
  27260. serializationObject.id = this.id;
  27261. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27262. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27263. }
  27264. return serializationObject;
  27265. };
  27266. Geometry.prototype.toNumberArray = function (origin) {
  27267. if (Array.isArray(origin)) {
  27268. return origin;
  27269. }
  27270. else {
  27271. return Array.prototype.slice.call(origin);
  27272. }
  27273. };
  27274. Geometry.prototype.serializeVerticeData = function () {
  27275. var serializationObject = this.serialize();
  27276. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27277. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27278. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27279. serializationObject.positions._updatable = true;
  27280. }
  27281. }
  27282. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27283. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27284. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27285. serializationObject.normals._updatable = true;
  27286. }
  27287. }
  27288. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27289. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27290. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27291. serializationObject.uvs._updatable = true;
  27292. }
  27293. }
  27294. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27295. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27296. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27297. serializationObject.uv2s._updatable = true;
  27298. }
  27299. }
  27300. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27301. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27302. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27303. serializationObject.uv3s._updatable = true;
  27304. }
  27305. }
  27306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27307. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27308. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27309. serializationObject.uv4s._updatable = true;
  27310. }
  27311. }
  27312. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27313. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27314. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27315. serializationObject.uv5s._updatable = true;
  27316. }
  27317. }
  27318. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27319. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27320. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27321. serializationObject.uv6s._updatable = true;
  27322. }
  27323. }
  27324. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27325. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27326. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27327. serializationObject.colors._updatable = true;
  27328. }
  27329. }
  27330. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27331. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27332. serializationObject.matricesIndices._isExpanded = true;
  27333. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27334. serializationObject.matricesIndices._updatable = true;
  27335. }
  27336. }
  27337. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27338. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27339. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27340. serializationObject.matricesWeights._updatable = true;
  27341. }
  27342. }
  27343. serializationObject.indices = this.toNumberArray(this.getIndices());
  27344. return serializationObject;
  27345. };
  27346. // Statics
  27347. Geometry.ExtractFromMesh = function (mesh, id) {
  27348. var geometry = mesh._geometry;
  27349. if (!geometry) {
  27350. return null;
  27351. }
  27352. return geometry.copy(id);
  27353. };
  27354. /**
  27355. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27356. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27357. * Be aware Math.random() could cause collisions, but:
  27358. * "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"
  27359. */
  27360. Geometry.RandomId = function () {
  27361. return BABYLON.Tools.RandomId();
  27362. };
  27363. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27364. var scene = mesh.getScene();
  27365. // Geometry
  27366. var geometryId = parsedGeometry.geometryId;
  27367. if (geometryId) {
  27368. var geometry = scene.getGeometryByID(geometryId);
  27369. if (geometry) {
  27370. geometry.applyToMesh(mesh);
  27371. }
  27372. }
  27373. else if (parsedGeometry instanceof ArrayBuffer) {
  27374. var binaryInfo = mesh._binaryInfo;
  27375. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27376. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27377. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27378. }
  27379. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27380. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27381. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27382. }
  27383. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27384. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27385. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27386. }
  27387. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27388. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27389. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27390. }
  27391. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27392. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27393. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27394. }
  27395. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27396. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27397. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27398. }
  27399. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27400. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27401. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27402. }
  27403. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27404. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27405. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27406. }
  27407. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27408. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27409. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27410. }
  27411. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27412. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27413. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27414. }
  27415. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27416. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27417. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27418. }
  27419. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27420. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27421. mesh.setIndices(indicesData);
  27422. }
  27423. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27424. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27425. mesh.subMeshes = [];
  27426. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27427. var materialIndex = subMeshesData[(i * 5) + 0];
  27428. var verticesStart = subMeshesData[(i * 5) + 1];
  27429. var verticesCount = subMeshesData[(i * 5) + 2];
  27430. var indexStart = subMeshesData[(i * 5) + 3];
  27431. var indexCount = subMeshesData[(i * 5) + 4];
  27432. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27433. }
  27434. }
  27435. }
  27436. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27437. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27438. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27439. if (parsedGeometry.uvs) {
  27440. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27441. }
  27442. if (parsedGeometry.uvs2) {
  27443. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27444. }
  27445. if (parsedGeometry.uvs3) {
  27446. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27447. }
  27448. if (parsedGeometry.uvs4) {
  27449. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27450. }
  27451. if (parsedGeometry.uvs5) {
  27452. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27453. }
  27454. if (parsedGeometry.uvs6) {
  27455. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27456. }
  27457. if (parsedGeometry.colors) {
  27458. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27459. }
  27460. if (parsedGeometry.matricesIndices) {
  27461. if (!parsedGeometry.matricesIndices._isExpanded) {
  27462. var floatIndices = [];
  27463. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27464. var matricesIndex = parsedGeometry.matricesIndices[i];
  27465. floatIndices.push(matricesIndex & 0x000000FF);
  27466. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27467. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27468. floatIndices.push(matricesIndex >> 24);
  27469. }
  27470. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27471. }
  27472. else {
  27473. delete parsedGeometry.matricesIndices._isExpanded;
  27474. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27475. }
  27476. }
  27477. if (parsedGeometry.matricesIndicesExtra) {
  27478. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27479. var floatIndices = [];
  27480. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27481. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27482. floatIndices.push(matricesIndex & 0x000000FF);
  27483. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27484. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27485. floatIndices.push(matricesIndex >> 24);
  27486. }
  27487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27488. }
  27489. else {
  27490. delete parsedGeometry.matricesIndices._isExpanded;
  27491. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27492. }
  27493. }
  27494. if (parsedGeometry.matricesWeights) {
  27495. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27496. }
  27497. if (parsedGeometry.matricesWeightsExtra) {
  27498. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27499. }
  27500. mesh.setIndices(parsedGeometry.indices);
  27501. }
  27502. // SubMeshes
  27503. if (parsedGeometry.subMeshes) {
  27504. mesh.subMeshes = [];
  27505. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27506. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27507. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27508. }
  27509. }
  27510. // Flat shading
  27511. if (mesh._shouldGenerateFlatShading) {
  27512. mesh.convertToFlatShadedMesh();
  27513. delete mesh._shouldGenerateFlatShading;
  27514. }
  27515. // Update
  27516. mesh.computeWorldMatrix(true);
  27517. // Octree
  27518. if (scene['_selectionOctree']) {
  27519. scene['_selectionOctree'].addMesh(mesh);
  27520. }
  27521. };
  27522. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27523. if (scene.getGeometryByID(parsedVertexData.id)) {
  27524. return null; // null since geometry could be something else than a box...
  27525. }
  27526. var geometry = new Geometry(parsedVertexData.id, scene);
  27527. if (BABYLON.Tags) {
  27528. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27529. }
  27530. if (parsedVertexData.delayLoadingFile) {
  27531. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27532. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27533. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27534. geometry._delayInfo = [];
  27535. if (parsedVertexData.hasUVs) {
  27536. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27537. }
  27538. if (parsedVertexData.hasUVs2) {
  27539. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27540. }
  27541. if (parsedVertexData.hasUVs3) {
  27542. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27543. }
  27544. if (parsedVertexData.hasUVs4) {
  27545. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27546. }
  27547. if (parsedVertexData.hasUVs5) {
  27548. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27549. }
  27550. if (parsedVertexData.hasUVs6) {
  27551. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27552. }
  27553. if (parsedVertexData.hasColors) {
  27554. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27555. }
  27556. if (parsedVertexData.hasMatricesIndices) {
  27557. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27558. }
  27559. if (parsedVertexData.hasMatricesWeights) {
  27560. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27561. }
  27562. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27563. }
  27564. else {
  27565. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27566. }
  27567. scene.pushGeometry(geometry, true);
  27568. return geometry;
  27569. };
  27570. return Geometry;
  27571. }());
  27572. BABYLON.Geometry = Geometry;
  27573. /////// Primitives //////////////////////////////////////////////
  27574. (function (Geometry) {
  27575. var Primitives;
  27576. (function (Primitives) {
  27577. /// Abstract class
  27578. var _Primitive = (function (_super) {
  27579. __extends(_Primitive, _super);
  27580. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27581. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27582. _this._canBeRegenerated = _canBeRegenerated;
  27583. _this._beingRegenerated = true;
  27584. _this.regenerate();
  27585. _this._beingRegenerated = false;
  27586. return _this;
  27587. }
  27588. _Primitive.prototype.canBeRegenerated = function () {
  27589. return this._canBeRegenerated;
  27590. };
  27591. _Primitive.prototype.regenerate = function () {
  27592. if (!this._canBeRegenerated) {
  27593. return;
  27594. }
  27595. this._beingRegenerated = true;
  27596. this.setAllVerticesData(this._regenerateVertexData(), false);
  27597. this._beingRegenerated = false;
  27598. };
  27599. _Primitive.prototype.asNewGeometry = function (id) {
  27600. return _super.prototype.copy.call(this, id);
  27601. };
  27602. // overrides
  27603. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27604. if (!this._beingRegenerated) {
  27605. return;
  27606. }
  27607. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27608. };
  27609. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27610. if (!this._beingRegenerated) {
  27611. return;
  27612. }
  27613. _super.prototype.setVerticesData.call(this, kind, data, false);
  27614. };
  27615. // to override
  27616. // protected
  27617. _Primitive.prototype._regenerateVertexData = function () {
  27618. throw new Error("Abstract method");
  27619. };
  27620. _Primitive.prototype.copy = function (id) {
  27621. throw new Error("Must be overriden in sub-classes.");
  27622. };
  27623. _Primitive.prototype.serialize = function () {
  27624. var serializationObject = _super.prototype.serialize.call(this);
  27625. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27626. return serializationObject;
  27627. };
  27628. return _Primitive;
  27629. }(Geometry));
  27630. Primitives._Primitive = _Primitive;
  27631. var Ribbon = (function (_super) {
  27632. __extends(Ribbon, _super);
  27633. // Members
  27634. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27635. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27636. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27637. _this.pathArray = pathArray;
  27638. _this.closeArray = closeArray;
  27639. _this.closePath = closePath;
  27640. _this.offset = offset;
  27641. _this.side = side;
  27642. return _this;
  27643. }
  27644. Ribbon.prototype._regenerateVertexData = function () {
  27645. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27646. };
  27647. Ribbon.prototype.copy = function (id) {
  27648. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27649. };
  27650. return Ribbon;
  27651. }(_Primitive));
  27652. Primitives.Ribbon = Ribbon;
  27653. var Box = (function (_super) {
  27654. __extends(Box, _super);
  27655. // Members
  27656. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27657. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27658. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27659. _this.size = size;
  27660. _this.side = side;
  27661. return _this;
  27662. }
  27663. Box.prototype._regenerateVertexData = function () {
  27664. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27665. };
  27666. Box.prototype.copy = function (id) {
  27667. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27668. };
  27669. Box.prototype.serialize = function () {
  27670. var serializationObject = _super.prototype.serialize.call(this);
  27671. serializationObject.size = this.size;
  27672. return serializationObject;
  27673. };
  27674. Box.Parse = function (parsedBox, scene) {
  27675. if (scene.getGeometryByID(parsedBox.id)) {
  27676. return null; // null since geometry could be something else than a box...
  27677. }
  27678. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27679. if (BABYLON.Tags) {
  27680. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27681. }
  27682. scene.pushGeometry(box, true);
  27683. return box;
  27684. };
  27685. return Box;
  27686. }(_Primitive));
  27687. Primitives.Box = Box;
  27688. var Sphere = (function (_super) {
  27689. __extends(Sphere, _super);
  27690. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27691. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27692. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27693. _this.segments = segments;
  27694. _this.diameter = diameter;
  27695. _this.side = side;
  27696. return _this;
  27697. }
  27698. Sphere.prototype._regenerateVertexData = function () {
  27699. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27700. };
  27701. Sphere.prototype.copy = function (id) {
  27702. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27703. };
  27704. Sphere.prototype.serialize = function () {
  27705. var serializationObject = _super.prototype.serialize.call(this);
  27706. serializationObject.segments = this.segments;
  27707. serializationObject.diameter = this.diameter;
  27708. return serializationObject;
  27709. };
  27710. Sphere.Parse = function (parsedSphere, scene) {
  27711. if (scene.getGeometryByID(parsedSphere.id)) {
  27712. return null; // null since geometry could be something else than a sphere...
  27713. }
  27714. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27715. if (BABYLON.Tags) {
  27716. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27717. }
  27718. scene.pushGeometry(sphere, true);
  27719. return sphere;
  27720. };
  27721. return Sphere;
  27722. }(_Primitive));
  27723. Primitives.Sphere = Sphere;
  27724. var Disc = (function (_super) {
  27725. __extends(Disc, _super);
  27726. // Members
  27727. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27728. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27729. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27730. _this.radius = radius;
  27731. _this.tessellation = tessellation;
  27732. _this.side = side;
  27733. return _this;
  27734. }
  27735. Disc.prototype._regenerateVertexData = function () {
  27736. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27737. };
  27738. Disc.prototype.copy = function (id) {
  27739. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27740. };
  27741. return Disc;
  27742. }(_Primitive));
  27743. Primitives.Disc = Disc;
  27744. var Cylinder = (function (_super) {
  27745. __extends(Cylinder, _super);
  27746. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27747. if (subdivisions === void 0) { subdivisions = 1; }
  27748. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27749. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27750. _this.height = height;
  27751. _this.diameterTop = diameterTop;
  27752. _this.diameterBottom = diameterBottom;
  27753. _this.tessellation = tessellation;
  27754. _this.subdivisions = subdivisions;
  27755. _this.side = side;
  27756. return _this;
  27757. }
  27758. Cylinder.prototype._regenerateVertexData = function () {
  27759. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27760. };
  27761. Cylinder.prototype.copy = function (id) {
  27762. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27763. };
  27764. Cylinder.prototype.serialize = function () {
  27765. var serializationObject = _super.prototype.serialize.call(this);
  27766. serializationObject.height = this.height;
  27767. serializationObject.diameterTop = this.diameterTop;
  27768. serializationObject.diameterBottom = this.diameterBottom;
  27769. serializationObject.tessellation = this.tessellation;
  27770. return serializationObject;
  27771. };
  27772. Cylinder.Parse = function (parsedCylinder, scene) {
  27773. if (scene.getGeometryByID(parsedCylinder.id)) {
  27774. return null; // null since geometry could be something else than a cylinder...
  27775. }
  27776. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27777. if (BABYLON.Tags) {
  27778. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27779. }
  27780. scene.pushGeometry(cylinder, true);
  27781. return cylinder;
  27782. };
  27783. return Cylinder;
  27784. }(_Primitive));
  27785. Primitives.Cylinder = Cylinder;
  27786. var Torus = (function (_super) {
  27787. __extends(Torus, _super);
  27788. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27789. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27790. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27791. _this.diameter = diameter;
  27792. _this.thickness = thickness;
  27793. _this.tessellation = tessellation;
  27794. _this.side = side;
  27795. return _this;
  27796. }
  27797. Torus.prototype._regenerateVertexData = function () {
  27798. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27799. };
  27800. Torus.prototype.copy = function (id) {
  27801. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27802. };
  27803. Torus.prototype.serialize = function () {
  27804. var serializationObject = _super.prototype.serialize.call(this);
  27805. serializationObject.diameter = this.diameter;
  27806. serializationObject.thickness = this.thickness;
  27807. serializationObject.tessellation = this.tessellation;
  27808. return serializationObject;
  27809. };
  27810. Torus.Parse = function (parsedTorus, scene) {
  27811. if (scene.getGeometryByID(parsedTorus.id)) {
  27812. return null; // null since geometry could be something else than a torus...
  27813. }
  27814. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27815. if (BABYLON.Tags) {
  27816. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27817. }
  27818. scene.pushGeometry(torus, true);
  27819. return torus;
  27820. };
  27821. return Torus;
  27822. }(_Primitive));
  27823. Primitives.Torus = Torus;
  27824. var Ground = (function (_super) {
  27825. __extends(Ground, _super);
  27826. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27827. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27828. _this.width = width;
  27829. _this.height = height;
  27830. _this.subdivisions = subdivisions;
  27831. return _this;
  27832. }
  27833. Ground.prototype._regenerateVertexData = function () {
  27834. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27835. };
  27836. Ground.prototype.copy = function (id) {
  27837. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27838. };
  27839. Ground.prototype.serialize = function () {
  27840. var serializationObject = _super.prototype.serialize.call(this);
  27841. serializationObject.width = this.width;
  27842. serializationObject.height = this.height;
  27843. serializationObject.subdivisions = this.subdivisions;
  27844. return serializationObject;
  27845. };
  27846. Ground.Parse = function (parsedGround, scene) {
  27847. if (scene.getGeometryByID(parsedGround.id)) {
  27848. return null; // null since geometry could be something else than a ground...
  27849. }
  27850. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27851. if (BABYLON.Tags) {
  27852. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27853. }
  27854. scene.pushGeometry(ground, true);
  27855. return ground;
  27856. };
  27857. return Ground;
  27858. }(_Primitive));
  27859. Primitives.Ground = Ground;
  27860. var TiledGround = (function (_super) {
  27861. __extends(TiledGround, _super);
  27862. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27863. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27864. _this.xmin = xmin;
  27865. _this.zmin = zmin;
  27866. _this.xmax = xmax;
  27867. _this.zmax = zmax;
  27868. _this.subdivisions = subdivisions;
  27869. _this.precision = precision;
  27870. return _this;
  27871. }
  27872. TiledGround.prototype._regenerateVertexData = function () {
  27873. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27874. };
  27875. TiledGround.prototype.copy = function (id) {
  27876. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27877. };
  27878. return TiledGround;
  27879. }(_Primitive));
  27880. Primitives.TiledGround = TiledGround;
  27881. var Plane = (function (_super) {
  27882. __extends(Plane, _super);
  27883. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27884. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27885. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27886. _this.size = size;
  27887. _this.side = side;
  27888. return _this;
  27889. }
  27890. Plane.prototype._regenerateVertexData = function () {
  27891. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27892. };
  27893. Plane.prototype.copy = function (id) {
  27894. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27895. };
  27896. Plane.prototype.serialize = function () {
  27897. var serializationObject = _super.prototype.serialize.call(this);
  27898. serializationObject.size = this.size;
  27899. return serializationObject;
  27900. };
  27901. Plane.Parse = function (parsedPlane, scene) {
  27902. if (scene.getGeometryByID(parsedPlane.id)) {
  27903. return null; // null since geometry could be something else than a ground...
  27904. }
  27905. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27906. if (BABYLON.Tags) {
  27907. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27908. }
  27909. scene.pushGeometry(plane, true);
  27910. return plane;
  27911. };
  27912. return Plane;
  27913. }(_Primitive));
  27914. Primitives.Plane = Plane;
  27915. var TorusKnot = (function (_super) {
  27916. __extends(TorusKnot, _super);
  27917. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27918. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27919. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27920. _this.radius = radius;
  27921. _this.tube = tube;
  27922. _this.radialSegments = radialSegments;
  27923. _this.tubularSegments = tubularSegments;
  27924. _this.p = p;
  27925. _this.q = q;
  27926. _this.side = side;
  27927. return _this;
  27928. }
  27929. TorusKnot.prototype._regenerateVertexData = function () {
  27930. 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 });
  27931. };
  27932. TorusKnot.prototype.copy = function (id) {
  27933. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27934. };
  27935. TorusKnot.prototype.serialize = function () {
  27936. var serializationObject = _super.prototype.serialize.call(this);
  27937. serializationObject.radius = this.radius;
  27938. serializationObject.tube = this.tube;
  27939. serializationObject.radialSegments = this.radialSegments;
  27940. serializationObject.tubularSegments = this.tubularSegments;
  27941. serializationObject.p = this.p;
  27942. serializationObject.q = this.q;
  27943. return serializationObject;
  27944. };
  27945. ;
  27946. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27947. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27948. return null; // null since geometry could be something else than a ground...
  27949. }
  27950. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27951. if (BABYLON.Tags) {
  27952. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27953. }
  27954. scene.pushGeometry(torusKnot, true);
  27955. return torusKnot;
  27956. };
  27957. return TorusKnot;
  27958. }(_Primitive));
  27959. Primitives.TorusKnot = TorusKnot;
  27960. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27961. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27962. })(BABYLON || (BABYLON = {}));
  27963. //# sourceMappingURL=babylon.geometry.js.map
  27964. var BABYLON;
  27965. (function (BABYLON) {
  27966. var PostProcessManager = (function () {
  27967. function PostProcessManager(scene) {
  27968. this._vertexBuffers = {};
  27969. this._scene = scene;
  27970. }
  27971. PostProcessManager.prototype._prepareBuffers = function () {
  27972. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  27973. return;
  27974. }
  27975. // VBO
  27976. var vertices = [];
  27977. vertices.push(1, 1);
  27978. vertices.push(-1, 1);
  27979. vertices.push(-1, -1);
  27980. vertices.push(1, -1);
  27981. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27982. // Indices
  27983. var indices = [];
  27984. indices.push(0);
  27985. indices.push(1);
  27986. indices.push(2);
  27987. indices.push(0);
  27988. indices.push(2);
  27989. indices.push(3);
  27990. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27991. };
  27992. // Methods
  27993. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27994. var postProcesses = this._scene.activeCamera._postProcesses;
  27995. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27996. return false;
  27997. }
  27998. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27999. return true;
  28000. };
  28001. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28002. var engine = this._scene.getEngine();
  28003. for (var index = 0; index < postProcesses.length; index++) {
  28004. if (index < postProcesses.length - 1) {
  28005. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28006. }
  28007. else {
  28008. if (targetTexture) {
  28009. engine.bindFramebuffer(targetTexture);
  28010. }
  28011. else {
  28012. engine.restoreDefaultFramebuffer();
  28013. }
  28014. }
  28015. var pp = postProcesses[index];
  28016. var effect = pp.apply();
  28017. if (effect) {
  28018. pp.onBeforeRenderObservable.notifyObservers(effect);
  28019. // VBOs
  28020. this._prepareBuffers();
  28021. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28022. // Draw order
  28023. engine.draw(true, 0, 6);
  28024. pp.onAfterRenderObservable.notifyObservers(effect);
  28025. }
  28026. }
  28027. // Restore depth buffer
  28028. engine.setDepthBuffer(true);
  28029. engine.setDepthWrite(true);
  28030. };
  28031. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28032. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28033. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28034. return;
  28035. }
  28036. var engine = this._scene.getEngine();
  28037. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28038. if (index < len - 1) {
  28039. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28040. }
  28041. else {
  28042. if (targetTexture) {
  28043. engine.bindFramebuffer(targetTexture, faceIndex);
  28044. }
  28045. else {
  28046. engine.restoreDefaultFramebuffer();
  28047. }
  28048. }
  28049. if (doNotPresent) {
  28050. break;
  28051. }
  28052. var pp = postProcesses[index];
  28053. var effect = pp.apply();
  28054. if (effect) {
  28055. pp.onBeforeRenderObservable.notifyObservers(effect);
  28056. // VBOs
  28057. this._prepareBuffers();
  28058. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28059. // Draw order
  28060. engine.draw(true, 0, 6);
  28061. pp.onAfterRenderObservable.notifyObservers(effect);
  28062. }
  28063. }
  28064. // Restore states
  28065. engine.setDepthBuffer(true);
  28066. engine.setDepthWrite(true);
  28067. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28068. };
  28069. PostProcessManager.prototype.dispose = function () {
  28070. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28071. if (buffer) {
  28072. buffer.dispose();
  28073. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28074. }
  28075. if (this._indexBuffer) {
  28076. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28077. this._indexBuffer = null;
  28078. }
  28079. };
  28080. return PostProcessManager;
  28081. }());
  28082. BABYLON.PostProcessManager = PostProcessManager;
  28083. })(BABYLON || (BABYLON = {}));
  28084. //# sourceMappingURL=babylon.postProcessManager.js.map
  28085. var BABYLON;
  28086. (function (BABYLON) {
  28087. var ShaderMaterial = (function (_super) {
  28088. __extends(ShaderMaterial, _super);
  28089. function ShaderMaterial(name, scene, shaderPath, options) {
  28090. var _this = _super.call(this, name, scene) || this;
  28091. _this._textures = {};
  28092. _this._textureArrays = {};
  28093. _this._floats = {};
  28094. _this._floatsArrays = {};
  28095. _this._colors3 = {};
  28096. _this._colors4 = {};
  28097. _this._vectors2 = {};
  28098. _this._vectors3 = {};
  28099. _this._vectors4 = {};
  28100. _this._matrices = {};
  28101. _this._matrices3x3 = {};
  28102. _this._matrices2x2 = {};
  28103. _this._vectors3Arrays = {};
  28104. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28105. _this._shaderPath = shaderPath;
  28106. options.needAlphaBlending = options.needAlphaBlending || false;
  28107. options.needAlphaTesting = options.needAlphaTesting || false;
  28108. options.attributes = options.attributes || ["position", "normal", "uv"];
  28109. options.uniforms = options.uniforms || ["worldViewProjection"];
  28110. options.uniformBuffers = options.uniformBuffers || [];
  28111. options.samplers = options.samplers || [];
  28112. options.defines = options.defines || [];
  28113. _this._options = options;
  28114. return _this;
  28115. }
  28116. ShaderMaterial.prototype.getClassName = function () {
  28117. return "ShaderMaterial";
  28118. };
  28119. ShaderMaterial.prototype.needAlphaBlending = function () {
  28120. return this._options.needAlphaBlending;
  28121. };
  28122. ShaderMaterial.prototype.needAlphaTesting = function () {
  28123. return this._options.needAlphaTesting;
  28124. };
  28125. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28126. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28127. this._options.uniforms.push(uniformName);
  28128. }
  28129. };
  28130. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28131. if (this._options.samplers.indexOf(name) === -1) {
  28132. this._options.samplers.push(name);
  28133. }
  28134. this._textures[name] = texture;
  28135. return this;
  28136. };
  28137. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  28138. if (this._options.samplers.indexOf(name) === -1) {
  28139. this._options.samplers.push(name);
  28140. }
  28141. this._checkUniform(name);
  28142. this._textureArrays[name] = textures;
  28143. return this;
  28144. };
  28145. ShaderMaterial.prototype.setFloat = function (name, value) {
  28146. this._checkUniform(name);
  28147. this._floats[name] = value;
  28148. return this;
  28149. };
  28150. ShaderMaterial.prototype.setFloats = function (name, value) {
  28151. this._checkUniform(name);
  28152. this._floatsArrays[name] = value;
  28153. return this;
  28154. };
  28155. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28156. this._checkUniform(name);
  28157. this._colors3[name] = value;
  28158. return this;
  28159. };
  28160. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28161. this._checkUniform(name);
  28162. this._colors4[name] = value;
  28163. return this;
  28164. };
  28165. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28166. this._checkUniform(name);
  28167. this._vectors2[name] = value;
  28168. return this;
  28169. };
  28170. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28171. this._checkUniform(name);
  28172. this._vectors3[name] = value;
  28173. return this;
  28174. };
  28175. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28176. this._checkUniform(name);
  28177. this._vectors4[name] = value;
  28178. return this;
  28179. };
  28180. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28181. this._checkUniform(name);
  28182. this._matrices[name] = value;
  28183. return this;
  28184. };
  28185. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28186. this._checkUniform(name);
  28187. this._matrices3x3[name] = value;
  28188. return this;
  28189. };
  28190. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28191. this._checkUniform(name);
  28192. this._matrices2x2[name] = value;
  28193. return this;
  28194. };
  28195. ShaderMaterial.prototype.setArray3 = function (name, value) {
  28196. this._checkUniform(name);
  28197. this._vectors3Arrays[name] = value;
  28198. return this;
  28199. };
  28200. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  28201. if (!mesh) {
  28202. return true;
  28203. }
  28204. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  28205. return false;
  28206. }
  28207. return false;
  28208. };
  28209. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28210. var scene = this.getScene();
  28211. var engine = scene.getEngine();
  28212. if (!this.checkReadyOnEveryCall) {
  28213. if (this._renderId === scene.getRenderId()) {
  28214. if (this._checkCache(scene, mesh, useInstances)) {
  28215. return true;
  28216. }
  28217. }
  28218. }
  28219. // Instances
  28220. var defines = [];
  28221. var attribs = [];
  28222. var fallbacks = new BABYLON.EffectFallbacks();
  28223. if (useInstances) {
  28224. defines.push("#define INSTANCES");
  28225. }
  28226. for (var index = 0; index < this._options.defines.length; index++) {
  28227. defines.push(this._options.defines[index]);
  28228. }
  28229. for (var index = 0; index < this._options.attributes.length; index++) {
  28230. attribs.push(this._options.attributes[index]);
  28231. }
  28232. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28233. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28234. defines.push("#define VERTEXCOLOR");
  28235. }
  28236. // Bones
  28237. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28238. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28239. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28240. if (mesh.numBoneInfluencers > 4) {
  28241. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  28242. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  28243. }
  28244. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28245. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28246. fallbacks.addCPUSkinningFallback(0, mesh);
  28247. }
  28248. else {
  28249. defines.push("#define NUM_BONE_INFLUENCERS 0");
  28250. }
  28251. // Textures
  28252. for (var name in this._textures) {
  28253. if (!this._textures[name].isReady()) {
  28254. return false;
  28255. }
  28256. }
  28257. // Alpha test
  28258. if (engine.getAlphaTesting()) {
  28259. defines.push("#define ALPHATEST");
  28260. }
  28261. var previousEffect = this._effect;
  28262. var join = defines.join("\n");
  28263. this._effect = engine.createEffect(this._shaderPath, {
  28264. attributes: attribs,
  28265. uniformsNames: this._options.uniforms,
  28266. uniformBuffersNames: this._options.uniformBuffers,
  28267. samplers: this._options.samplers,
  28268. defines: join,
  28269. fallbacks: fallbacks,
  28270. onCompiled: this.onCompiled,
  28271. onError: this.onError
  28272. }, engine);
  28273. if (!this._effect.isReady()) {
  28274. return false;
  28275. }
  28276. if (previousEffect !== this._effect) {
  28277. scene.resetCachedMaterial();
  28278. }
  28279. this._renderId = scene.getRenderId();
  28280. return true;
  28281. };
  28282. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28283. var scene = this.getScene();
  28284. if (this._options.uniforms.indexOf("world") !== -1) {
  28285. this._effect.setMatrix("world", world);
  28286. }
  28287. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28288. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28289. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28290. }
  28291. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28292. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28293. }
  28294. };
  28295. ShaderMaterial.prototype.bind = function (world, mesh) {
  28296. // Std values
  28297. this.bindOnlyWorldMatrix(world);
  28298. if (this.getScene().getCachedMaterial() !== this) {
  28299. if (this._options.uniforms.indexOf("view") !== -1) {
  28300. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28301. }
  28302. if (this._options.uniforms.indexOf("projection") !== -1) {
  28303. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28304. }
  28305. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28306. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28307. }
  28308. // Bones
  28309. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  28310. var name;
  28311. // Texture
  28312. for (name in this._textures) {
  28313. this._effect.setTexture(name, this._textures[name]);
  28314. }
  28315. // Texture arrays
  28316. for (name in this._textureArrays) {
  28317. this._effect.setTextureArray(name, this._textureArrays[name]);
  28318. }
  28319. // Float
  28320. for (name in this._floats) {
  28321. this._effect.setFloat(name, this._floats[name]);
  28322. }
  28323. // Float s
  28324. for (name in this._floatsArrays) {
  28325. this._effect.setArray(name, this._floatsArrays[name]);
  28326. }
  28327. // Color3
  28328. for (name in this._colors3) {
  28329. this._effect.setColor3(name, this._colors3[name]);
  28330. }
  28331. // Color4
  28332. for (name in this._colors4) {
  28333. var color = this._colors4[name];
  28334. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28335. }
  28336. // Vector2
  28337. for (name in this._vectors2) {
  28338. this._effect.setVector2(name, this._vectors2[name]);
  28339. }
  28340. // Vector3
  28341. for (name in this._vectors3) {
  28342. this._effect.setVector3(name, this._vectors3[name]);
  28343. }
  28344. // Vector4
  28345. for (name in this._vectors4) {
  28346. this._effect.setVector4(name, this._vectors4[name]);
  28347. }
  28348. // Matrix
  28349. for (name in this._matrices) {
  28350. this._effect.setMatrix(name, this._matrices[name]);
  28351. }
  28352. // Matrix 3x3
  28353. for (name in this._matrices3x3) {
  28354. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28355. }
  28356. // Matrix 2x2
  28357. for (name in this._matrices2x2) {
  28358. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28359. }
  28360. // Vector3Array
  28361. for (name in this._vectors3Arrays) {
  28362. this._effect.setArray3(name, this._vectors3Arrays[name]);
  28363. }
  28364. }
  28365. this._afterBind(mesh);
  28366. };
  28367. ShaderMaterial.prototype.clone = function (name) {
  28368. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28369. return newShaderMaterial;
  28370. };
  28371. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28372. if (forceDisposeTextures) {
  28373. var name;
  28374. for (name in this._textures) {
  28375. this._textures[name].dispose();
  28376. }
  28377. for (name in this._textureArrays) {
  28378. var array = this._textureArrays[name];
  28379. for (var index = 0; index < array.length; index++) {
  28380. array[index].dispose();
  28381. }
  28382. }
  28383. }
  28384. this._textures = {};
  28385. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28386. };
  28387. ShaderMaterial.prototype.serialize = function () {
  28388. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  28389. serializationObject.customType = "BABYLON.ShaderMaterial";
  28390. serializationObject.options = this._options;
  28391. serializationObject.shaderPath = this._shaderPath;
  28392. var name;
  28393. // Texture
  28394. serializationObject.textures = {};
  28395. for (name in this._textures) {
  28396. serializationObject.textures[name] = this._textures[name].serialize();
  28397. }
  28398. // Texture arrays
  28399. serializationObject.textureArrays = {};
  28400. for (name in this._textureArrays) {
  28401. serializationObject.textureArrays[name] = [];
  28402. var array = this._textureArrays[name];
  28403. for (var index = 0; index < array.length; index++) {
  28404. serializationObject.textureArrays[name].push(array[index].serialize());
  28405. }
  28406. }
  28407. // Float
  28408. serializationObject.floats = {};
  28409. for (name in this._floats) {
  28410. serializationObject.floats[name] = this._floats[name];
  28411. }
  28412. // Float s
  28413. serializationObject.floatArrays = {};
  28414. for (name in this._floatsArrays) {
  28415. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28416. }
  28417. // Color3
  28418. serializationObject.colors3 = {};
  28419. for (name in this._colors3) {
  28420. serializationObject.colors3[name] = this._colors3[name].asArray();
  28421. }
  28422. // Color4
  28423. serializationObject.colors4 = {};
  28424. for (name in this._colors4) {
  28425. serializationObject.colors4[name] = this._colors4[name].asArray();
  28426. }
  28427. // Vector2
  28428. serializationObject.vectors2 = {};
  28429. for (name in this._vectors2) {
  28430. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28431. }
  28432. // Vector3
  28433. serializationObject.vectors3 = {};
  28434. for (name in this._vectors3) {
  28435. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28436. }
  28437. // Vector4
  28438. serializationObject.vectors4 = {};
  28439. for (name in this._vectors4) {
  28440. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28441. }
  28442. // Matrix
  28443. serializationObject.matrices = {};
  28444. for (name in this._matrices) {
  28445. serializationObject.matrices[name] = this._matrices[name].asArray();
  28446. }
  28447. // Matrix 3x3
  28448. serializationObject.matrices3x3 = {};
  28449. for (name in this._matrices3x3) {
  28450. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28451. }
  28452. // Matrix 2x2
  28453. serializationObject.matrices2x2 = {};
  28454. for (name in this._matrices2x2) {
  28455. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28456. }
  28457. // Vector3Array
  28458. serializationObject.vectors3Arrays = {};
  28459. for (name in this._vectors3Arrays) {
  28460. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  28461. }
  28462. return serializationObject;
  28463. };
  28464. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28465. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  28466. var name;
  28467. // Texture
  28468. for (name in source.textures) {
  28469. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28470. }
  28471. // Texture arrays
  28472. for (name in source.textureArrays) {
  28473. var array = source.textureArrays[name];
  28474. var textureArray = new Array();
  28475. for (var index = 0; index < array.length; index++) {
  28476. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  28477. }
  28478. material.setTextureArray(name, textureArray);
  28479. }
  28480. // Float
  28481. for (name in source.floats) {
  28482. material.setFloat(name, source.floats[name]);
  28483. }
  28484. // Float s
  28485. for (name in source.floatsArrays) {
  28486. material.setFloats(name, source.floatsArrays[name]);
  28487. }
  28488. // Color3
  28489. for (name in source.colors3) {
  28490. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28491. }
  28492. // Color4
  28493. for (name in source.colors4) {
  28494. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28495. }
  28496. // Vector2
  28497. for (name in source.vectors2) {
  28498. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  28499. }
  28500. // Vector3
  28501. for (name in source.vectors3) {
  28502. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  28503. }
  28504. // Vector4
  28505. for (name in source.vectors4) {
  28506. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  28507. }
  28508. // Matrix
  28509. for (name in source.matrices) {
  28510. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  28511. }
  28512. // Matrix 3x3
  28513. for (name in source.matrices3x3) {
  28514. material.setMatrix3x3(name, source.matrices3x3[name]);
  28515. }
  28516. // Matrix 2x2
  28517. for (name in source.matrices2x2) {
  28518. material.setMatrix2x2(name, source.matrices2x2[name]);
  28519. }
  28520. // Vector3Array
  28521. for (name in source.vectors3Arrays) {
  28522. material.setArray3(name, source.vectors3Arrays[name]);
  28523. }
  28524. return material;
  28525. };
  28526. return ShaderMaterial;
  28527. }(BABYLON.Material));
  28528. BABYLON.ShaderMaterial = ShaderMaterial;
  28529. })(BABYLON || (BABYLON = {}));
  28530. //# sourceMappingURL=babylon.shaderMaterial.js.map
  28531. var BABYLON;
  28532. (function (BABYLON) {
  28533. var MeshBuilder = (function () {
  28534. function MeshBuilder() {
  28535. }
  28536. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  28537. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  28538. return BABYLON.Mesh.DOUBLESIDE;
  28539. }
  28540. if (orientation === undefined || orientation === null) {
  28541. return BABYLON.Mesh.FRONTSIDE;
  28542. }
  28543. return orientation;
  28544. };
  28545. /**
  28546. * Creates a box mesh.
  28547. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  28548. * The parameter `size` sets the size (float) of each box side (default 1).
  28549. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  28550. * 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).
  28551. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  28552. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28553. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  28554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28556. */
  28557. MeshBuilder.CreateBox = function (name, options, scene) {
  28558. var box = new BABYLON.Mesh(name, scene);
  28559. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28560. box.sideOrientation = options.sideOrientation;
  28561. var vertexData = BABYLON.VertexData.CreateBox(options);
  28562. vertexData.applyToMesh(box, options.updatable);
  28563. return box;
  28564. };
  28565. /**
  28566. * Creates a sphere mesh.
  28567. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  28568. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28569. * 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`).
  28570. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28571. * 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
  28572. * 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).
  28573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28574. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  28575. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28577. */
  28578. MeshBuilder.CreateSphere = function (name, options, scene) {
  28579. var sphere = new BABYLON.Mesh(name, scene);
  28580. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28581. sphere.sideOrientation = options.sideOrientation;
  28582. var vertexData = BABYLON.VertexData.CreateSphere(options);
  28583. vertexData.applyToMesh(sphere, options.updatable);
  28584. return sphere;
  28585. };
  28586. /**
  28587. * Creates a plane polygonal mesh. By default, this is a disc.
  28588. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  28589. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28590. * 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.
  28591. * 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
  28592. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28593. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  28594. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28595. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28596. */
  28597. MeshBuilder.CreateDisc = function (name, options, scene) {
  28598. var disc = new BABYLON.Mesh(name, scene);
  28599. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28600. disc.sideOrientation = options.sideOrientation;
  28601. var vertexData = BABYLON.VertexData.CreateDisc(options);
  28602. vertexData.applyToMesh(disc, options.updatable);
  28603. return disc;
  28604. };
  28605. /**
  28606. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28607. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  28608. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28609. * 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`).
  28610. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28611. * 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.
  28612. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28613. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  28614. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28615. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28616. */
  28617. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  28618. var sphere = new BABYLON.Mesh(name, scene);
  28619. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28620. sphere.sideOrientation = options.sideOrientation;
  28621. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  28622. vertexData.applyToMesh(sphere, options.updatable);
  28623. return sphere;
  28624. };
  28625. ;
  28626. /**
  28627. * Creates a ribbon mesh.
  28628. * 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.
  28629. *
  28630. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28631. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28632. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28633. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28634. * 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.
  28635. * 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.
  28636. * 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
  28637. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28638. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  28639. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28640. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  28641. * 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.
  28642. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  28643. * 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
  28644. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  28645. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  28646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28647. */
  28648. MeshBuilder.CreateRibbon = function (name, options, scene) {
  28649. var pathArray = options.pathArray;
  28650. var closeArray = options.closeArray;
  28651. var closePath = options.closePath;
  28652. var offset = options.offset;
  28653. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28654. var instance = options.instance;
  28655. var updatable = options.updatable;
  28656. if (instance) {
  28657. // positionFunction : ribbon case
  28658. // only pathArray and sideOrientation parameters are taken into account for positions update
  28659. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  28660. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  28661. var positionFunction = function (positions) {
  28662. var minlg = pathArray[0].length;
  28663. var i = 0;
  28664. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  28665. for (var si = 1; si <= ns; si++) {
  28666. for (var p = 0; p < pathArray.length; p++) {
  28667. var path = pathArray[p];
  28668. var l = path.length;
  28669. minlg = (minlg < l) ? minlg : l;
  28670. var j = 0;
  28671. while (j < minlg) {
  28672. positions[i] = path[j].x;
  28673. positions[i + 1] = path[j].y;
  28674. positions[i + 2] = path[j].z;
  28675. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  28676. BABYLON.Tmp.Vector3[0].x = path[j].x;
  28677. }
  28678. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  28679. BABYLON.Tmp.Vector3[1].x = path[j].x;
  28680. }
  28681. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  28682. BABYLON.Tmp.Vector3[0].y = path[j].y;
  28683. }
  28684. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  28685. BABYLON.Tmp.Vector3[1].y = path[j].y;
  28686. }
  28687. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  28688. BABYLON.Tmp.Vector3[0].z = path[j].z;
  28689. }
  28690. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  28691. BABYLON.Tmp.Vector3[1].z = path[j].z;
  28692. }
  28693. j++;
  28694. i += 3;
  28695. }
  28696. if (instance._closePath) {
  28697. positions[i] = path[0].x;
  28698. positions[i + 1] = path[0].y;
  28699. positions[i + 2] = path[0].z;
  28700. i += 3;
  28701. }
  28702. }
  28703. }
  28704. };
  28705. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28706. positionFunction(positions);
  28707. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  28708. instance._boundingInfo.update(instance._worldMatrix);
  28709. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28710. if (options.colors) {
  28711. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28712. for (var c = 0; c < options.colors.length; c++) {
  28713. colors[c * 4] = options.colors[c].r;
  28714. colors[c * 4 + 1] = options.colors[c].g;
  28715. colors[c * 4 + 2] = options.colors[c].b;
  28716. colors[c * 4 + 3] = options.colors[c].a;
  28717. }
  28718. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  28719. }
  28720. if (options.uvs) {
  28721. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28722. for (var i = 0; i < options.uvs.length; i++) {
  28723. uvs[i * 2] = options.uvs[i].x;
  28724. uvs[i * 2 + 1] = options.uvs[i].y;
  28725. }
  28726. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  28727. }
  28728. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  28729. var indices = instance.getIndices();
  28730. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28731. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  28732. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  28733. if (instance._closePath) {
  28734. var indexFirst = 0;
  28735. var indexLast = 0;
  28736. for (var p = 0; p < pathArray.length; p++) {
  28737. indexFirst = instance._idx[p] * 3;
  28738. if (p + 1 < pathArray.length) {
  28739. indexLast = (instance._idx[p + 1] - 1) * 3;
  28740. }
  28741. else {
  28742. indexLast = normals.length - 3;
  28743. }
  28744. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28745. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28746. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28747. normals[indexLast] = normals[indexFirst];
  28748. normals[indexLast + 1] = normals[indexFirst + 1];
  28749. normals[indexLast + 2] = normals[indexFirst + 2];
  28750. }
  28751. }
  28752. if (!(instance.areNormalsFrozen)) {
  28753. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28754. }
  28755. }
  28756. return instance;
  28757. }
  28758. else {
  28759. var ribbon = new BABYLON.Mesh(name, scene);
  28760. ribbon.sideOrientation = sideOrientation;
  28761. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  28762. if (closePath) {
  28763. ribbon._idx = vertexData._idx;
  28764. }
  28765. ribbon._closePath = closePath;
  28766. ribbon._closeArray = closeArray;
  28767. vertexData.applyToMesh(ribbon, updatable);
  28768. return ribbon;
  28769. }
  28770. };
  28771. /**
  28772. * Creates a cylinder or a cone mesh.
  28773. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  28774. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28775. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28776. * 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.
  28777. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28778. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28779. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  28780. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  28781. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  28782. * 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).
  28783. * 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
  28784. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  28785. * 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
  28786. * 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.
  28787. * If `enclose` is false, a ring surface is one element.
  28788. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  28789. * 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
  28790. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28791. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  28792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28794. */
  28795. MeshBuilder.CreateCylinder = function (name, options, scene) {
  28796. var cylinder = new BABYLON.Mesh(name, scene);
  28797. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28798. cylinder.sideOrientation = options.sideOrientation;
  28799. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  28800. vertexData.applyToMesh(cylinder, options.updatable);
  28801. return cylinder;
  28802. };
  28803. /**
  28804. * Creates a torus mesh.
  28805. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  28806. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28807. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28808. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28810. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  28811. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28813. */
  28814. MeshBuilder.CreateTorus = function (name, options, scene) {
  28815. var torus = new BABYLON.Mesh(name, scene);
  28816. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28817. torus.sideOrientation = options.sideOrientation;
  28818. var vertexData = BABYLON.VertexData.CreateTorus(options);
  28819. vertexData.applyToMesh(torus, options.updatable);
  28820. return torus;
  28821. };
  28822. /**
  28823. * Creates a torus knot mesh.
  28824. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  28825. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28826. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28827. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28828. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28829. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28830. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  28831. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28833. */
  28834. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  28835. var torusKnot = new BABYLON.Mesh(name, scene);
  28836. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28837. torusKnot.sideOrientation = options.sideOrientation;
  28838. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  28839. vertexData.applyToMesh(torusKnot, options.updatable);
  28840. return torusKnot;
  28841. };
  28842. /**
  28843. * Creates a line system mesh.
  28844. * A line system is a pool of many lines gathered in a single mesh.
  28845. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  28846. * 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.
  28847. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  28848. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  28849. * 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
  28850. * 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
  28851. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  28852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28853. */
  28854. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  28855. var instance = options.instance;
  28856. var lines = options.lines;
  28857. if (instance) {
  28858. var positionFunction = function (positions) {
  28859. var i = 0;
  28860. for (var l = 0; l < lines.length; l++) {
  28861. var points = lines[l];
  28862. for (var p = 0; p < points.length; p++) {
  28863. positions[i] = points[p].x;
  28864. positions[i + 1] = points[p].y;
  28865. positions[i + 2] = points[p].z;
  28866. i += 3;
  28867. }
  28868. }
  28869. };
  28870. instance.updateMeshPositions(positionFunction, false);
  28871. return instance;
  28872. }
  28873. // line system creation
  28874. var lineSystem = new BABYLON.LinesMesh(name, scene);
  28875. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  28876. vertexData.applyToMesh(lineSystem, options.updatable);
  28877. return lineSystem;
  28878. };
  28879. /**
  28880. * Creates a line mesh.
  28881. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  28882. * 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.
  28883. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28884. * The parameter `points` is an array successive Vector3.
  28885. * 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
  28886. * When updating an instance, remember that only point positions can change, not the number of points.
  28887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28888. */
  28889. MeshBuilder.CreateLines = function (name, options, scene) {
  28890. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  28891. return lines;
  28892. };
  28893. /**
  28894. * Creates a dashed line mesh.
  28895. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  28896. * 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.
  28897. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28898. * The parameter `points` is an array successive Vector3.
  28899. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28900. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28901. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28902. * 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
  28903. * When updating an instance, remember that only point positions can change, not the number of points.
  28904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28905. */
  28906. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  28907. var points = options.points;
  28908. var instance = options.instance;
  28909. var gapSize = options.gapSize;
  28910. var dashNb = options.dashNb;
  28911. var dashSize = options.dashSize;
  28912. if (instance) {
  28913. var positionFunction = function (positions) {
  28914. var curvect = BABYLON.Vector3.Zero();
  28915. var nbSeg = positions.length / 6;
  28916. var lg = 0;
  28917. var nb = 0;
  28918. var shft = 0;
  28919. var dashshft = 0;
  28920. var curshft = 0;
  28921. var p = 0;
  28922. var i = 0;
  28923. var j = 0;
  28924. for (i = 0; i < points.length - 1; i++) {
  28925. points[i + 1].subtractToRef(points[i], curvect);
  28926. lg += curvect.length();
  28927. }
  28928. shft = lg / nbSeg;
  28929. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  28930. for (i = 0; i < points.length - 1; i++) {
  28931. points[i + 1].subtractToRef(points[i], curvect);
  28932. nb = Math.floor(curvect.length() / shft);
  28933. curvect.normalize();
  28934. j = 0;
  28935. while (j < nb && p < positions.length) {
  28936. curshft = shft * j;
  28937. positions[p] = points[i].x + curshft * curvect.x;
  28938. positions[p + 1] = points[i].y + curshft * curvect.y;
  28939. positions[p + 2] = points[i].z + curshft * curvect.z;
  28940. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  28941. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  28942. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  28943. p += 6;
  28944. j++;
  28945. }
  28946. }
  28947. while (p < positions.length) {
  28948. positions[p] = points[i].x;
  28949. positions[p + 1] = points[i].y;
  28950. positions[p + 2] = points[i].z;
  28951. p += 3;
  28952. }
  28953. };
  28954. instance.updateMeshPositions(positionFunction, false);
  28955. return instance;
  28956. }
  28957. // dashed lines creation
  28958. var dashedLines = new BABYLON.LinesMesh(name, scene);
  28959. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  28960. vertexData.applyToMesh(dashedLines, options.updatable);
  28961. dashedLines.dashSize = dashSize;
  28962. dashedLines.gapSize = gapSize;
  28963. return dashedLines;
  28964. };
  28965. /**
  28966. * Creates an extruded shape mesh.
  28967. * 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.
  28968. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  28969. *
  28970. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  28971. * 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
  28972. * extruded along the Z axis.
  28973. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  28974. * 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.
  28975. * The parameter `scale` (float, default 1) is the value to scale the shape.
  28976. * 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
  28977. * 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
  28978. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  28979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28980. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  28981. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28982. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  28983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28984. */
  28985. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  28986. var path = options.path;
  28987. var shape = options.shape;
  28988. var scale = options.scale || 1;
  28989. var rotation = options.rotation || 0;
  28990. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  28991. var updatable = options.updatable;
  28992. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28993. var instance = options.instance;
  28994. var invertUV = options.invertUV || false;
  28995. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  28996. };
  28997. /**
  28998. * Creates an custom extruded shape mesh.
  28999. * 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.
  29000. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  29001. *
  29002. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29003. * 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
  29004. * extruded along the Z axis.
  29005. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29006. * 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
  29007. * and the distance of this point from the begining of the path :
  29008. * ```javascript
  29009. * var rotationFunction = function(i, distance) {
  29010. * // do things
  29011. * return rotationValue; }
  29012. * ```
  29013. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29014. * 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
  29015. * and the distance of this point from the begining of the path :
  29016. * ```javascript
  29017. * var scaleFunction = function(i, distance) {
  29018. * // do things
  29019. * return scaleValue;}
  29020. * ```
  29021. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29022. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29023. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29024. * 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
  29025. * 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
  29026. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29027. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29028. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  29029. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29030. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29032. */
  29033. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  29034. var path = options.path;
  29035. var shape = options.shape;
  29036. var scaleFunction = options.scaleFunction || (function () { return 1; });
  29037. var rotationFunction = options.rotationFunction || (function () { return 0; });
  29038. var ribbonCloseArray = options.ribbonCloseArray || false;
  29039. var ribbonClosePath = options.ribbonClosePath || false;
  29040. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  29041. var updatable = options.updatable;
  29042. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29043. var instance = options.instance;
  29044. var invertUV = options.invertUV || false;
  29045. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  29046. };
  29047. /**
  29048. * Creates lathe mesh.
  29049. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29050. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  29051. *
  29052. * 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
  29053. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29054. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29055. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29056. * 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.
  29057. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  29058. * 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
  29059. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29060. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  29061. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29062. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29064. */
  29065. MeshBuilder.CreateLathe = function (name, options, scene) {
  29066. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  29067. var closed = (options.closed === undefined) ? true : options.closed;
  29068. var shape = options.shape;
  29069. var radius = options.radius || 1;
  29070. var tessellation = options.tessellation || 64;
  29071. var updatable = options.updatable;
  29072. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29073. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  29074. var pi2 = Math.PI * 2;
  29075. var paths = new Array();
  29076. var invertUV = options.invertUV || false;
  29077. var i = 0;
  29078. var p = 0;
  29079. var step = pi2 / tessellation * arc;
  29080. var rotated;
  29081. var path = new Array();
  29082. ;
  29083. for (i = 0; i <= tessellation; i++) {
  29084. var path = [];
  29085. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  29086. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  29087. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  29088. }
  29089. for (p = 0; p < shape.length; p++) {
  29090. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  29091. path.push(rotated);
  29092. }
  29093. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  29094. 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));
  29095. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  29096. }
  29097. paths.push(path);
  29098. }
  29099. // lathe ribbon
  29100. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  29101. return lathe;
  29102. };
  29103. /**
  29104. * Creates a plane mesh.
  29105. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  29106. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29107. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  29108. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  29109. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29110. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  29111. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29112. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29113. */
  29114. MeshBuilder.CreatePlane = function (name, options, scene) {
  29115. var plane = new BABYLON.Mesh(name, scene);
  29116. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29117. plane.sideOrientation = options.sideOrientation;
  29118. var vertexData = BABYLON.VertexData.CreatePlane(options);
  29119. vertexData.applyToMesh(plane, options.updatable);
  29120. if (options.sourcePlane) {
  29121. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  29122. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  29123. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  29124. plane.rotate(vectorProduct, product);
  29125. }
  29126. return plane;
  29127. };
  29128. /**
  29129. * Creates a ground mesh.
  29130. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  29131. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29132. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29134. */
  29135. MeshBuilder.CreateGround = function (name, options, scene) {
  29136. var ground = new BABYLON.GroundMesh(name, scene);
  29137. ground._setReady(false);
  29138. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29139. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29140. ground._width = options.width || 1;
  29141. ground._height = options.height || 1;
  29142. ground._maxX = ground._width / 2;
  29143. ground._maxZ = ground._height / 2;
  29144. ground._minX = -ground._maxX;
  29145. ground._minZ = -ground._maxZ;
  29146. var vertexData = BABYLON.VertexData.CreateGround(options);
  29147. vertexData.applyToMesh(ground, options.updatable);
  29148. ground._setReady(true);
  29149. return ground;
  29150. };
  29151. /**
  29152. * Creates a tiled ground mesh.
  29153. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  29154. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29155. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29156. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29157. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29158. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29159. * numbers of subdivisions on the ground width and height of each tile.
  29160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29161. */
  29162. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  29163. var tiledGround = new BABYLON.Mesh(name, scene);
  29164. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  29165. vertexData.applyToMesh(tiledGround, options.updatable);
  29166. return tiledGround;
  29167. };
  29168. /**
  29169. * Creates a ground mesh from a height map.
  29170. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  29172. * The parameter `url` sets the URL of the height map image resource.
  29173. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29174. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29175. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29176. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29177. * 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.
  29178. * 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).
  29179. * This function is passed the newly built mesh :
  29180. * ```javascript
  29181. * function(mesh) { // do things
  29182. * return; }
  29183. * ```
  29184. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29185. */
  29186. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  29187. var width = options.width || 10.0;
  29188. var height = options.height || 10.0;
  29189. var subdivisions = options.subdivisions || 1 | 0;
  29190. var minHeight = options.minHeight || 0.0;
  29191. var maxHeight = options.maxHeight || 10.0;
  29192. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29193. var updatable = options.updatable;
  29194. var onReady = options.onReady;
  29195. var ground = new BABYLON.GroundMesh(name, scene);
  29196. ground._subdivisionsX = subdivisions;
  29197. ground._subdivisionsY = subdivisions;
  29198. ground._width = width;
  29199. ground._height = height;
  29200. ground._maxX = ground._width / 2.0;
  29201. ground._maxZ = ground._height / 2.0;
  29202. ground._minX = -ground._maxX;
  29203. ground._minZ = -ground._maxZ;
  29204. ground._setReady(false);
  29205. var onload = function (img) {
  29206. // Getting height map data
  29207. var canvas = document.createElement("canvas");
  29208. var context = canvas.getContext("2d");
  29209. var bufferWidth = img.width;
  29210. var bufferHeight = img.height;
  29211. canvas.width = bufferWidth;
  29212. canvas.height = bufferHeight;
  29213. context.drawImage(img, 0, 0);
  29214. // Create VertexData from map data
  29215. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29216. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  29217. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  29218. width: width, height: height,
  29219. subdivisions: subdivisions,
  29220. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  29221. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  29222. });
  29223. vertexData.applyToMesh(ground, updatable);
  29224. ground._setReady(true);
  29225. //execute ready callback, if set
  29226. if (onReady) {
  29227. onReady(ground);
  29228. }
  29229. };
  29230. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29231. return ground;
  29232. };
  29233. /**
  29234. * Creates a polygon mesh.
  29235. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29236. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  29237. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29238. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29239. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  29240. * Remember you can only change the shape positions, not their number when updating a polygon.
  29241. */
  29242. MeshBuilder.CreatePolygon = function (name, options, scene) {
  29243. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29244. var shape = options.shape;
  29245. var holes = options.holes || [];
  29246. var depth = options.depth || 0;
  29247. var contours = [];
  29248. var hole = [];
  29249. for (var i = 0; i < shape.length; i++) {
  29250. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  29251. }
  29252. var epsilon = 0.00000001;
  29253. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  29254. contours.pop();
  29255. }
  29256. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  29257. for (var hNb = 0; hNb < holes.length; hNb++) {
  29258. hole = [];
  29259. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  29260. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  29261. }
  29262. polygonTriangulation.addHole(hole);
  29263. }
  29264. var polygon = polygonTriangulation.build(options.updatable, depth);
  29265. polygon.sideOrientation = options.sideOrientation;
  29266. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  29267. vertexData.applyToMesh(polygon, options.updatable);
  29268. return polygon;
  29269. };
  29270. ;
  29271. /**
  29272. * Creates an extruded polygon mesh, with depth in the Y direction.
  29273. * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements).
  29274. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  29275. */
  29276. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  29277. return MeshBuilder.CreatePolygon(name, options, scene);
  29278. };
  29279. ;
  29280. /**
  29281. * Creates a tube mesh.
  29282. * 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.
  29283. *
  29284. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  29285. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29286. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29287. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29288. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29289. * 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.
  29290. * It must return a radius value (positive float) :
  29291. * ```javascript
  29292. * var radiusFunction = function(i, distance) {
  29293. * // do things
  29294. * return radius; }
  29295. * ```
  29296. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  29297. * 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
  29298. * 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
  29299. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29300. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  29301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29302. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29303. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29304. */
  29305. MeshBuilder.CreateTube = function (name, options, scene) {
  29306. var path = options.path;
  29307. var radius = options.radius || 1.0;
  29308. var tessellation = options.tessellation || 64 | 0;
  29309. var radiusFunction = options.radiusFunction;
  29310. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  29311. var invertUV = options.invertUV || false;
  29312. var updatable = options.updatable;
  29313. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29314. var instance = options.instance;
  29315. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  29316. // tube geometry
  29317. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  29318. var tangents = path3D.getTangents();
  29319. var normals = path3D.getNormals();
  29320. var distances = path3D.getDistances();
  29321. var pi2 = Math.PI * 2;
  29322. var step = pi2 / tessellation * arc;
  29323. var returnRadius = function () { return radius; };
  29324. var radiusFunctionFinal = radiusFunction || returnRadius;
  29325. var circlePath;
  29326. var rad;
  29327. var normal;
  29328. var rotated;
  29329. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  29330. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  29331. for (var i = 0; i < path.length; i++) {
  29332. rad = radiusFunctionFinal(i, distances[i]); // current radius
  29333. circlePath = Array(); // current circle array
  29334. normal = normals[i]; // current normal
  29335. for (var t = 0; t < tessellation; t++) {
  29336. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  29337. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  29338. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  29339. rotated.scaleInPlace(rad).addInPlace(path[i]);
  29340. circlePath[t] = rotated;
  29341. }
  29342. circlePaths[index] = circlePath;
  29343. index++;
  29344. }
  29345. // cap
  29346. var capPath = function (nbPoints, pathIndex) {
  29347. var pointCap = Array();
  29348. for (var i = 0; i < nbPoints; i++) {
  29349. pointCap.push(path[pathIndex]);
  29350. }
  29351. return pointCap;
  29352. };
  29353. switch (cap) {
  29354. case BABYLON.Mesh.NO_CAP:
  29355. break;
  29356. case BABYLON.Mesh.CAP_START:
  29357. circlePaths[0] = capPath(tessellation, 0);
  29358. circlePaths[1] = circlePaths[2].slice(0);
  29359. break;
  29360. case BABYLON.Mesh.CAP_END:
  29361. circlePaths[index] = circlePaths[index - 1].slice(0);
  29362. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  29363. break;
  29364. case BABYLON.Mesh.CAP_ALL:
  29365. circlePaths[0] = capPath(tessellation, 0);
  29366. circlePaths[1] = circlePaths[2].slice(0);
  29367. circlePaths[index] = circlePaths[index - 1].slice(0);
  29368. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  29369. break;
  29370. default:
  29371. break;
  29372. }
  29373. return circlePaths;
  29374. };
  29375. var path3D;
  29376. var pathArray;
  29377. if (instance) {
  29378. var arc = options.arc || instance.arc;
  29379. path3D = (instance.path3D).update(path);
  29380. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  29381. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  29382. instance.path3D = path3D;
  29383. instance.pathArray = pathArray;
  29384. instance.arc = arc;
  29385. return instance;
  29386. }
  29387. // tube creation
  29388. path3D = new BABYLON.Path3D(path);
  29389. var newPathArray = new Array();
  29390. cap = (cap < 0 || cap > 3) ? 0 : cap;
  29391. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  29392. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  29393. tube.pathArray = pathArray;
  29394. tube.path3D = path3D;
  29395. tube.tessellation = tessellation;
  29396. tube.cap = cap;
  29397. tube.arc = options.arc;
  29398. return tube;
  29399. };
  29400. /**
  29401. * Creates a polyhedron mesh.
  29402. *
  29403. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  29404. * 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
  29405. * to choose the wanted type.
  29406. * The parameter `size` (positive float, default 1) sets the polygon size.
  29407. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29408. * 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`.
  29409. * 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
  29410. * 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)`).
  29411. * 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
  29412. * 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.
  29413. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29414. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  29415. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29416. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29417. */
  29418. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  29419. var polyhedron = new BABYLON.Mesh(name, scene);
  29420. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29421. polyhedron.sideOrientation = options.sideOrientation;
  29422. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  29423. vertexData.applyToMesh(polyhedron, options.updatable);
  29424. return polyhedron;
  29425. };
  29426. /**
  29427. * Creates a decal mesh.
  29428. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  29429. * 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.
  29430. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29431. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29432. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29433. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29434. */
  29435. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  29436. var indices = sourceMesh.getIndices();
  29437. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29438. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29439. var position = options.position || BABYLON.Vector3.Zero();
  29440. var normal = options.normal || BABYLON.Vector3.Up();
  29441. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  29442. var angle = options.angle || 0;
  29443. // Getting correct rotation
  29444. if (!normal) {
  29445. var target = new BABYLON.Vector3(0, 0, 1);
  29446. var camera = sourceMesh.getScene().activeCamera;
  29447. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  29448. normal = camera.globalPosition.subtract(cameraWorldTarget);
  29449. }
  29450. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  29451. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  29452. var pitch = Math.atan2(normal.y, len);
  29453. // Matrix
  29454. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  29455. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  29456. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  29457. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  29458. var vertexData = new BABYLON.VertexData();
  29459. vertexData.indices = [];
  29460. vertexData.positions = [];
  29461. vertexData.normals = [];
  29462. vertexData.uvs = [];
  29463. var currentVertexDataIndex = 0;
  29464. var extractDecalVector3 = function (indexId) {
  29465. var vertexId = indices[indexId];
  29466. var result = new BABYLON.PositionNormalVertex();
  29467. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  29468. // Send vector to decal local world
  29469. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  29470. // Get normal
  29471. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  29472. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  29473. return result;
  29474. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  29475. var clip = function (vertices, axis) {
  29476. if (vertices.length === 0) {
  29477. return vertices;
  29478. }
  29479. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  29480. var clipVertices = function (v0, v1) {
  29481. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  29482. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  29483. };
  29484. var result = new Array();
  29485. for (var index = 0; index < vertices.length; index += 3) {
  29486. var v1Out;
  29487. var v2Out;
  29488. var v3Out;
  29489. var total = 0;
  29490. var nV1, nV2, nV3, nV4;
  29491. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  29492. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  29493. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  29494. v1Out = d1 > 0;
  29495. v2Out = d2 > 0;
  29496. v3Out = d3 > 0;
  29497. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  29498. switch (total) {
  29499. case 0:
  29500. result.push(vertices[index]);
  29501. result.push(vertices[index + 1]);
  29502. result.push(vertices[index + 2]);
  29503. break;
  29504. case 1:
  29505. if (v1Out) {
  29506. nV1 = vertices[index + 1];
  29507. nV2 = vertices[index + 2];
  29508. nV3 = clipVertices(vertices[index], nV1);
  29509. nV4 = clipVertices(vertices[index], nV2);
  29510. }
  29511. if (v2Out) {
  29512. nV1 = vertices[index];
  29513. nV2 = vertices[index + 2];
  29514. nV3 = clipVertices(vertices[index + 1], nV1);
  29515. nV4 = clipVertices(vertices[index + 1], nV2);
  29516. result.push(nV3);
  29517. result.push(nV2.clone());
  29518. result.push(nV1.clone());
  29519. result.push(nV2.clone());
  29520. result.push(nV3.clone());
  29521. result.push(nV4);
  29522. break;
  29523. }
  29524. if (v3Out) {
  29525. nV1 = vertices[index];
  29526. nV2 = vertices[index + 1];
  29527. nV3 = clipVertices(vertices[index + 2], nV1);
  29528. nV4 = clipVertices(vertices[index + 2], nV2);
  29529. }
  29530. result.push(nV1.clone());
  29531. result.push(nV2.clone());
  29532. result.push(nV3);
  29533. result.push(nV4);
  29534. result.push(nV3.clone());
  29535. result.push(nV2.clone());
  29536. break;
  29537. case 2:
  29538. if (!v1Out) {
  29539. nV1 = vertices[index].clone();
  29540. nV2 = clipVertices(nV1, vertices[index + 1]);
  29541. nV3 = clipVertices(nV1, vertices[index + 2]);
  29542. result.push(nV1);
  29543. result.push(nV2);
  29544. result.push(nV3);
  29545. }
  29546. if (!v2Out) {
  29547. nV1 = vertices[index + 1].clone();
  29548. nV2 = clipVertices(nV1, vertices[index + 2]);
  29549. nV3 = clipVertices(nV1, vertices[index]);
  29550. result.push(nV1);
  29551. result.push(nV2);
  29552. result.push(nV3);
  29553. }
  29554. if (!v3Out) {
  29555. nV1 = vertices[index + 2].clone();
  29556. nV2 = clipVertices(nV1, vertices[index]);
  29557. nV3 = clipVertices(nV1, vertices[index + 1]);
  29558. result.push(nV1);
  29559. result.push(nV2);
  29560. result.push(nV3);
  29561. }
  29562. break;
  29563. case 3:
  29564. break;
  29565. }
  29566. }
  29567. return result;
  29568. };
  29569. for (var index = 0; index < indices.length; index += 3) {
  29570. var faceVertices = new Array();
  29571. faceVertices.push(extractDecalVector3(index));
  29572. faceVertices.push(extractDecalVector3(index + 1));
  29573. faceVertices.push(extractDecalVector3(index + 2));
  29574. // Clip
  29575. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  29576. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  29577. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  29578. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  29579. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  29580. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  29581. if (faceVertices.length === 0) {
  29582. continue;
  29583. }
  29584. // Add UVs and get back to world
  29585. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  29586. var vertex = faceVertices[vIndex];
  29587. //TODO check for Int32Array | Uint32Array | Uint16Array
  29588. vertexData.indices.push(currentVertexDataIndex);
  29589. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  29590. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  29591. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  29592. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  29593. currentVertexDataIndex++;
  29594. }
  29595. }
  29596. // Return mesh
  29597. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  29598. vertexData.applyToMesh(decal);
  29599. decal.position = position.clone();
  29600. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  29601. return decal;
  29602. };
  29603. // Privates
  29604. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  29605. // extrusion geometry
  29606. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  29607. var tangents = path3D.getTangents();
  29608. var normals = path3D.getNormals();
  29609. var binormals = path3D.getBinormals();
  29610. var distances = path3D.getDistances();
  29611. var angle = 0;
  29612. var returnScale = function () { return scale; };
  29613. var returnRotation = function () { return rotation; };
  29614. var rotate = custom ? rotateFunction : returnRotation;
  29615. var scl = custom ? scaleFunction : returnScale;
  29616. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  29617. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  29618. for (var i = 0; i < curve.length; i++) {
  29619. var shapePath = new Array();
  29620. var angleStep = rotate(i, distances[i]);
  29621. var scaleRatio = scl(i, distances[i]);
  29622. for (var p = 0; p < shape.length; p++) {
  29623. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  29624. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  29625. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  29626. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  29627. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  29628. shapePath[p] = rotated;
  29629. }
  29630. shapePaths[index] = shapePath;
  29631. angle += angleStep;
  29632. index++;
  29633. }
  29634. // cap
  29635. var capPath = function (shapePath) {
  29636. var pointCap = Array();
  29637. var barycenter = BABYLON.Vector3.Zero();
  29638. var i;
  29639. for (i = 0; i < shapePath.length; i++) {
  29640. barycenter.addInPlace(shapePath[i]);
  29641. }
  29642. barycenter.scaleInPlace(1.0 / shapePath.length);
  29643. for (i = 0; i < shapePath.length; i++) {
  29644. pointCap.push(barycenter);
  29645. }
  29646. return pointCap;
  29647. };
  29648. switch (cap) {
  29649. case BABYLON.Mesh.NO_CAP:
  29650. break;
  29651. case BABYLON.Mesh.CAP_START:
  29652. shapePaths[0] = capPath(shapePaths[2]);
  29653. shapePaths[1] = shapePaths[2];
  29654. break;
  29655. case BABYLON.Mesh.CAP_END:
  29656. shapePaths[index] = shapePaths[index - 1];
  29657. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  29658. break;
  29659. case BABYLON.Mesh.CAP_ALL:
  29660. shapePaths[0] = capPath(shapePaths[2]);
  29661. shapePaths[1] = shapePaths[2];
  29662. shapePaths[index] = shapePaths[index - 1];
  29663. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  29664. break;
  29665. default:
  29666. break;
  29667. }
  29668. return shapePaths;
  29669. };
  29670. var path3D;
  29671. var pathArray;
  29672. if (instance) {
  29673. path3D = (instance.path3D).update(curve);
  29674. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  29675. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  29676. return instance;
  29677. }
  29678. // extruded shape creation
  29679. path3D = new BABYLON.Path3D(curve);
  29680. var newShapePaths = new Array();
  29681. cap = (cap < 0 || cap > 3) ? 0 : cap;
  29682. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  29683. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  29684. extrudedGeneric.pathArray = pathArray;
  29685. extrudedGeneric.path3D = path3D;
  29686. extrudedGeneric.cap = cap;
  29687. return extrudedGeneric;
  29688. };
  29689. return MeshBuilder;
  29690. }());
  29691. BABYLON.MeshBuilder = MeshBuilder;
  29692. })(BABYLON || (BABYLON = {}));
  29693. //# sourceMappingURL=babylon.meshBuilder.js.map
  29694. var BABYLON;
  29695. (function (BABYLON) {
  29696. var AnimationRange = (function () {
  29697. function AnimationRange(name, from, to) {
  29698. this.name = name;
  29699. this.from = from;
  29700. this.to = to;
  29701. }
  29702. AnimationRange.prototype.clone = function () {
  29703. return new AnimationRange(this.name, this.from, this.to);
  29704. };
  29705. return AnimationRange;
  29706. }());
  29707. BABYLON.AnimationRange = AnimationRange;
  29708. /**
  29709. * Composed of a frame, and an action function
  29710. */
  29711. var AnimationEvent = (function () {
  29712. function AnimationEvent(frame, action, onlyOnce) {
  29713. this.frame = frame;
  29714. this.action = action;
  29715. this.onlyOnce = onlyOnce;
  29716. this.isDone = false;
  29717. }
  29718. return AnimationEvent;
  29719. }());
  29720. BABYLON.AnimationEvent = AnimationEvent;
  29721. var PathCursor = (function () {
  29722. function PathCursor(path) {
  29723. this.path = path;
  29724. this._onchange = new Array();
  29725. this.value = 0;
  29726. this.animations = new Array();
  29727. }
  29728. PathCursor.prototype.getPoint = function () {
  29729. var point = this.path.getPointAtLengthPosition(this.value);
  29730. return new BABYLON.Vector3(point.x, 0, point.y);
  29731. };
  29732. PathCursor.prototype.moveAhead = function (step) {
  29733. if (step === void 0) { step = 0.002; }
  29734. this.move(step);
  29735. return this;
  29736. };
  29737. PathCursor.prototype.moveBack = function (step) {
  29738. if (step === void 0) { step = 0.002; }
  29739. this.move(-step);
  29740. return this;
  29741. };
  29742. PathCursor.prototype.move = function (step) {
  29743. if (Math.abs(step) > 1) {
  29744. throw "step size should be less than 1.";
  29745. }
  29746. this.value += step;
  29747. this.ensureLimits();
  29748. this.raiseOnChange();
  29749. return this;
  29750. };
  29751. PathCursor.prototype.ensureLimits = function () {
  29752. while (this.value > 1) {
  29753. this.value -= 1;
  29754. }
  29755. while (this.value < 0) {
  29756. this.value += 1;
  29757. }
  29758. return this;
  29759. };
  29760. // used by animation engine
  29761. PathCursor.prototype.markAsDirty = function (propertyName) {
  29762. this.ensureLimits();
  29763. this.raiseOnChange();
  29764. return this;
  29765. };
  29766. PathCursor.prototype.raiseOnChange = function () {
  29767. var _this = this;
  29768. this._onchange.forEach(function (f) { return f(_this); });
  29769. return this;
  29770. };
  29771. PathCursor.prototype.onchange = function (f) {
  29772. this._onchange.push(f);
  29773. return this;
  29774. };
  29775. return PathCursor;
  29776. }());
  29777. BABYLON.PathCursor = PathCursor;
  29778. var Animation = (function () {
  29779. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29780. this.name = name;
  29781. this.targetProperty = targetProperty;
  29782. this.framePerSecond = framePerSecond;
  29783. this.dataType = dataType;
  29784. this.loopMode = loopMode;
  29785. this.enableBlending = enableBlending;
  29786. this._offsetsCache = {};
  29787. this._highLimitsCache = {};
  29788. this._stopped = false;
  29789. this._blendingFactor = 0;
  29790. // The set of event that will be linked to this animation
  29791. this._events = new Array();
  29792. this.allowMatricesInterpolation = false;
  29793. this.blendingSpeed = 0.01;
  29794. this._ranges = {};
  29795. this.targetPropertyPath = targetProperty.split(".");
  29796. this.dataType = dataType;
  29797. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29798. }
  29799. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29800. var dataType = undefined;
  29801. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29802. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29803. }
  29804. else if (from instanceof BABYLON.Quaternion) {
  29805. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29806. }
  29807. else if (from instanceof BABYLON.Vector3) {
  29808. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29809. }
  29810. else if (from instanceof BABYLON.Vector2) {
  29811. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29812. }
  29813. else if (from instanceof BABYLON.Color3) {
  29814. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29815. }
  29816. else if (from instanceof BABYLON.Size) {
  29817. dataType = Animation.ANIMATIONTYPE_SIZE;
  29818. }
  29819. if (dataType == undefined) {
  29820. return null;
  29821. }
  29822. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29823. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29824. animation.setKeys(keys);
  29825. if (easingFunction !== undefined) {
  29826. animation.setEasingFunction(easingFunction);
  29827. }
  29828. return animation;
  29829. };
  29830. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29831. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29832. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29833. };
  29834. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29835. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29836. node.animations.push(animation);
  29837. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29838. };
  29839. // Methods
  29840. /**
  29841. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29842. */
  29843. Animation.prototype.toString = function (fullDetails) {
  29844. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29845. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29846. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29847. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29848. if (fullDetails) {
  29849. ret += ", Ranges: {";
  29850. var first = true;
  29851. for (var name in this._ranges) {
  29852. if (first) {
  29853. ret += ", ";
  29854. first = false;
  29855. }
  29856. ret += name;
  29857. }
  29858. ret += "}";
  29859. }
  29860. return ret;
  29861. };
  29862. /**
  29863. * Add an event to this animation.
  29864. */
  29865. Animation.prototype.addEvent = function (event) {
  29866. this._events.push(event);
  29867. };
  29868. /**
  29869. * Remove all events found at the given frame
  29870. * @param frame
  29871. */
  29872. Animation.prototype.removeEvents = function (frame) {
  29873. for (var index = 0; index < this._events.length; index++) {
  29874. if (this._events[index].frame === frame) {
  29875. this._events.splice(index, 1);
  29876. index--;
  29877. }
  29878. }
  29879. };
  29880. Animation.prototype.createRange = function (name, from, to) {
  29881. // check name not already in use; could happen for bones after serialized
  29882. if (!this._ranges[name]) {
  29883. this._ranges[name] = new AnimationRange(name, from, to);
  29884. }
  29885. };
  29886. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29887. if (deleteFrames === void 0) { deleteFrames = true; }
  29888. if (this._ranges[name]) {
  29889. if (deleteFrames) {
  29890. var from = this._ranges[name].from;
  29891. var to = this._ranges[name].to;
  29892. // this loop MUST go high to low for multiple splices to work
  29893. for (var key = this._keys.length - 1; key >= 0; key--) {
  29894. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29895. this._keys.splice(key, 1);
  29896. }
  29897. }
  29898. }
  29899. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29900. }
  29901. };
  29902. Animation.prototype.getRange = function (name) {
  29903. return this._ranges[name];
  29904. };
  29905. Animation.prototype.reset = function () {
  29906. this._offsetsCache = {};
  29907. this._highLimitsCache = {};
  29908. this.currentFrame = 0;
  29909. this._blendingFactor = 0;
  29910. this._originalBlendValue = null;
  29911. };
  29912. Animation.prototype.isStopped = function () {
  29913. return this._stopped;
  29914. };
  29915. Animation.prototype.getKeys = function () {
  29916. return this._keys;
  29917. };
  29918. Animation.prototype.getHighestFrame = function () {
  29919. var ret = 0;
  29920. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29921. if (ret < this._keys[key].frame) {
  29922. ret = this._keys[key].frame;
  29923. }
  29924. }
  29925. return ret;
  29926. };
  29927. Animation.prototype.getEasingFunction = function () {
  29928. return this._easingFunction;
  29929. };
  29930. Animation.prototype.setEasingFunction = function (easingFunction) {
  29931. this._easingFunction = easingFunction;
  29932. };
  29933. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29934. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  29935. };
  29936. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  29937. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  29938. };
  29939. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29940. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29941. };
  29942. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  29943. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  29944. };
  29945. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29946. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29947. };
  29948. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  29949. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  29950. };
  29951. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29952. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29953. };
  29954. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  29955. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  29956. };
  29957. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29958. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29959. };
  29960. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29961. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29962. };
  29963. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29964. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29965. };
  29966. Animation.prototype.clone = function () {
  29967. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29968. clone.enableBlending = this.enableBlending;
  29969. clone.blendingSpeed = this.blendingSpeed;
  29970. if (this._keys) {
  29971. clone.setKeys(this._keys);
  29972. }
  29973. if (this._ranges) {
  29974. clone._ranges = {};
  29975. for (var name in this._ranges) {
  29976. clone._ranges[name] = this._ranges[name].clone();
  29977. }
  29978. }
  29979. return clone;
  29980. };
  29981. Animation.prototype.setKeys = function (values) {
  29982. this._keys = values.slice(0);
  29983. this._offsetsCache = {};
  29984. this._highLimitsCache = {};
  29985. };
  29986. Animation.prototype._getKeyValue = function (value) {
  29987. if (typeof value === "function") {
  29988. return value();
  29989. }
  29990. return value;
  29991. };
  29992. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29993. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29994. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29995. }
  29996. this.currentFrame = currentFrame;
  29997. // Try to get a hash to find the right key
  29998. var startKeyIndex = 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));
  29999. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30000. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30001. startKeyIndex--;
  30002. }
  30003. }
  30004. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30005. var endKey = this._keys[key + 1];
  30006. if (endKey.frame >= currentFrame) {
  30007. var startKey = this._keys[key];
  30008. var startValue = this._getKeyValue(startKey.value);
  30009. var endValue = this._getKeyValue(endKey.value);
  30010. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30011. var frameDelta = endKey.frame - startKey.frame;
  30012. // gradient : percent of currentFrame between the frame inf and the frame sup
  30013. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30014. // check for easingFunction and correction of gradient
  30015. if (this._easingFunction != null) {
  30016. gradient = this._easingFunction.ease(gradient);
  30017. }
  30018. switch (this.dataType) {
  30019. // Float
  30020. case Animation.ANIMATIONTYPE_FLOAT:
  30021. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30022. switch (loopMode) {
  30023. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30024. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30025. return floatValue;
  30026. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30027. return offsetValue * repeatCount + floatValue;
  30028. }
  30029. break;
  30030. // Quaternion
  30031. case Animation.ANIMATIONTYPE_QUATERNION:
  30032. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30033. switch (loopMode) {
  30034. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30035. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30036. return quatValue;
  30037. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30038. return quatValue.add(offsetValue.scale(repeatCount));
  30039. }
  30040. return quatValue;
  30041. // Vector3
  30042. case Animation.ANIMATIONTYPE_VECTOR3:
  30043. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30044. switch (loopMode) {
  30045. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30046. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30047. return vec3Value;
  30048. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30049. return vec3Value.add(offsetValue.scale(repeatCount));
  30050. }
  30051. // Vector2
  30052. case Animation.ANIMATIONTYPE_VECTOR2:
  30053. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30054. switch (loopMode) {
  30055. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30056. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30057. return vec2Value;
  30058. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30059. return vec2Value.add(offsetValue.scale(repeatCount));
  30060. }
  30061. // Size
  30062. case Animation.ANIMATIONTYPE_SIZE:
  30063. switch (loopMode) {
  30064. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30065. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30066. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30067. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30068. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30069. }
  30070. // Color3
  30071. case Animation.ANIMATIONTYPE_COLOR3:
  30072. switch (loopMode) {
  30073. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30074. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30075. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30076. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30077. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30078. }
  30079. // Matrix
  30080. case Animation.ANIMATIONTYPE_MATRIX:
  30081. switch (loopMode) {
  30082. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30083. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30084. if (this.allowMatricesInterpolation) {
  30085. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30086. }
  30087. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30088. return startValue;
  30089. }
  30090. default:
  30091. break;
  30092. }
  30093. break;
  30094. }
  30095. }
  30096. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30097. };
  30098. Animation.prototype.setValue = function (currentValue, blend) {
  30099. if (blend === void 0) { blend = false; }
  30100. // Set value
  30101. var path;
  30102. var destination;
  30103. if (this.targetPropertyPath.length > 1) {
  30104. var property = this._target[this.targetPropertyPath[0]];
  30105. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30106. property = property[this.targetPropertyPath[index]];
  30107. }
  30108. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30109. destination = property;
  30110. }
  30111. else {
  30112. path = this.targetPropertyPath[0];
  30113. destination = this._target;
  30114. }
  30115. // Blending
  30116. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30117. if (!this._originalBlendValue) {
  30118. if (destination[path].clone) {
  30119. this._originalBlendValue = destination[path].clone();
  30120. }
  30121. else {
  30122. this._originalBlendValue = destination[path];
  30123. }
  30124. }
  30125. if (this._originalBlendValue.prototype) {
  30126. if (this._originalBlendValue.prototype.Lerp) {
  30127. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30128. }
  30129. else {
  30130. destination[path] = currentValue;
  30131. }
  30132. }
  30133. else if (this._originalBlendValue.m) {
  30134. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30135. }
  30136. else {
  30137. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30138. }
  30139. this._blendingFactor += this.blendingSpeed;
  30140. }
  30141. else {
  30142. destination[path] = currentValue;
  30143. }
  30144. if (this._target.markAsDirty) {
  30145. this._target.markAsDirty(this.targetProperty);
  30146. }
  30147. };
  30148. Animation.prototype.goToFrame = function (frame) {
  30149. if (frame < this._keys[0].frame) {
  30150. frame = this._keys[0].frame;
  30151. }
  30152. else if (frame > this._keys[this._keys.length - 1].frame) {
  30153. frame = this._keys[this._keys.length - 1].frame;
  30154. }
  30155. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30156. this.setValue(currentValue);
  30157. };
  30158. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30159. if (blend === void 0) { blend = false; }
  30160. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30161. this._stopped = true;
  30162. return false;
  30163. }
  30164. var returnValue = true;
  30165. // Adding a start key at frame 0 if missing
  30166. if (this._keys[0].frame !== 0) {
  30167. var newKey = { frame: 0, value: this._keys[0].value };
  30168. this._keys.splice(0, 0, newKey);
  30169. }
  30170. // Check limits
  30171. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30172. from = this._keys[0].frame;
  30173. }
  30174. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30175. to = this._keys[this._keys.length - 1].frame;
  30176. }
  30177. //to and from cannot be the same key
  30178. if (from === to) {
  30179. from++;
  30180. }
  30181. // Compute ratio
  30182. var range = to - from;
  30183. var offsetValue;
  30184. // ratio represents the frame delta between from and to
  30185. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30186. var highLimitValue = 0;
  30187. if (ratio > range && !loop) {
  30188. returnValue = false;
  30189. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30190. }
  30191. else {
  30192. // Get max value if required
  30193. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30194. var keyOffset = to.toString() + from.toString();
  30195. if (!this._offsetsCache[keyOffset]) {
  30196. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30197. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30198. switch (this.dataType) {
  30199. // Float
  30200. case Animation.ANIMATIONTYPE_FLOAT:
  30201. this._offsetsCache[keyOffset] = toValue - fromValue;
  30202. break;
  30203. // Quaternion
  30204. case Animation.ANIMATIONTYPE_QUATERNION:
  30205. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30206. break;
  30207. // Vector3
  30208. case Animation.ANIMATIONTYPE_VECTOR3:
  30209. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30210. // Vector2
  30211. case Animation.ANIMATIONTYPE_VECTOR2:
  30212. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30213. // Size
  30214. case Animation.ANIMATIONTYPE_SIZE:
  30215. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30216. // Color3
  30217. case Animation.ANIMATIONTYPE_COLOR3:
  30218. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30219. default:
  30220. break;
  30221. }
  30222. this._highLimitsCache[keyOffset] = toValue;
  30223. }
  30224. highLimitValue = this._highLimitsCache[keyOffset];
  30225. offsetValue = this._offsetsCache[keyOffset];
  30226. }
  30227. }
  30228. if (offsetValue === undefined) {
  30229. switch (this.dataType) {
  30230. // Float
  30231. case Animation.ANIMATIONTYPE_FLOAT:
  30232. offsetValue = 0;
  30233. break;
  30234. // Quaternion
  30235. case Animation.ANIMATIONTYPE_QUATERNION:
  30236. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30237. break;
  30238. // Vector3
  30239. case Animation.ANIMATIONTYPE_VECTOR3:
  30240. offsetValue = BABYLON.Vector3.Zero();
  30241. break;
  30242. // Vector2
  30243. case Animation.ANIMATIONTYPE_VECTOR2:
  30244. offsetValue = BABYLON.Vector2.Zero();
  30245. break;
  30246. // Size
  30247. case Animation.ANIMATIONTYPE_SIZE:
  30248. offsetValue = BABYLON.Size.Zero();
  30249. break;
  30250. // Color3
  30251. case Animation.ANIMATIONTYPE_COLOR3:
  30252. offsetValue = BABYLON.Color3.Black();
  30253. }
  30254. }
  30255. // Compute value
  30256. var repeatCount = (ratio / range) >> 0;
  30257. var currentFrame = returnValue ? from + ratio % range : to;
  30258. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30259. // Set value
  30260. this.setValue(currentValue);
  30261. // Check events
  30262. for (var index = 0; index < this._events.length; index++) {
  30263. if (currentFrame >= this._events[index].frame) {
  30264. var event = this._events[index];
  30265. if (!event.isDone) {
  30266. // If event should be done only once, remove it.
  30267. if (event.onlyOnce) {
  30268. this._events.splice(index, 1);
  30269. index--;
  30270. }
  30271. event.isDone = true;
  30272. event.action();
  30273. } // Don't do anything if the event has already be done.
  30274. }
  30275. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30276. // reset event, the animation is looping
  30277. this._events[index].isDone = false;
  30278. }
  30279. }
  30280. if (!returnValue) {
  30281. this._stopped = true;
  30282. }
  30283. return returnValue;
  30284. };
  30285. Animation.prototype.serialize = function () {
  30286. var serializationObject = {};
  30287. serializationObject.name = this.name;
  30288. serializationObject.property = this.targetProperty;
  30289. serializationObject.framePerSecond = this.framePerSecond;
  30290. serializationObject.dataType = this.dataType;
  30291. serializationObject.loopBehavior = this.loopMode;
  30292. serializationObject.enableBlending = this.enableBlending;
  30293. serializationObject.blendingSpeed = this.blendingSpeed;
  30294. var dataType = this.dataType;
  30295. serializationObject.keys = [];
  30296. var keys = this.getKeys();
  30297. for (var index = 0; index < keys.length; index++) {
  30298. var animationKey = keys[index];
  30299. var key = {};
  30300. key.frame = animationKey.frame;
  30301. switch (dataType) {
  30302. case Animation.ANIMATIONTYPE_FLOAT:
  30303. key.values = [animationKey.value];
  30304. break;
  30305. case Animation.ANIMATIONTYPE_QUATERNION:
  30306. case Animation.ANIMATIONTYPE_MATRIX:
  30307. case Animation.ANIMATIONTYPE_VECTOR3:
  30308. case Animation.ANIMATIONTYPE_COLOR3:
  30309. key.values = animationKey.value.asArray();
  30310. break;
  30311. }
  30312. serializationObject.keys.push(key);
  30313. }
  30314. serializationObject.ranges = [];
  30315. for (var name in this._ranges) {
  30316. var range = {};
  30317. range.name = name;
  30318. range.from = this._ranges[name].from;
  30319. range.to = this._ranges[name].to;
  30320. serializationObject.ranges.push(range);
  30321. }
  30322. return serializationObject;
  30323. };
  30324. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30325. get: function () {
  30326. return Animation._ANIMATIONTYPE_FLOAT;
  30327. },
  30328. enumerable: true,
  30329. configurable: true
  30330. });
  30331. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30332. get: function () {
  30333. return Animation._ANIMATIONTYPE_VECTOR3;
  30334. },
  30335. enumerable: true,
  30336. configurable: true
  30337. });
  30338. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30339. get: function () {
  30340. return Animation._ANIMATIONTYPE_VECTOR2;
  30341. },
  30342. enumerable: true,
  30343. configurable: true
  30344. });
  30345. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30346. get: function () {
  30347. return Animation._ANIMATIONTYPE_SIZE;
  30348. },
  30349. enumerable: true,
  30350. configurable: true
  30351. });
  30352. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30353. get: function () {
  30354. return Animation._ANIMATIONTYPE_QUATERNION;
  30355. },
  30356. enumerable: true,
  30357. configurable: true
  30358. });
  30359. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30360. get: function () {
  30361. return Animation._ANIMATIONTYPE_MATRIX;
  30362. },
  30363. enumerable: true,
  30364. configurable: true
  30365. });
  30366. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30367. get: function () {
  30368. return Animation._ANIMATIONTYPE_COLOR3;
  30369. },
  30370. enumerable: true,
  30371. configurable: true
  30372. });
  30373. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30374. get: function () {
  30375. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30376. },
  30377. enumerable: true,
  30378. configurable: true
  30379. });
  30380. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30381. get: function () {
  30382. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30383. },
  30384. enumerable: true,
  30385. configurable: true
  30386. });
  30387. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30388. get: function () {
  30389. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30390. },
  30391. enumerable: true,
  30392. configurable: true
  30393. });
  30394. Animation.Parse = function (parsedAnimation) {
  30395. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30396. var dataType = parsedAnimation.dataType;
  30397. var keys = [];
  30398. var data;
  30399. var index;
  30400. if (parsedAnimation.enableBlending) {
  30401. animation.enableBlending = parsedAnimation.enableBlending;
  30402. }
  30403. if (parsedAnimation.blendingSpeed) {
  30404. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30405. }
  30406. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30407. var key = parsedAnimation.keys[index];
  30408. switch (dataType) {
  30409. case Animation.ANIMATIONTYPE_FLOAT:
  30410. data = key.values[0];
  30411. break;
  30412. case Animation.ANIMATIONTYPE_QUATERNION:
  30413. data = BABYLON.Quaternion.FromArray(key.values);
  30414. break;
  30415. case Animation.ANIMATIONTYPE_MATRIX:
  30416. data = BABYLON.Matrix.FromArray(key.values);
  30417. break;
  30418. case Animation.ANIMATIONTYPE_COLOR3:
  30419. data = BABYLON.Color3.FromArray(key.values);
  30420. break;
  30421. case Animation.ANIMATIONTYPE_VECTOR3:
  30422. default:
  30423. data = BABYLON.Vector3.FromArray(key.values);
  30424. break;
  30425. }
  30426. keys.push({
  30427. frame: key.frame,
  30428. value: data
  30429. });
  30430. }
  30431. animation.setKeys(keys);
  30432. if (parsedAnimation.ranges) {
  30433. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30434. data = parsedAnimation.ranges[index];
  30435. animation.createRange(data.name, data.from, data.to);
  30436. }
  30437. }
  30438. return animation;
  30439. };
  30440. Animation.AppendSerializedAnimations = function (source, destination) {
  30441. if (source.animations) {
  30442. destination.animations = [];
  30443. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30444. var animation = source.animations[animationIndex];
  30445. destination.animations.push(animation.serialize());
  30446. }
  30447. }
  30448. };
  30449. return Animation;
  30450. }());
  30451. // Statics
  30452. Animation._ANIMATIONTYPE_FLOAT = 0;
  30453. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30454. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30455. Animation._ANIMATIONTYPE_MATRIX = 3;
  30456. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30457. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30458. Animation._ANIMATIONTYPE_SIZE = 6;
  30459. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30460. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30461. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30462. BABYLON.Animation = Animation;
  30463. })(BABYLON || (BABYLON = {}));
  30464. //# sourceMappingURL=babylon.animation.js.map
  30465. var BABYLON;
  30466. (function (BABYLON) {
  30467. var Animatable = (function () {
  30468. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30469. if (fromFrame === void 0) { fromFrame = 0; }
  30470. if (toFrame === void 0) { toFrame = 100; }
  30471. if (loopAnimation === void 0) { loopAnimation = false; }
  30472. if (speedRatio === void 0) { speedRatio = 1.0; }
  30473. this.target = target;
  30474. this.fromFrame = fromFrame;
  30475. this.toFrame = toFrame;
  30476. this.loopAnimation = loopAnimation;
  30477. this.speedRatio = speedRatio;
  30478. this.onAnimationEnd = onAnimationEnd;
  30479. this._localDelayOffset = null;
  30480. this._pausedDelay = null;
  30481. this._animations = new Array();
  30482. this._paused = false;
  30483. this.animationStarted = false;
  30484. if (animations) {
  30485. this.appendAnimations(target, animations);
  30486. }
  30487. this._scene = scene;
  30488. scene._activeAnimatables.push(this);
  30489. }
  30490. // Methods
  30491. Animatable.prototype.getAnimations = function () {
  30492. return this._animations;
  30493. };
  30494. Animatable.prototype.appendAnimations = function (target, animations) {
  30495. for (var index = 0; index < animations.length; index++) {
  30496. var animation = animations[index];
  30497. animation._target = target;
  30498. this._animations.push(animation);
  30499. }
  30500. };
  30501. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30502. var animations = this._animations;
  30503. for (var index = 0; index < animations.length; index++) {
  30504. if (animations[index].targetProperty === property) {
  30505. return animations[index];
  30506. }
  30507. }
  30508. return null;
  30509. };
  30510. Animatable.prototype.reset = function () {
  30511. var animations = this._animations;
  30512. for (var index = 0; index < animations.length; index++) {
  30513. animations[index].reset();
  30514. }
  30515. this._localDelayOffset = null;
  30516. this._pausedDelay = null;
  30517. };
  30518. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30519. var animations = this._animations;
  30520. for (var index = 0; index < animations.length; index++) {
  30521. animations[index].enableBlending = true;
  30522. animations[index].blendingSpeed = blendingSpeed;
  30523. }
  30524. };
  30525. Animatable.prototype.disableBlending = function () {
  30526. var animations = this._animations;
  30527. for (var index = 0; index < animations.length; index++) {
  30528. animations[index].enableBlending = false;
  30529. }
  30530. };
  30531. Animatable.prototype.goToFrame = function (frame) {
  30532. var animations = this._animations;
  30533. if (animations[0]) {
  30534. var fps = animations[0].framePerSecond;
  30535. var currentFrame = animations[0].currentFrame;
  30536. var adjustTime = frame - currentFrame;
  30537. var delay = adjustTime * 1000 / fps;
  30538. this._localDelayOffset -= delay;
  30539. }
  30540. for (var index = 0; index < animations.length; index++) {
  30541. animations[index].goToFrame(frame);
  30542. }
  30543. };
  30544. Animatable.prototype.pause = function () {
  30545. if (this._paused) {
  30546. return;
  30547. }
  30548. this._paused = true;
  30549. };
  30550. Animatable.prototype.restart = function () {
  30551. this._paused = false;
  30552. };
  30553. Animatable.prototype.stop = function (animationName) {
  30554. if (animationName) {
  30555. var idx = this._scene._activeAnimatables.indexOf(this);
  30556. if (idx > -1) {
  30557. var animations = this._animations;
  30558. for (var index = animations.length - 1; index >= 0; index--) {
  30559. if (typeof animationName === "string" && animations[index].name != animationName) {
  30560. continue;
  30561. }
  30562. animations[index].reset();
  30563. animations.splice(index, 1);
  30564. }
  30565. if (animations.length == 0) {
  30566. this._scene._activeAnimatables.splice(idx, 1);
  30567. if (this.onAnimationEnd) {
  30568. this.onAnimationEnd();
  30569. }
  30570. }
  30571. }
  30572. }
  30573. else {
  30574. var index = this._scene._activeAnimatables.indexOf(this);
  30575. if (index > -1) {
  30576. this._scene._activeAnimatables.splice(index, 1);
  30577. var animations = this._animations;
  30578. for (var index = 0; index < animations.length; index++) {
  30579. animations[index].reset();
  30580. }
  30581. if (this.onAnimationEnd) {
  30582. this.onAnimationEnd();
  30583. }
  30584. }
  30585. }
  30586. };
  30587. Animatable.prototype._animate = function (delay) {
  30588. if (this._paused) {
  30589. this.animationStarted = false;
  30590. if (this._pausedDelay === null) {
  30591. this._pausedDelay = delay;
  30592. }
  30593. return true;
  30594. }
  30595. if (this._localDelayOffset === null) {
  30596. this._localDelayOffset = delay;
  30597. }
  30598. else if (this._pausedDelay !== null) {
  30599. this._localDelayOffset += delay - this._pausedDelay;
  30600. this._pausedDelay = null;
  30601. }
  30602. // Animating
  30603. var running = false;
  30604. var animations = this._animations;
  30605. var index;
  30606. for (index = 0; index < animations.length; index++) {
  30607. var animation = animations[index];
  30608. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30609. running = running || isRunning;
  30610. }
  30611. this.animationStarted = running;
  30612. if (!running) {
  30613. // Remove from active animatables
  30614. index = this._scene._activeAnimatables.indexOf(this);
  30615. this._scene._activeAnimatables.splice(index, 1);
  30616. }
  30617. if (!running && this.onAnimationEnd) {
  30618. this.onAnimationEnd();
  30619. this.onAnimationEnd = null;
  30620. }
  30621. return running;
  30622. };
  30623. return Animatable;
  30624. }());
  30625. BABYLON.Animatable = Animatable;
  30626. })(BABYLON || (BABYLON = {}));
  30627. //# sourceMappingURL=babylon.animatable.js.map
  30628. var BABYLON;
  30629. (function (BABYLON) {
  30630. var EasingFunction = (function () {
  30631. function EasingFunction() {
  30632. // Properties
  30633. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30634. }
  30635. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30636. get: function () {
  30637. return EasingFunction._EASINGMODE_EASEIN;
  30638. },
  30639. enumerable: true,
  30640. configurable: true
  30641. });
  30642. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30643. get: function () {
  30644. return EasingFunction._EASINGMODE_EASEOUT;
  30645. },
  30646. enumerable: true,
  30647. configurable: true
  30648. });
  30649. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30650. get: function () {
  30651. return EasingFunction._EASINGMODE_EASEINOUT;
  30652. },
  30653. enumerable: true,
  30654. configurable: true
  30655. });
  30656. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30657. var n = Math.min(Math.max(easingMode, 0), 2);
  30658. this._easingMode = n;
  30659. };
  30660. EasingFunction.prototype.getEasingMode = function () {
  30661. return this._easingMode;
  30662. };
  30663. EasingFunction.prototype.easeInCore = function (gradient) {
  30664. throw new Error('You must implement this method');
  30665. };
  30666. EasingFunction.prototype.ease = function (gradient) {
  30667. switch (this._easingMode) {
  30668. case EasingFunction.EASINGMODE_EASEIN:
  30669. return this.easeInCore(gradient);
  30670. case EasingFunction.EASINGMODE_EASEOUT:
  30671. return (1 - this.easeInCore(1 - gradient));
  30672. }
  30673. if (gradient >= 0.5) {
  30674. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30675. }
  30676. return (this.easeInCore(gradient * 2) * 0.5);
  30677. };
  30678. return EasingFunction;
  30679. }());
  30680. //Statics
  30681. EasingFunction._EASINGMODE_EASEIN = 0;
  30682. EasingFunction._EASINGMODE_EASEOUT = 1;
  30683. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30684. BABYLON.EasingFunction = EasingFunction;
  30685. var CircleEase = (function (_super) {
  30686. __extends(CircleEase, _super);
  30687. function CircleEase() {
  30688. return _super !== null && _super.apply(this, arguments) || this;
  30689. }
  30690. CircleEase.prototype.easeInCore = function (gradient) {
  30691. gradient = Math.max(0, Math.min(1, gradient));
  30692. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30693. };
  30694. return CircleEase;
  30695. }(EasingFunction));
  30696. BABYLON.CircleEase = CircleEase;
  30697. var BackEase = (function (_super) {
  30698. __extends(BackEase, _super);
  30699. function BackEase(amplitude) {
  30700. if (amplitude === void 0) { amplitude = 1; }
  30701. var _this = _super.call(this) || this;
  30702. _this.amplitude = amplitude;
  30703. return _this;
  30704. }
  30705. BackEase.prototype.easeInCore = function (gradient) {
  30706. var num = Math.max(0, this.amplitude);
  30707. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30708. };
  30709. return BackEase;
  30710. }(EasingFunction));
  30711. BABYLON.BackEase = BackEase;
  30712. var BounceEase = (function (_super) {
  30713. __extends(BounceEase, _super);
  30714. function BounceEase(bounces, bounciness) {
  30715. if (bounces === void 0) { bounces = 3; }
  30716. if (bounciness === void 0) { bounciness = 2; }
  30717. var _this = _super.call(this) || this;
  30718. _this.bounces = bounces;
  30719. _this.bounciness = bounciness;
  30720. return _this;
  30721. }
  30722. BounceEase.prototype.easeInCore = function (gradient) {
  30723. var y = Math.max(0.0, this.bounces);
  30724. var bounciness = this.bounciness;
  30725. if (bounciness <= 1.0) {
  30726. bounciness = 1.001;
  30727. }
  30728. var num9 = Math.pow(bounciness, y);
  30729. var num5 = 1.0 - bounciness;
  30730. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30731. var num15 = gradient * num4;
  30732. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30733. var num3 = Math.floor(num65);
  30734. var num13 = num3 + 1.0;
  30735. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30736. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30737. var num7 = (num8 + num12) * 0.5;
  30738. var num6 = gradient - num7;
  30739. var num2 = num7 - num8;
  30740. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30741. };
  30742. return BounceEase;
  30743. }(EasingFunction));
  30744. BABYLON.BounceEase = BounceEase;
  30745. var CubicEase = (function (_super) {
  30746. __extends(CubicEase, _super);
  30747. function CubicEase() {
  30748. return _super !== null && _super.apply(this, arguments) || this;
  30749. }
  30750. CubicEase.prototype.easeInCore = function (gradient) {
  30751. return (gradient * gradient * gradient);
  30752. };
  30753. return CubicEase;
  30754. }(EasingFunction));
  30755. BABYLON.CubicEase = CubicEase;
  30756. var ElasticEase = (function (_super) {
  30757. __extends(ElasticEase, _super);
  30758. function ElasticEase(oscillations, springiness) {
  30759. if (oscillations === void 0) { oscillations = 3; }
  30760. if (springiness === void 0) { springiness = 3; }
  30761. var _this = _super.call(this) || this;
  30762. _this.oscillations = oscillations;
  30763. _this.springiness = springiness;
  30764. return _this;
  30765. }
  30766. ElasticEase.prototype.easeInCore = function (gradient) {
  30767. var num2;
  30768. var num3 = Math.max(0.0, this.oscillations);
  30769. var num = Math.max(0.0, this.springiness);
  30770. if (num == 0) {
  30771. num2 = gradient;
  30772. }
  30773. else {
  30774. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30775. }
  30776. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30777. };
  30778. return ElasticEase;
  30779. }(EasingFunction));
  30780. BABYLON.ElasticEase = ElasticEase;
  30781. var ExponentialEase = (function (_super) {
  30782. __extends(ExponentialEase, _super);
  30783. function ExponentialEase(exponent) {
  30784. if (exponent === void 0) { exponent = 2; }
  30785. var _this = _super.call(this) || this;
  30786. _this.exponent = exponent;
  30787. return _this;
  30788. }
  30789. ExponentialEase.prototype.easeInCore = function (gradient) {
  30790. if (this.exponent <= 0) {
  30791. return gradient;
  30792. }
  30793. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30794. };
  30795. return ExponentialEase;
  30796. }(EasingFunction));
  30797. BABYLON.ExponentialEase = ExponentialEase;
  30798. var PowerEase = (function (_super) {
  30799. __extends(PowerEase, _super);
  30800. function PowerEase(power) {
  30801. if (power === void 0) { power = 2; }
  30802. var _this = _super.call(this) || this;
  30803. _this.power = power;
  30804. return _this;
  30805. }
  30806. PowerEase.prototype.easeInCore = function (gradient) {
  30807. var y = Math.max(0.0, this.power);
  30808. return Math.pow(gradient, y);
  30809. };
  30810. return PowerEase;
  30811. }(EasingFunction));
  30812. BABYLON.PowerEase = PowerEase;
  30813. var QuadraticEase = (function (_super) {
  30814. __extends(QuadraticEase, _super);
  30815. function QuadraticEase() {
  30816. return _super !== null && _super.apply(this, arguments) || this;
  30817. }
  30818. QuadraticEase.prototype.easeInCore = function (gradient) {
  30819. return (gradient * gradient);
  30820. };
  30821. return QuadraticEase;
  30822. }(EasingFunction));
  30823. BABYLON.QuadraticEase = QuadraticEase;
  30824. var QuarticEase = (function (_super) {
  30825. __extends(QuarticEase, _super);
  30826. function QuarticEase() {
  30827. return _super !== null && _super.apply(this, arguments) || this;
  30828. }
  30829. QuarticEase.prototype.easeInCore = function (gradient) {
  30830. return (gradient * gradient * gradient * gradient);
  30831. };
  30832. return QuarticEase;
  30833. }(EasingFunction));
  30834. BABYLON.QuarticEase = QuarticEase;
  30835. var QuinticEase = (function (_super) {
  30836. __extends(QuinticEase, _super);
  30837. function QuinticEase() {
  30838. return _super !== null && _super.apply(this, arguments) || this;
  30839. }
  30840. QuinticEase.prototype.easeInCore = function (gradient) {
  30841. return (gradient * gradient * gradient * gradient * gradient);
  30842. };
  30843. return QuinticEase;
  30844. }(EasingFunction));
  30845. BABYLON.QuinticEase = QuinticEase;
  30846. var SineEase = (function (_super) {
  30847. __extends(SineEase, _super);
  30848. function SineEase() {
  30849. return _super !== null && _super.apply(this, arguments) || this;
  30850. }
  30851. SineEase.prototype.easeInCore = function (gradient) {
  30852. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30853. };
  30854. return SineEase;
  30855. }(EasingFunction));
  30856. BABYLON.SineEase = SineEase;
  30857. var BezierCurveEase = (function (_super) {
  30858. __extends(BezierCurveEase, _super);
  30859. function BezierCurveEase(x1, y1, x2, y2) {
  30860. if (x1 === void 0) { x1 = 0; }
  30861. if (y1 === void 0) { y1 = 0; }
  30862. if (x2 === void 0) { x2 = 1; }
  30863. if (y2 === void 0) { y2 = 1; }
  30864. var _this = _super.call(this) || this;
  30865. _this.x1 = x1;
  30866. _this.y1 = y1;
  30867. _this.x2 = x2;
  30868. _this.y2 = y2;
  30869. return _this;
  30870. }
  30871. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30872. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30873. };
  30874. return BezierCurveEase;
  30875. }(EasingFunction));
  30876. BABYLON.BezierCurveEase = BezierCurveEase;
  30877. })(BABYLON || (BABYLON = {}));
  30878. //# sourceMappingURL=babylon.easing.js.map
  30879. var BABYLON;
  30880. (function (BABYLON) {
  30881. BABYLON.CameraInputTypes = {};
  30882. var CameraInputsManager = (function () {
  30883. function CameraInputsManager(camera) {
  30884. this.attached = {};
  30885. this.camera = camera;
  30886. this.checkInputs = function () { };
  30887. }
  30888. CameraInputsManager.prototype.add = function (input) {
  30889. var type = input.getSimpleName();
  30890. if (this.attached[type]) {
  30891. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  30892. return;
  30893. }
  30894. this.attached[type] = input;
  30895. input.camera = this.camera;
  30896. //for checkInputs, we are dynamically creating a function
  30897. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  30898. if (input.checkInputs) {
  30899. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  30900. }
  30901. if (this.attachedElement) {
  30902. input.attachControl(this.attachedElement);
  30903. }
  30904. };
  30905. CameraInputsManager.prototype.remove = function (inputToRemove) {
  30906. for (var cam in this.attached) {
  30907. var input = this.attached[cam];
  30908. if (input === inputToRemove) {
  30909. input.detachControl(this.attachedElement);
  30910. delete this.attached[cam];
  30911. this.rebuildInputCheck();
  30912. }
  30913. }
  30914. };
  30915. CameraInputsManager.prototype.removeByType = function (inputType) {
  30916. for (var cam in this.attached) {
  30917. var input = this.attached[cam];
  30918. if (input.getTypeName() === inputType) {
  30919. input.detachControl(this.attachedElement);
  30920. delete this.attached[cam];
  30921. this.rebuildInputCheck();
  30922. }
  30923. }
  30924. };
  30925. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  30926. var current = this.checkInputs;
  30927. return function () {
  30928. current();
  30929. fn();
  30930. };
  30931. };
  30932. CameraInputsManager.prototype.attachInput = function (input) {
  30933. input.attachControl(this.attachedElement, this.noPreventDefault);
  30934. };
  30935. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  30936. if (this.attachedElement) {
  30937. return;
  30938. }
  30939. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  30940. this.attachedElement = element;
  30941. this.noPreventDefault = noPreventDefault;
  30942. for (var cam in this.attached) {
  30943. var input = this.attached[cam];
  30944. this.attached[cam].attachControl(element, noPreventDefault);
  30945. }
  30946. };
  30947. CameraInputsManager.prototype.detachElement = function (element) {
  30948. if (this.attachedElement !== element) {
  30949. return;
  30950. }
  30951. for (var cam in this.attached) {
  30952. var input = this.attached[cam];
  30953. this.attached[cam].detachControl(element);
  30954. }
  30955. this.attachedElement = null;
  30956. };
  30957. CameraInputsManager.prototype.rebuildInputCheck = function () {
  30958. this.checkInputs = function () { };
  30959. for (var cam in this.attached) {
  30960. var input = this.attached[cam];
  30961. if (input.checkInputs) {
  30962. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  30963. }
  30964. }
  30965. };
  30966. CameraInputsManager.prototype.clear = function () {
  30967. if (this.attachedElement) {
  30968. this.detachElement(this.attachedElement);
  30969. }
  30970. this.attached = {};
  30971. this.attachedElement = null;
  30972. this.checkInputs = function () { };
  30973. };
  30974. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  30975. var inputs = {};
  30976. for (var cam in this.attached) {
  30977. var input = this.attached[cam];
  30978. var res = BABYLON.SerializationHelper.Serialize(input);
  30979. inputs[input.getTypeName()] = res;
  30980. }
  30981. serializedCamera.inputsmgr = inputs;
  30982. };
  30983. CameraInputsManager.prototype.parse = function (parsedCamera) {
  30984. var parsedInputs = parsedCamera.inputsmgr;
  30985. if (parsedInputs) {
  30986. this.clear();
  30987. for (var n in parsedInputs) {
  30988. var construct = BABYLON.CameraInputTypes[n];
  30989. if (construct) {
  30990. var parsedinput = parsedInputs[n];
  30991. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  30992. this.add(input);
  30993. }
  30994. }
  30995. }
  30996. else {
  30997. //2016-03-08 this part is for managing backward compatibility
  30998. for (var n in this.attached) {
  30999. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31000. if (construct) {
  31001. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31002. this.remove(this.attached[n]);
  31003. this.add(input);
  31004. }
  31005. }
  31006. }
  31007. };
  31008. return CameraInputsManager;
  31009. }());
  31010. BABYLON.CameraInputsManager = CameraInputsManager;
  31011. })(BABYLON || (BABYLON = {}));
  31012. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31013. /// <reference path="babylon.camera.ts" />
  31014. var BABYLON;
  31015. (function (BABYLON) {
  31016. var TargetCamera = (function (_super) {
  31017. __extends(TargetCamera, _super);
  31018. function TargetCamera(name, position, scene) {
  31019. var _this = _super.call(this, name, position, scene) || this;
  31020. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31021. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31022. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31023. _this.speed = 2.0;
  31024. _this.noRotationConstraint = false;
  31025. _this.lockedTarget = null;
  31026. _this._currentTarget = BABYLON.Vector3.Zero();
  31027. _this._viewMatrix = BABYLON.Matrix.Zero();
  31028. _this._camMatrix = BABYLON.Matrix.Zero();
  31029. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31030. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31031. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31032. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31033. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31034. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31035. _this._tempMatrix = BABYLON.Matrix.Zero();
  31036. return _this;
  31037. }
  31038. TargetCamera.prototype.getFrontPosition = function (distance) {
  31039. var direction = this.getTarget().subtract(this.position);
  31040. direction.normalize();
  31041. direction.scaleInPlace(distance);
  31042. return this.globalPosition.add(direction);
  31043. };
  31044. TargetCamera.prototype._getLockedTargetPosition = function () {
  31045. if (!this.lockedTarget) {
  31046. return null;
  31047. }
  31048. if (this.lockedTarget.absolutePosition) {
  31049. this.lockedTarget.computeWorldMatrix();
  31050. }
  31051. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31052. };
  31053. // Cache
  31054. TargetCamera.prototype._initCache = function () {
  31055. _super.prototype._initCache.call(this);
  31056. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31057. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31058. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31059. };
  31060. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31061. if (!ignoreParentClass) {
  31062. _super.prototype._updateCache.call(this);
  31063. }
  31064. var lockedTargetPosition = this._getLockedTargetPosition();
  31065. if (!lockedTargetPosition) {
  31066. this._cache.lockedTarget = null;
  31067. }
  31068. else {
  31069. if (!this._cache.lockedTarget) {
  31070. this._cache.lockedTarget = lockedTargetPosition.clone();
  31071. }
  31072. else {
  31073. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31074. }
  31075. }
  31076. this._cache.rotation.copyFrom(this.rotation);
  31077. if (this.rotationQuaternion)
  31078. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31079. };
  31080. // Synchronized
  31081. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31082. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31083. return false;
  31084. }
  31085. var lockedTargetPosition = this._getLockedTargetPosition();
  31086. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31087. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31088. };
  31089. // Methods
  31090. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31091. var engine = this.getEngine();
  31092. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31093. };
  31094. // Target
  31095. TargetCamera.prototype.setTarget = function (target) {
  31096. this.upVector.normalize();
  31097. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31098. this._camMatrix.invert();
  31099. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31100. var vDir = target.subtract(this.position);
  31101. if (vDir.x >= 0.0) {
  31102. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31103. }
  31104. else {
  31105. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31106. }
  31107. this.rotation.z = 0;
  31108. if (isNaN(this.rotation.x)) {
  31109. this.rotation.x = 0;
  31110. }
  31111. if (isNaN(this.rotation.y)) {
  31112. this.rotation.y = 0;
  31113. }
  31114. if (isNaN(this.rotation.z)) {
  31115. this.rotation.z = 0;
  31116. }
  31117. if (this.rotationQuaternion) {
  31118. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31119. }
  31120. };
  31121. /**
  31122. * Return the current target position of the camera. This value is expressed in local space.
  31123. */
  31124. TargetCamera.prototype.getTarget = function () {
  31125. return this._currentTarget;
  31126. };
  31127. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31128. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31129. };
  31130. TargetCamera.prototype._updatePosition = function () {
  31131. if (this.parent) {
  31132. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31133. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31134. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31135. return;
  31136. }
  31137. this.position.addInPlace(this.cameraDirection);
  31138. };
  31139. TargetCamera.prototype._checkInputs = function () {
  31140. var needToMove = this._decideIfNeedsToMove();
  31141. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31142. // Move
  31143. if (needToMove) {
  31144. this._updatePosition();
  31145. }
  31146. // Rotate
  31147. if (needToRotate) {
  31148. this.rotation.x += this.cameraRotation.x;
  31149. this.rotation.y += this.cameraRotation.y;
  31150. //rotate, if quaternion is set and rotation was used
  31151. if (this.rotationQuaternion) {
  31152. var len = this.rotation.lengthSquared();
  31153. if (len) {
  31154. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31155. }
  31156. }
  31157. if (!this.noRotationConstraint) {
  31158. var limit = (Math.PI / 2) * 0.95;
  31159. if (this.rotation.x > limit)
  31160. this.rotation.x = limit;
  31161. if (this.rotation.x < -limit)
  31162. this.rotation.x = -limit;
  31163. }
  31164. }
  31165. // Inertia
  31166. if (needToMove) {
  31167. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31168. this.cameraDirection.x = 0;
  31169. }
  31170. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31171. this.cameraDirection.y = 0;
  31172. }
  31173. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31174. this.cameraDirection.z = 0;
  31175. }
  31176. this.cameraDirection.scaleInPlace(this.inertia);
  31177. }
  31178. if (needToRotate) {
  31179. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31180. this.cameraRotation.x = 0;
  31181. }
  31182. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31183. this.cameraRotation.y = 0;
  31184. }
  31185. this.cameraRotation.scaleInPlace(this.inertia);
  31186. }
  31187. _super.prototype._checkInputs.call(this);
  31188. };
  31189. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31190. if (this.rotationQuaternion) {
  31191. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31192. //update the up vector!
  31193. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31194. }
  31195. else {
  31196. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31197. }
  31198. };
  31199. TargetCamera.prototype._getViewMatrix = function () {
  31200. if (!this.lockedTarget) {
  31201. // Compute
  31202. this._updateCameraRotationMatrix();
  31203. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31204. // Computing target and final matrix
  31205. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31206. }
  31207. else {
  31208. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31209. }
  31210. if (this.getScene().useRightHandedSystem) {
  31211. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31212. }
  31213. else {
  31214. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31215. }
  31216. return this._viewMatrix;
  31217. };
  31218. /**
  31219. * @override
  31220. * Override Camera.createRigCamera
  31221. */
  31222. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31223. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31224. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31225. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31226. if (!this.rotationQuaternion) {
  31227. this.rotationQuaternion = new BABYLON.Quaternion();
  31228. }
  31229. rigCamera._cameraRigParams = {};
  31230. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31231. }
  31232. return rigCamera;
  31233. }
  31234. return null;
  31235. };
  31236. /**
  31237. * @override
  31238. * Override Camera._updateRigCameras
  31239. */
  31240. TargetCamera.prototype._updateRigCameras = function () {
  31241. var camLeft = this._rigCameras[0];
  31242. var camRight = this._rigCameras[1];
  31243. switch (this.cameraRigMode) {
  31244. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31245. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31246. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31247. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31248. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31249. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31250. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31251. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31252. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31253. camLeft.setTarget(this.getTarget());
  31254. camRight.setTarget(this.getTarget());
  31255. break;
  31256. case BABYLON.Camera.RIG_MODE_VR:
  31257. if (camLeft.rotationQuaternion) {
  31258. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31259. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31260. }
  31261. else {
  31262. camLeft.rotation.copyFrom(this.rotation);
  31263. camRight.rotation.copyFrom(this.rotation);
  31264. }
  31265. camLeft.position.copyFrom(this.position);
  31266. camRight.position.copyFrom(this.position);
  31267. break;
  31268. }
  31269. _super.prototype._updateRigCameras.call(this);
  31270. };
  31271. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31272. if (!this._rigCamTransformMatrix) {
  31273. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31274. }
  31275. var target = this.getTarget();
  31276. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31277. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31278. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31279. };
  31280. TargetCamera.prototype.getClassName = function () {
  31281. return "TargetCamera";
  31282. };
  31283. return TargetCamera;
  31284. }(BABYLON.Camera));
  31285. __decorate([
  31286. BABYLON.serializeAsVector3()
  31287. ], TargetCamera.prototype, "rotation", void 0);
  31288. __decorate([
  31289. BABYLON.serialize()
  31290. ], TargetCamera.prototype, "speed", void 0);
  31291. __decorate([
  31292. BABYLON.serializeAsMeshReference("lockedTargetId")
  31293. ], TargetCamera.prototype, "lockedTarget", void 0);
  31294. BABYLON.TargetCamera = TargetCamera;
  31295. })(BABYLON || (BABYLON = {}));
  31296. //# sourceMappingURL=babylon.targetCamera.js.map
  31297. var BABYLON;
  31298. (function (BABYLON) {
  31299. var ArcRotateCameraKeyboardMoveInput = (function () {
  31300. function ArcRotateCameraKeyboardMoveInput() {
  31301. this._keys = [];
  31302. this.keysUp = [38];
  31303. this.keysDown = [40];
  31304. this.keysLeft = [37];
  31305. this.keysRight = [39];
  31306. }
  31307. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31308. var _this = this;
  31309. element.tabIndex = 1;
  31310. this._onKeyDown = function (evt) {
  31311. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31312. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31313. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31314. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31315. var index = _this._keys.indexOf(evt.keyCode);
  31316. if (index === -1) {
  31317. _this._keys.push(evt.keyCode);
  31318. }
  31319. if (evt.preventDefault) {
  31320. if (!noPreventDefault) {
  31321. evt.preventDefault();
  31322. }
  31323. }
  31324. }
  31325. };
  31326. this._onKeyUp = function (evt) {
  31327. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31328. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31329. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31330. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31331. var index = _this._keys.indexOf(evt.keyCode);
  31332. if (index >= 0) {
  31333. _this._keys.splice(index, 1);
  31334. }
  31335. if (evt.preventDefault) {
  31336. if (!noPreventDefault) {
  31337. evt.preventDefault();
  31338. }
  31339. }
  31340. }
  31341. };
  31342. this._onLostFocus = function () {
  31343. _this._keys = [];
  31344. };
  31345. element.addEventListener("keydown", this._onKeyDown, false);
  31346. element.addEventListener("keyup", this._onKeyUp, false);
  31347. BABYLON.Tools.RegisterTopRootEvents([
  31348. { name: "blur", handler: this._onLostFocus }
  31349. ]);
  31350. };
  31351. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31352. if (element) {
  31353. element.removeEventListener("keydown", this._onKeyDown);
  31354. element.removeEventListener("keyup", this._onKeyUp);
  31355. }
  31356. BABYLON.Tools.UnregisterTopRootEvents([
  31357. { name: "blur", handler: this._onLostFocus }
  31358. ]);
  31359. this._keys = [];
  31360. this._onKeyDown = null;
  31361. this._onKeyUp = null;
  31362. this._onLostFocus = null;
  31363. };
  31364. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31365. if (this._onKeyDown) {
  31366. var camera = this.camera;
  31367. for (var index = 0; index < this._keys.length; index++) {
  31368. var keyCode = this._keys[index];
  31369. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31370. camera.inertialAlphaOffset -= 0.01;
  31371. }
  31372. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31373. camera.inertialBetaOffset -= 0.01;
  31374. }
  31375. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31376. camera.inertialAlphaOffset += 0.01;
  31377. }
  31378. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31379. camera.inertialBetaOffset += 0.01;
  31380. }
  31381. }
  31382. }
  31383. };
  31384. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  31385. return "ArcRotateCameraKeyboardMoveInput";
  31386. };
  31387. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31388. return "keyboard";
  31389. };
  31390. return ArcRotateCameraKeyboardMoveInput;
  31391. }());
  31392. __decorate([
  31393. BABYLON.serialize()
  31394. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31395. __decorate([
  31396. BABYLON.serialize()
  31397. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31398. __decorate([
  31399. BABYLON.serialize()
  31400. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31401. __decorate([
  31402. BABYLON.serialize()
  31403. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31404. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  31405. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  31406. })(BABYLON || (BABYLON = {}));
  31407. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  31408. var BABYLON;
  31409. (function (BABYLON) {
  31410. var ArcRotateCameraMouseWheelInput = (function () {
  31411. function ArcRotateCameraMouseWheelInput() {
  31412. this.wheelPrecision = 3.0;
  31413. }
  31414. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  31415. var _this = this;
  31416. this._wheel = function (p, s) {
  31417. //sanity check - this should be a PointerWheel event.
  31418. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  31419. return;
  31420. var event = p.event;
  31421. var delta = 0;
  31422. if (event.wheelDelta) {
  31423. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  31424. }
  31425. else if (event.detail) {
  31426. delta = -event.detail / _this.wheelPrecision;
  31427. }
  31428. if (delta)
  31429. _this.camera.inertialRadiusOffset += delta;
  31430. if (event.preventDefault) {
  31431. if (!noPreventDefault) {
  31432. event.preventDefault();
  31433. }
  31434. }
  31435. };
  31436. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  31437. };
  31438. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  31439. if (this._observer && element) {
  31440. this.camera.getScene().onPointerObservable.remove(this._observer);
  31441. this._observer = null;
  31442. this._wheel = null;
  31443. }
  31444. };
  31445. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  31446. return "ArcRotateCameraMouseWheelInput";
  31447. };
  31448. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  31449. return "mousewheel";
  31450. };
  31451. return ArcRotateCameraMouseWheelInput;
  31452. }());
  31453. __decorate([
  31454. BABYLON.serialize()
  31455. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  31456. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  31457. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  31458. })(BABYLON || (BABYLON = {}));
  31459. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  31460. var BABYLON;
  31461. (function (BABYLON) {
  31462. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  31463. var ArcRotateCameraPointersInput = (function () {
  31464. function ArcRotateCameraPointersInput() {
  31465. this.buttons = [0, 1, 2];
  31466. this.angularSensibilityX = 1000.0;
  31467. this.angularSensibilityY = 1000.0;
  31468. this.pinchPrecision = 6.0;
  31469. this.panningSensibility = 50.0;
  31470. this._isPanClick = false;
  31471. this.pinchInwards = true;
  31472. }
  31473. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  31474. var _this = this;
  31475. var engine = this.camera.getEngine();
  31476. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  31477. var pointA, pointB;
  31478. var previousPinchDistance = 0;
  31479. this._pointerInput = function (p, s) {
  31480. var evt = p.event;
  31481. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31482. return;
  31483. }
  31484. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31485. try {
  31486. evt.srcElement.setPointerCapture(evt.pointerId);
  31487. }
  31488. catch (e) {
  31489. //Nothing to do with the error. Execution will continue.
  31490. }
  31491. // Manage panning with pan button click
  31492. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  31493. // manage pointers
  31494. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31495. if (pointA === undefined) {
  31496. pointA = cacheSoloPointer;
  31497. }
  31498. else if (pointB === undefined) {
  31499. pointB = cacheSoloPointer;
  31500. }
  31501. if (!noPreventDefault) {
  31502. evt.preventDefault();
  31503. element.focus();
  31504. }
  31505. }
  31506. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31507. try {
  31508. evt.srcElement.releasePointerCapture(evt.pointerId);
  31509. }
  31510. catch (e) {
  31511. //Nothing to do with the error.
  31512. }
  31513. cacheSoloPointer = null;
  31514. previousPinchDistance = 0;
  31515. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  31516. //but emptying completly pointers collection is required to fix a bug on iPhone :
  31517. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  31518. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  31519. pointA = pointB = undefined;
  31520. if (!noPreventDefault) {
  31521. evt.preventDefault();
  31522. }
  31523. }
  31524. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31525. if (!noPreventDefault) {
  31526. evt.preventDefault();
  31527. }
  31528. // One button down
  31529. if (pointA && pointB === undefined) {
  31530. if (_this.panningSensibility !== 0 &&
  31531. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  31532. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  31533. _this.camera
  31534. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  31535. _this.camera
  31536. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  31537. }
  31538. else {
  31539. var offsetX = evt.clientX - cacheSoloPointer.x;
  31540. var offsetY = evt.clientY - cacheSoloPointer.y;
  31541. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31542. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31543. }
  31544. cacheSoloPointer.x = evt.clientX;
  31545. cacheSoloPointer.y = evt.clientY;
  31546. }
  31547. else if (pointA && pointB) {
  31548. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  31549. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  31550. ed.x = evt.clientX;
  31551. ed.y = evt.clientY;
  31552. var direction = _this.pinchInwards ? 1 : -1;
  31553. var distX = pointA.x - pointB.x;
  31554. var distY = pointA.y - pointB.y;
  31555. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  31556. if (previousPinchDistance === 0) {
  31557. previousPinchDistance = pinchSquaredDistance;
  31558. return;
  31559. }
  31560. if (pinchSquaredDistance !== previousPinchDistance) {
  31561. _this.camera
  31562. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  31563. (_this.pinchPrecision *
  31564. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  31565. direction);
  31566. previousPinchDistance = pinchSquaredDistance;
  31567. }
  31568. }
  31569. }
  31570. };
  31571. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31572. this._onContextMenu = function (evt) {
  31573. evt.preventDefault();
  31574. };
  31575. if (!this.camera._useCtrlForPanning) {
  31576. element.addEventListener("contextmenu", this._onContextMenu, false);
  31577. }
  31578. this._onLostFocus = function () {
  31579. //this._keys = [];
  31580. pointA = pointB = undefined;
  31581. previousPinchDistance = 0;
  31582. cacheSoloPointer = null;
  31583. };
  31584. this._onMouseMove = function (evt) {
  31585. if (!engine.isPointerLock) {
  31586. return;
  31587. }
  31588. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31589. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31590. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31591. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31592. if (!noPreventDefault) {
  31593. evt.preventDefault();
  31594. }
  31595. };
  31596. this._onGestureStart = function (e) {
  31597. if (window.MSGesture === undefined) {
  31598. return;
  31599. }
  31600. if (!_this._MSGestureHandler) {
  31601. _this._MSGestureHandler = new MSGesture();
  31602. _this._MSGestureHandler.target = element;
  31603. }
  31604. _this._MSGestureHandler.addPointer(e.pointerId);
  31605. };
  31606. this._onGesture = function (e) {
  31607. _this.camera.radius *= e.scale;
  31608. if (e.preventDefault) {
  31609. if (!noPreventDefault) {
  31610. e.stopPropagation();
  31611. e.preventDefault();
  31612. }
  31613. }
  31614. };
  31615. element.addEventListener("mousemove", this._onMouseMove, false);
  31616. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  31617. element.addEventListener("MSGestureChange", this._onGesture, false);
  31618. BABYLON.Tools.RegisterTopRootEvents([
  31619. { name: "blur", handler: this._onLostFocus }
  31620. ]);
  31621. };
  31622. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  31623. if (element && this._observer) {
  31624. this.camera.getScene().onPointerObservable.remove(this._observer);
  31625. this._observer = null;
  31626. element.removeEventListener("contextmenu", this._onContextMenu);
  31627. element.removeEventListener("mousemove", this._onMouseMove);
  31628. element.removeEventListener("MSPointerDown", this._onGestureStart);
  31629. element.removeEventListener("MSGestureChange", this._onGesture);
  31630. this._isPanClick = false;
  31631. this.pinchInwards = true;
  31632. this._onMouseMove = null;
  31633. this._onGestureStart = null;
  31634. this._onGesture = null;
  31635. this._MSGestureHandler = null;
  31636. this._onLostFocus = null;
  31637. this._onContextMenu = null;
  31638. }
  31639. BABYLON.Tools.UnregisterTopRootEvents([
  31640. { name: "blur", handler: this._onLostFocus }
  31641. ]);
  31642. };
  31643. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  31644. return "ArcRotateCameraPointersInput";
  31645. };
  31646. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  31647. return "pointers";
  31648. };
  31649. return ArcRotateCameraPointersInput;
  31650. }());
  31651. __decorate([
  31652. BABYLON.serialize()
  31653. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  31654. __decorate([
  31655. BABYLON.serialize()
  31656. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  31657. __decorate([
  31658. BABYLON.serialize()
  31659. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  31660. __decorate([
  31661. BABYLON.serialize()
  31662. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  31663. __decorate([
  31664. BABYLON.serialize()
  31665. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  31666. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  31667. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  31668. })(BABYLON || (BABYLON = {}));
  31669. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  31670. /// <reference path="babylon.targetCamera.ts" />
  31671. /// <reference path="..\Tools\babylon.tools.ts" />
  31672. var BABYLON;
  31673. (function (BABYLON) {
  31674. var ArcRotateCamera = (function (_super) {
  31675. __extends(ArcRotateCamera, _super);
  31676. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  31677. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  31678. _this.inertialAlphaOffset = 0;
  31679. _this.inertialBetaOffset = 0;
  31680. _this.inertialRadiusOffset = 0;
  31681. _this.lowerAlphaLimit = null;
  31682. _this.upperAlphaLimit = null;
  31683. _this.lowerBetaLimit = 0.01;
  31684. _this.upperBetaLimit = Math.PI;
  31685. _this.lowerRadiusLimit = null;
  31686. _this.upperRadiusLimit = null;
  31687. _this.inertialPanningX = 0;
  31688. _this.inertialPanningY = 0;
  31689. _this.panningInertia = 0.9;
  31690. //-- end properties for backward compatibility for inputs
  31691. _this.zoomOnFactor = 1;
  31692. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31693. _this.allowUpsideDown = true;
  31694. _this._viewMatrix = new BABYLON.Matrix();
  31695. // Panning
  31696. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31697. _this.checkCollisions = false;
  31698. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31699. _this._previousPosition = BABYLON.Vector3.Zero();
  31700. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31701. _this._newPosition = BABYLON.Vector3.Zero();
  31702. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31703. if (collidedMesh === void 0) { collidedMesh = null; }
  31704. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31705. newPosition.multiplyInPlace(_this._collider.radius);
  31706. }
  31707. if (!collidedMesh) {
  31708. _this._previousPosition.copyFrom(_this.position);
  31709. }
  31710. else {
  31711. _this.setPosition(newPosition);
  31712. if (_this.onCollide) {
  31713. _this.onCollide(collidedMesh);
  31714. }
  31715. }
  31716. // Recompute because of constraints
  31717. var cosa = Math.cos(_this.alpha);
  31718. var sina = Math.sin(_this.alpha);
  31719. var cosb = Math.cos(_this.beta);
  31720. var sinb = Math.sin(_this.beta);
  31721. if (sinb === 0) {
  31722. sinb = 0.0001;
  31723. }
  31724. var target = _this._getTargetPosition();
  31725. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31726. _this.position.copyFrom(_this._newPosition);
  31727. var up = _this.upVector;
  31728. if (_this.allowUpsideDown && _this.beta < 0) {
  31729. up = up.clone();
  31730. up = up.negate();
  31731. }
  31732. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31733. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31734. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31735. _this._collisionTriggered = false;
  31736. };
  31737. _this._target = BABYLON.Vector3.Zero();
  31738. if (target) {
  31739. _this.setTarget(target);
  31740. }
  31741. _this.alpha = alpha;
  31742. _this.beta = beta;
  31743. _this.radius = radius;
  31744. _this.getViewMatrix();
  31745. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31746. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31747. return _this;
  31748. }
  31749. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31750. get: function () {
  31751. return this._target;
  31752. },
  31753. set: function (value) {
  31754. this.setTarget(value);
  31755. },
  31756. enumerable: true,
  31757. configurable: true
  31758. });
  31759. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31760. //-- begin properties for backward compatibility for inputs
  31761. get: function () {
  31762. var pointers = this.inputs.attached["pointers"];
  31763. if (pointers)
  31764. return pointers.angularSensibilityX;
  31765. },
  31766. set: function (value) {
  31767. var pointers = this.inputs.attached["pointers"];
  31768. if (pointers) {
  31769. pointers.angularSensibilityX = value;
  31770. }
  31771. },
  31772. enumerable: true,
  31773. configurable: true
  31774. });
  31775. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31776. get: function () {
  31777. var pointers = this.inputs.attached["pointers"];
  31778. if (pointers)
  31779. return pointers.angularSensibilityY;
  31780. },
  31781. set: function (value) {
  31782. var pointers = this.inputs.attached["pointers"];
  31783. if (pointers) {
  31784. pointers.angularSensibilityY = value;
  31785. }
  31786. },
  31787. enumerable: true,
  31788. configurable: true
  31789. });
  31790. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31791. get: function () {
  31792. var pointers = this.inputs.attached["pointers"];
  31793. if (pointers)
  31794. return pointers.pinchPrecision;
  31795. },
  31796. set: function (value) {
  31797. var pointers = this.inputs.attached["pointers"];
  31798. if (pointers) {
  31799. pointers.pinchPrecision = value;
  31800. }
  31801. },
  31802. enumerable: true,
  31803. configurable: true
  31804. });
  31805. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31806. get: function () {
  31807. var pointers = this.inputs.attached["pointers"];
  31808. if (pointers)
  31809. return pointers.panningSensibility;
  31810. },
  31811. set: function (value) {
  31812. var pointers = this.inputs.attached["pointers"];
  31813. if (pointers) {
  31814. pointers.panningSensibility = value;
  31815. }
  31816. },
  31817. enumerable: true,
  31818. configurable: true
  31819. });
  31820. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31821. get: function () {
  31822. var keyboard = this.inputs.attached["keyboard"];
  31823. if (keyboard)
  31824. return keyboard.keysUp;
  31825. },
  31826. set: function (value) {
  31827. var keyboard = this.inputs.attached["keyboard"];
  31828. if (keyboard)
  31829. keyboard.keysUp = value;
  31830. },
  31831. enumerable: true,
  31832. configurable: true
  31833. });
  31834. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31835. get: function () {
  31836. var keyboard = this.inputs.attached["keyboard"];
  31837. if (keyboard)
  31838. return keyboard.keysDown;
  31839. },
  31840. set: function (value) {
  31841. var keyboard = this.inputs.attached["keyboard"];
  31842. if (keyboard)
  31843. keyboard.keysDown = value;
  31844. },
  31845. enumerable: true,
  31846. configurable: true
  31847. });
  31848. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31849. get: function () {
  31850. var keyboard = this.inputs.attached["keyboard"];
  31851. if (keyboard)
  31852. return keyboard.keysLeft;
  31853. },
  31854. set: function (value) {
  31855. var keyboard = this.inputs.attached["keyboard"];
  31856. if (keyboard)
  31857. keyboard.keysLeft = value;
  31858. },
  31859. enumerable: true,
  31860. configurable: true
  31861. });
  31862. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31863. get: function () {
  31864. var keyboard = this.inputs.attached["keyboard"];
  31865. if (keyboard)
  31866. return keyboard.keysRight;
  31867. },
  31868. set: function (value) {
  31869. var keyboard = this.inputs.attached["keyboard"];
  31870. if (keyboard)
  31871. keyboard.keysRight = value;
  31872. },
  31873. enumerable: true,
  31874. configurable: true
  31875. });
  31876. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31877. get: function () {
  31878. var mousewheel = this.inputs.attached["mousewheel"];
  31879. if (mousewheel)
  31880. return mousewheel.wheelPrecision;
  31881. },
  31882. set: function (value) {
  31883. var mousewheel = this.inputs.attached["mousewheel"];
  31884. if (mousewheel)
  31885. mousewheel.wheelPrecision = value;
  31886. },
  31887. enumerable: true,
  31888. configurable: true
  31889. });
  31890. // Cache
  31891. ArcRotateCamera.prototype._initCache = function () {
  31892. _super.prototype._initCache.call(this);
  31893. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31894. this._cache.alpha = undefined;
  31895. this._cache.beta = undefined;
  31896. this._cache.radius = undefined;
  31897. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  31898. };
  31899. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  31900. if (!ignoreParentClass) {
  31901. _super.prototype._updateCache.call(this);
  31902. }
  31903. this._cache._target.copyFrom(this._getTargetPosition());
  31904. this._cache.alpha = this.alpha;
  31905. this._cache.beta = this.beta;
  31906. this._cache.radius = this.radius;
  31907. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  31908. };
  31909. ArcRotateCamera.prototype._getTargetPosition = function () {
  31910. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  31911. var pos = this._targetHost.getAbsolutePosition();
  31912. if (this._targetBoundingCenter) {
  31913. pos.addToRef(this._targetBoundingCenter, this._target);
  31914. }
  31915. else {
  31916. this._target.copyFrom(pos);
  31917. }
  31918. }
  31919. return this._target;
  31920. };
  31921. // Synchronized
  31922. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  31923. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  31924. return false;
  31925. return this._cache._target.equals(this._target)
  31926. && this._cache.alpha === this.alpha
  31927. && this._cache.beta === this.beta
  31928. && this._cache.radius === this.radius
  31929. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  31930. };
  31931. // Methods
  31932. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  31933. var _this = this;
  31934. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  31935. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  31936. this._useCtrlForPanning = useCtrlForPanning;
  31937. this._panningMouseButton = panningMouseButton;
  31938. this.inputs.attachElement(element, noPreventDefault);
  31939. this._reset = function () {
  31940. _this.inertialAlphaOffset = 0;
  31941. _this.inertialBetaOffset = 0;
  31942. _this.inertialRadiusOffset = 0;
  31943. };
  31944. };
  31945. ArcRotateCamera.prototype.detachControl = function (element) {
  31946. this.inputs.detachElement(element);
  31947. if (this._reset) {
  31948. this._reset();
  31949. }
  31950. };
  31951. ArcRotateCamera.prototype._checkInputs = function () {
  31952. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  31953. if (this._collisionTriggered) {
  31954. return;
  31955. }
  31956. this.inputs.checkInputs();
  31957. // Inertia
  31958. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  31959. if (this.getScene().useRightHandedSystem) {
  31960. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31961. }
  31962. else {
  31963. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31964. }
  31965. this.beta += this.inertialBetaOffset;
  31966. this.radius -= this.inertialRadiusOffset;
  31967. this.inertialAlphaOffset *= this.inertia;
  31968. this.inertialBetaOffset *= this.inertia;
  31969. this.inertialRadiusOffset *= this.inertia;
  31970. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  31971. this.inertialAlphaOffset = 0;
  31972. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  31973. this.inertialBetaOffset = 0;
  31974. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  31975. this.inertialRadiusOffset = 0;
  31976. }
  31977. // Panning inertia
  31978. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  31979. if (!this._localDirection) {
  31980. this._localDirection = BABYLON.Vector3.Zero();
  31981. this._transformedDirection = BABYLON.Vector3.Zero();
  31982. }
  31983. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  31984. this._localDirection.multiplyInPlace(this.panningAxis);
  31985. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  31986. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  31987. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  31988. if (!this.panningAxis.y) {
  31989. this._transformedDirection.y = 0;
  31990. }
  31991. if (!this._targetHost) {
  31992. this._target.addInPlace(this._transformedDirection);
  31993. }
  31994. this.inertialPanningX *= this.panningInertia;
  31995. this.inertialPanningY *= this.panningInertia;
  31996. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  31997. this.inertialPanningX = 0;
  31998. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  31999. this.inertialPanningY = 0;
  32000. }
  32001. // Limits
  32002. this._checkLimits();
  32003. _super.prototype._checkInputs.call(this);
  32004. };
  32005. ArcRotateCamera.prototype._checkLimits = function () {
  32006. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32007. if (this.allowUpsideDown && this.beta > Math.PI) {
  32008. this.beta = this.beta - (2 * Math.PI);
  32009. }
  32010. }
  32011. else {
  32012. if (this.beta < this.lowerBetaLimit) {
  32013. this.beta = this.lowerBetaLimit;
  32014. }
  32015. }
  32016. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32017. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32018. this.beta = this.beta + (2 * Math.PI);
  32019. }
  32020. }
  32021. else {
  32022. if (this.beta > this.upperBetaLimit) {
  32023. this.beta = this.upperBetaLimit;
  32024. }
  32025. }
  32026. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32027. this.alpha = this.lowerAlphaLimit;
  32028. }
  32029. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32030. this.alpha = this.upperAlphaLimit;
  32031. }
  32032. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32033. this.radius = this.lowerRadiusLimit;
  32034. }
  32035. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32036. this.radius = this.upperRadiusLimit;
  32037. }
  32038. };
  32039. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32040. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32041. this.radius = radiusv3.length();
  32042. // Alpha
  32043. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32044. if (radiusv3.z < 0) {
  32045. this.alpha = 2 * Math.PI - this.alpha;
  32046. }
  32047. // Beta
  32048. this.beta = Math.acos(radiusv3.y / this.radius);
  32049. this._checkLimits();
  32050. };
  32051. ArcRotateCamera.prototype.setPosition = function (position) {
  32052. if (this.position.equals(position)) {
  32053. return;
  32054. }
  32055. this.position.copyFrom(position);
  32056. this.rebuildAnglesAndRadius();
  32057. };
  32058. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32059. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32060. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32061. if (target.getBoundingInfo) {
  32062. if (toBoundingCenter) {
  32063. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32064. }
  32065. else {
  32066. this._targetBoundingCenter = null;
  32067. }
  32068. this._targetHost = target;
  32069. this._target = this._getTargetPosition();
  32070. }
  32071. else {
  32072. var newTarget = target;
  32073. var currentTarget = this._getTargetPosition();
  32074. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32075. return;
  32076. }
  32077. this._target = newTarget;
  32078. this._targetBoundingCenter = null;
  32079. }
  32080. this.rebuildAnglesAndRadius();
  32081. };
  32082. ArcRotateCamera.prototype._getViewMatrix = function () {
  32083. // Compute
  32084. var cosa = Math.cos(this.alpha);
  32085. var sina = Math.sin(this.alpha);
  32086. var cosb = Math.cos(this.beta);
  32087. var sinb = Math.sin(this.beta);
  32088. if (sinb === 0) {
  32089. sinb = 0.0001;
  32090. }
  32091. var target = this._getTargetPosition();
  32092. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32093. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32094. if (!this._collider) {
  32095. this._collider = new BABYLON.Collider();
  32096. }
  32097. this._collider.radius = this.collisionRadius;
  32098. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32099. this._collisionTriggered = true;
  32100. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32101. }
  32102. else {
  32103. this.position.copyFrom(this._newPosition);
  32104. var up = this.upVector;
  32105. if (this.allowUpsideDown && sinb < 0) {
  32106. up = up.clone();
  32107. up = up.negate();
  32108. }
  32109. if (this.getScene().useRightHandedSystem) {
  32110. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32111. }
  32112. else {
  32113. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32114. }
  32115. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32116. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32117. }
  32118. this._currentTarget = target;
  32119. return this._viewMatrix;
  32120. };
  32121. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32122. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32123. meshes = meshes || this.getScene().meshes;
  32124. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32125. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32126. this.radius = distance * this.zoomOnFactor;
  32127. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32128. };
  32129. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32130. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32131. var meshesOrMinMaxVector;
  32132. var distance;
  32133. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32134. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32135. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32136. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32137. }
  32138. else {
  32139. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32140. distance = meshesOrMinMaxVectorAndDistance.distance;
  32141. }
  32142. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32143. if (!doNotUpdateMaxZ) {
  32144. this.maxZ = distance * 2;
  32145. }
  32146. };
  32147. /**
  32148. * @override
  32149. * Override Camera.createRigCamera
  32150. */
  32151. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32152. var alphaShift;
  32153. switch (this.cameraRigMode) {
  32154. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32155. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32156. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32157. case BABYLON.Camera.RIG_MODE_VR:
  32158. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32159. break;
  32160. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32161. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32162. break;
  32163. }
  32164. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32165. rigCam._cameraRigParams = {};
  32166. return rigCam;
  32167. };
  32168. /**
  32169. * @override
  32170. * Override Camera._updateRigCameras
  32171. */
  32172. ArcRotateCamera.prototype._updateRigCameras = function () {
  32173. var camLeft = this._rigCameras[0];
  32174. var camRight = this._rigCameras[1];
  32175. camLeft.beta = camRight.beta = this.beta;
  32176. camLeft.radius = camRight.radius = this.radius;
  32177. switch (this.cameraRigMode) {
  32178. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32179. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32181. case BABYLON.Camera.RIG_MODE_VR:
  32182. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32183. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32184. break;
  32185. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32186. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32187. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32188. break;
  32189. }
  32190. _super.prototype._updateRigCameras.call(this);
  32191. };
  32192. ArcRotateCamera.prototype.dispose = function () {
  32193. this.inputs.clear();
  32194. _super.prototype.dispose.call(this);
  32195. };
  32196. ArcRotateCamera.prototype.getClassName = function () {
  32197. return "ArcRotateCamera";
  32198. };
  32199. return ArcRotateCamera;
  32200. }(BABYLON.TargetCamera));
  32201. __decorate([
  32202. BABYLON.serialize()
  32203. ], ArcRotateCamera.prototype, "alpha", void 0);
  32204. __decorate([
  32205. BABYLON.serialize()
  32206. ], ArcRotateCamera.prototype, "beta", void 0);
  32207. __decorate([
  32208. BABYLON.serialize()
  32209. ], ArcRotateCamera.prototype, "radius", void 0);
  32210. __decorate([
  32211. BABYLON.serializeAsVector3("target")
  32212. ], ArcRotateCamera.prototype, "_target", void 0);
  32213. __decorate([
  32214. BABYLON.serialize()
  32215. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32216. __decorate([
  32217. BABYLON.serialize()
  32218. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32219. __decorate([
  32220. BABYLON.serialize()
  32221. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32222. __decorate([
  32223. BABYLON.serialize()
  32224. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32225. __decorate([
  32226. BABYLON.serialize()
  32227. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32228. __decorate([
  32229. BABYLON.serialize()
  32230. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32231. __decorate([
  32232. BABYLON.serialize()
  32233. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32234. __decorate([
  32235. BABYLON.serialize()
  32236. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32237. __decorate([
  32238. BABYLON.serialize()
  32239. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32240. __decorate([
  32241. BABYLON.serialize()
  32242. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32243. __decorate([
  32244. BABYLON.serialize()
  32245. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32246. __decorate([
  32247. BABYLON.serialize()
  32248. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32249. __decorate([
  32250. BABYLON.serialize()
  32251. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32252. __decorate([
  32253. BABYLON.serialize()
  32254. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32255. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32256. })(BABYLON || (BABYLON = {}));
  32257. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32258. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32259. var BABYLON;
  32260. (function (BABYLON) {
  32261. var ArcRotateCameraInputsManager = (function (_super) {
  32262. __extends(ArcRotateCameraInputsManager, _super);
  32263. function ArcRotateCameraInputsManager(camera) {
  32264. return _super.call(this, camera) || this;
  32265. }
  32266. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32267. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32268. return this;
  32269. };
  32270. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  32271. this.add(new BABYLON.ArcRotateCameraPointersInput());
  32272. return this;
  32273. };
  32274. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  32275. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  32276. return this;
  32277. };
  32278. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  32279. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  32280. return this;
  32281. };
  32282. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  32283. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  32284. return this;
  32285. };
  32286. return ArcRotateCameraInputsManager;
  32287. }(BABYLON.CameraInputsManager));
  32288. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  32289. })(BABYLON || (BABYLON = {}));
  32290. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  32291. var BABYLON;
  32292. (function (BABYLON) {
  32293. var CubeTexture = (function (_super) {
  32294. __extends(CubeTexture, _super);
  32295. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  32296. if (onLoad === void 0) { onLoad = null; }
  32297. if (onError === void 0) { onError = null; }
  32298. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32299. var _this = _super.call(this, scene) || this;
  32300. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  32301. _this.name = rootUrl;
  32302. _this.url = rootUrl;
  32303. _this._noMipmap = noMipmap;
  32304. _this.hasAlpha = false;
  32305. _this._format = format;
  32306. if (!rootUrl && !files) {
  32307. return _this;
  32308. }
  32309. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  32310. if (!files) {
  32311. if (!extensions) {
  32312. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  32313. }
  32314. files = [];
  32315. for (var index = 0; index < extensions.length; index++) {
  32316. files.push(rootUrl + extensions[index]);
  32317. }
  32318. _this._extensions = extensions;
  32319. }
  32320. _this._files = files;
  32321. if (!_this._texture) {
  32322. if (!scene.useDelayedTextureLoading) {
  32323. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  32324. }
  32325. else {
  32326. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32327. }
  32328. }
  32329. else if (onLoad) {
  32330. if (_this._texture.isReady) {
  32331. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  32332. }
  32333. else {
  32334. _this._texture.onLoadedCallbacks.push(onLoad);
  32335. }
  32336. }
  32337. _this.isCube = true;
  32338. _this._textureMatrix = BABYLON.Matrix.Identity();
  32339. return _this;
  32340. }
  32341. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  32342. return new CubeTexture("", scene, null, noMipmap, files);
  32343. };
  32344. // Methods
  32345. CubeTexture.prototype.delayLoad = function () {
  32346. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32347. return;
  32348. }
  32349. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32350. this._texture = this._getFromCache(this.url, this._noMipmap);
  32351. if (!this._texture) {
  32352. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  32353. }
  32354. };
  32355. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  32356. return this._textureMatrix;
  32357. };
  32358. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32359. var texture = BABYLON.SerializationHelper.Parse(function () {
  32360. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  32361. }, parsedTexture, scene);
  32362. // Animations
  32363. if (parsedTexture.animations) {
  32364. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32365. var parsedAnimation = parsedTexture.animations[animationIndex];
  32366. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32367. }
  32368. }
  32369. return texture;
  32370. };
  32371. CubeTexture.prototype.clone = function () {
  32372. var _this = this;
  32373. return BABYLON.SerializationHelper.Clone(function () {
  32374. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  32375. }, this);
  32376. };
  32377. return CubeTexture;
  32378. }(BABYLON.BaseTexture));
  32379. BABYLON.CubeTexture = CubeTexture;
  32380. })(BABYLON || (BABYLON = {}));
  32381. //# sourceMappingURL=babylon.cubeTexture.js.map
  32382. var BABYLON;
  32383. (function (BABYLON) {
  32384. var RenderTargetTexture = (function (_super) {
  32385. __extends(RenderTargetTexture, _super);
  32386. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  32387. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  32388. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32389. if (isCube === void 0) { isCube = false; }
  32390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32391. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  32392. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  32393. if (isMulti === void 0) { isMulti = false; }
  32394. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  32395. _this.isCube = isCube;
  32396. /**
  32397. * Use this list to define the list of mesh you want to render.
  32398. */
  32399. _this.renderList = new Array();
  32400. _this.renderParticles = true;
  32401. _this.renderSprites = false;
  32402. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  32403. // Events
  32404. /**
  32405. * An event triggered when the texture is unbind.
  32406. * @type {BABYLON.Observable}
  32407. */
  32408. _this.onAfterUnbindObservable = new BABYLON.Observable();
  32409. /**
  32410. * An event triggered before rendering the texture
  32411. * @type {BABYLON.Observable}
  32412. */
  32413. _this.onBeforeRenderObservable = new BABYLON.Observable();
  32414. /**
  32415. * An event triggered after rendering the texture
  32416. * @type {BABYLON.Observable}
  32417. */
  32418. _this.onAfterRenderObservable = new BABYLON.Observable();
  32419. /**
  32420. * An event triggered after the texture clear
  32421. * @type {BABYLON.Observable}
  32422. */
  32423. _this.onClearObservable = new BABYLON.Observable();
  32424. _this._currentRefreshId = -1;
  32425. _this._refreshRate = 1;
  32426. _this._samples = 1;
  32427. _this.name = name;
  32428. _this.isRenderTarget = true;
  32429. _this._size = size;
  32430. _this._generateMipMaps = generateMipMaps;
  32431. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  32432. // Rendering groups
  32433. _this._renderingManager = new BABYLON.RenderingManager(scene);
  32434. if (isMulti) {
  32435. return _this;
  32436. }
  32437. _this._renderTargetOptions = {
  32438. generateMipMaps: generateMipMaps,
  32439. type: type,
  32440. samplingMode: samplingMode,
  32441. generateDepthBuffer: generateDepthBuffer,
  32442. generateStencilBuffer: generateStencilBuffer
  32443. };
  32444. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32445. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32446. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32447. }
  32448. if (isCube) {
  32449. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  32450. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  32451. _this._textureMatrix = BABYLON.Matrix.Identity();
  32452. }
  32453. else {
  32454. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  32455. }
  32456. return _this;
  32457. }
  32458. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  32459. get: function () {
  32460. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  32461. },
  32462. enumerable: true,
  32463. configurable: true
  32464. });
  32465. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  32466. get: function () {
  32467. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  32468. },
  32469. enumerable: true,
  32470. configurable: true
  32471. });
  32472. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  32473. get: function () {
  32474. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  32475. },
  32476. enumerable: true,
  32477. configurable: true
  32478. });
  32479. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  32480. set: function (callback) {
  32481. if (this._onAfterUnbindObserver) {
  32482. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  32483. }
  32484. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  32485. },
  32486. enumerable: true,
  32487. configurable: true
  32488. });
  32489. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  32490. set: function (callback) {
  32491. if (this._onBeforeRenderObserver) {
  32492. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32493. }
  32494. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32495. },
  32496. enumerable: true,
  32497. configurable: true
  32498. });
  32499. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  32500. set: function (callback) {
  32501. if (this._onAfterRenderObserver) {
  32502. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32503. }
  32504. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32505. },
  32506. enumerable: true,
  32507. configurable: true
  32508. });
  32509. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  32510. set: function (callback) {
  32511. if (this._onClearObserver) {
  32512. this.onClearObservable.remove(this._onClearObserver);
  32513. }
  32514. this._onClearObserver = this.onClearObservable.add(callback);
  32515. },
  32516. enumerable: true,
  32517. configurable: true
  32518. });
  32519. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  32520. get: function () {
  32521. return this._renderTargetOptions;
  32522. },
  32523. enumerable: true,
  32524. configurable: true
  32525. });
  32526. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  32527. get: function () {
  32528. return this._samples;
  32529. },
  32530. set: function (value) {
  32531. if (this._samples === value) {
  32532. return;
  32533. }
  32534. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  32535. },
  32536. enumerable: true,
  32537. configurable: true
  32538. });
  32539. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  32540. this._currentRefreshId = -1;
  32541. };
  32542. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  32543. get: function () {
  32544. return this._refreshRate;
  32545. },
  32546. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  32547. set: function (value) {
  32548. this._refreshRate = value;
  32549. this.resetRefreshCounter();
  32550. },
  32551. enumerable: true,
  32552. configurable: true
  32553. });
  32554. RenderTargetTexture.prototype._shouldRender = function () {
  32555. if (this._currentRefreshId === -1) {
  32556. this._currentRefreshId = 1;
  32557. return true;
  32558. }
  32559. if (this.refreshRate === this._currentRefreshId) {
  32560. this._currentRefreshId = 1;
  32561. return true;
  32562. }
  32563. this._currentRefreshId++;
  32564. return false;
  32565. };
  32566. RenderTargetTexture.prototype.isReady = function () {
  32567. if (!this.getScene().renderTargetsEnabled) {
  32568. return false;
  32569. }
  32570. return _super.prototype.isReady.call(this);
  32571. };
  32572. RenderTargetTexture.prototype.getRenderSize = function () {
  32573. return this._size;
  32574. };
  32575. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  32576. get: function () {
  32577. return true;
  32578. },
  32579. enumerable: true,
  32580. configurable: true
  32581. });
  32582. RenderTargetTexture.prototype.scale = function (ratio) {
  32583. var newSize = this._size * ratio;
  32584. this.resize(newSize);
  32585. };
  32586. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  32587. if (this.isCube) {
  32588. return this._textureMatrix;
  32589. }
  32590. return _super.prototype.getReflectionTextureMatrix.call(this);
  32591. };
  32592. RenderTargetTexture.prototype.resize = function (size) {
  32593. this.releaseInternalTexture();
  32594. if (this.isCube) {
  32595. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  32596. }
  32597. else {
  32598. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  32599. }
  32600. };
  32601. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  32602. var scene = this.getScene();
  32603. var engine = scene.getEngine();
  32604. if (this.useCameraPostProcesses !== undefined) {
  32605. useCameraPostProcess = this.useCameraPostProcesses;
  32606. }
  32607. if (this._waitingRenderList) {
  32608. this.renderList = [];
  32609. for (var index = 0; index < this._waitingRenderList.length; index++) {
  32610. var id = this._waitingRenderList[index];
  32611. this.renderList.push(scene.getMeshByID(id));
  32612. }
  32613. delete this._waitingRenderList;
  32614. }
  32615. // Is predicate defined?
  32616. if (this.renderListPredicate) {
  32617. this.renderList.splice(0); // Clear previous renderList
  32618. var sceneMeshes = this.getScene().meshes;
  32619. for (var index = 0; index < sceneMeshes.length; index++) {
  32620. var mesh = sceneMeshes[index];
  32621. if (this.renderListPredicate(mesh)) {
  32622. this.renderList.push(mesh);
  32623. }
  32624. }
  32625. }
  32626. if (this.renderList && this.renderList.length === 0) {
  32627. return;
  32628. }
  32629. // Set custom projection.
  32630. // Needs to be before binding to prevent changing the aspect ratio.
  32631. if (this.activeCamera) {
  32632. engine.setViewport(this.activeCamera.viewport);
  32633. if (this.activeCamera !== scene.activeCamera) {
  32634. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  32635. }
  32636. }
  32637. else {
  32638. engine.setViewport(scene.activeCamera.viewport);
  32639. }
  32640. // Prepare renderingManager
  32641. this._renderingManager.reset();
  32642. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  32643. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  32644. var sceneRenderId = scene.getRenderId();
  32645. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  32646. var mesh = currentRenderList[meshIndex];
  32647. if (mesh) {
  32648. if (!mesh.isReady()) {
  32649. // Reset _currentRefreshId
  32650. this.resetRefreshCounter();
  32651. continue;
  32652. }
  32653. mesh._preActivateForIntermediateRendering(sceneRenderId);
  32654. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  32655. mesh._activate(sceneRenderId);
  32656. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32657. var subMesh = mesh.subMeshes[subIndex];
  32658. scene._activeIndices.addCount(subMesh.indexCount, false);
  32659. this._renderingManager.dispatch(subMesh);
  32660. }
  32661. }
  32662. }
  32663. }
  32664. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  32665. var particleSystem = scene.particleSystems[particleIndex];
  32666. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  32667. continue;
  32668. }
  32669. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  32670. this._renderingManager.dispatchParticles(particleSystem);
  32671. }
  32672. }
  32673. if (this.isCube) {
  32674. for (var face = 0; face < 6; face++) {
  32675. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32676. scene.incrementRenderId();
  32677. scene.resetCachedMaterial();
  32678. }
  32679. }
  32680. else {
  32681. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32682. }
  32683. this.onAfterUnbindObservable.notifyObservers(this);
  32684. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  32685. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  32686. }
  32687. engine.setViewport(scene.activeCamera.viewport);
  32688. scene.resetCachedMaterial();
  32689. };
  32690. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  32691. var _this = this;
  32692. var scene = this.getScene();
  32693. var engine = scene.getEngine();
  32694. // Bind
  32695. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  32696. if (this.isCube) {
  32697. engine.bindFramebuffer(this._texture, faceIndex);
  32698. }
  32699. else {
  32700. engine.bindFramebuffer(this._texture);
  32701. }
  32702. }
  32703. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  32704. // Clear
  32705. if (this.onClearObservable.hasObservers()) {
  32706. this.onClearObservable.notifyObservers(engine);
  32707. }
  32708. else {
  32709. engine.clear(scene.clearColor, true, true, true);
  32710. }
  32711. if (!this._doNotChangeAspectRatio) {
  32712. scene.updateTransformMatrix(true);
  32713. }
  32714. // Render
  32715. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  32716. if (useCameraPostProcess) {
  32717. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  32718. }
  32719. if (!this._doNotChangeAspectRatio) {
  32720. scene.updateTransformMatrix(true);
  32721. }
  32722. // Dump ?
  32723. if (dumpForDebug) {
  32724. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  32725. }
  32726. // Unbind
  32727. if (!this.isCube || faceIndex === 5) {
  32728. if (this.isCube) {
  32729. if (faceIndex === 5) {
  32730. engine.generateMipMapsForCubemap(this._texture);
  32731. }
  32732. }
  32733. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  32734. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  32735. });
  32736. }
  32737. else {
  32738. this.onAfterRenderObservable.notifyObservers(faceIndex);
  32739. }
  32740. };
  32741. /**
  32742. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  32743. * This allowed control for front to back rendering or reversly depending of the special needs.
  32744. *
  32745. * @param renderingGroupId The rendering group id corresponding to its index
  32746. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  32747. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  32748. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  32749. */
  32750. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  32751. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  32752. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  32753. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  32754. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  32755. };
  32756. /**
  32757. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  32758. *
  32759. * @param renderingGroupId The rendering group id corresponding to its index
  32760. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  32761. */
  32762. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  32763. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  32764. };
  32765. RenderTargetTexture.prototype.clone = function () {
  32766. var textureSize = this.getSize();
  32767. 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);
  32768. // Base texture
  32769. newTexture.hasAlpha = this.hasAlpha;
  32770. newTexture.level = this.level;
  32771. // RenderTarget Texture
  32772. newTexture.coordinatesMode = this.coordinatesMode;
  32773. newTexture.renderList = this.renderList.slice(0);
  32774. return newTexture;
  32775. };
  32776. RenderTargetTexture.prototype.serialize = function () {
  32777. if (!this.name) {
  32778. return null;
  32779. }
  32780. var serializationObject = _super.prototype.serialize.call(this);
  32781. serializationObject.renderTargetSize = this.getRenderSize();
  32782. serializationObject.renderList = [];
  32783. for (var index = 0; index < this.renderList.length; index++) {
  32784. serializationObject.renderList.push(this.renderList[index].id);
  32785. }
  32786. return serializationObject;
  32787. };
  32788. RenderTargetTexture.prototype.dispose = function () {
  32789. _super.prototype.dispose.call(this);
  32790. };
  32791. return RenderTargetTexture;
  32792. }(BABYLON.Texture));
  32793. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  32794. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  32795. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  32796. BABYLON.RenderTargetTexture = RenderTargetTexture;
  32797. })(BABYLON || (BABYLON = {}));
  32798. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  32799. var BABYLON;
  32800. (function (BABYLON) {
  32801. ;
  32802. var MultiRenderTarget = (function (_super) {
  32803. __extends(MultiRenderTarget, _super);
  32804. function MultiRenderTarget(name, size, count, scene, options) {
  32805. var _this = this;
  32806. options = options || {};
  32807. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  32808. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  32809. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  32810. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  32811. if (!_this.isSupported) {
  32812. _this.dispose();
  32813. return;
  32814. }
  32815. var types = [];
  32816. var samplingModes = [];
  32817. for (var i = 0; i < count; i++) {
  32818. if (options.types && options.types[i]) {
  32819. types.push(options.types[i]);
  32820. }
  32821. else {
  32822. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  32823. }
  32824. if (options.samplingModes && options.samplingModes[i]) {
  32825. samplingModes.push(options.samplingModes[i]);
  32826. }
  32827. else {
  32828. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32829. }
  32830. }
  32831. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  32832. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  32833. _this._count = count;
  32834. _this._size = size;
  32835. _this._multiRenderTargetOptions = {
  32836. samplingModes: samplingModes,
  32837. generateMipMaps: generateMipMaps,
  32838. generateDepthBuffer: generateDepthBuffer,
  32839. generateStencilBuffer: generateStencilBuffer,
  32840. generateDepthTexture: generateDepthTexture,
  32841. types: types,
  32842. textureCount: count
  32843. };
  32844. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  32845. _this._createInternalTextures();
  32846. return _this;
  32847. }
  32848. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  32849. get: function () {
  32850. var engine = this.getScene().getEngine();
  32851. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  32852. },
  32853. enumerable: true,
  32854. configurable: true
  32855. });
  32856. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  32857. get: function () {
  32858. return this._textures;
  32859. },
  32860. enumerable: true,
  32861. configurable: true
  32862. });
  32863. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  32864. get: function () {
  32865. return this._textures[this._textures.length - 1];
  32866. },
  32867. enumerable: true,
  32868. configurable: true
  32869. });
  32870. MultiRenderTarget.prototype._createInternalTextures = function () {
  32871. this._textures = [];
  32872. for (var i = 0; i < this._webGLTextures.length; i++) {
  32873. var texture = new BABYLON.Texture(null, this.getScene());
  32874. texture._texture = this._webGLTextures[i];
  32875. this._textures.push(texture);
  32876. }
  32877. // Keeps references to frame buffer and stencil/depth buffer
  32878. this._texture = this._webGLTextures[0];
  32879. };
  32880. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  32881. get: function () {
  32882. return this._samples;
  32883. },
  32884. set: function (value) {
  32885. if (this._samples === value) {
  32886. return;
  32887. }
  32888. for (var i = 0; i < this._webGLTextures.length; i++) {
  32889. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  32890. }
  32891. },
  32892. enumerable: true,
  32893. configurable: true
  32894. });
  32895. MultiRenderTarget.prototype.resize = function (size) {
  32896. this.releaseInternalTextures();
  32897. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  32898. this._createInternalTextures();
  32899. };
  32900. MultiRenderTarget.prototype.dispose = function () {
  32901. this.releaseInternalTextures();
  32902. _super.prototype.dispose.call(this);
  32903. };
  32904. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  32905. if (!this._webGLTextures) {
  32906. return;
  32907. }
  32908. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  32909. if (this._webGLTextures[i] !== undefined) {
  32910. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  32911. this._webGLTextures.splice(i, 1);
  32912. }
  32913. }
  32914. };
  32915. return MultiRenderTarget;
  32916. }(BABYLON.RenderTargetTexture));
  32917. BABYLON.MultiRenderTarget = MultiRenderTarget;
  32918. })(BABYLON || (BABYLON = {}));
  32919. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  32920. /// <reference path="babylon.renderTargetTexture.ts" />
  32921. var BABYLON;
  32922. (function (BABYLON) {
  32923. var MirrorTexture = (function (_super) {
  32924. __extends(MirrorTexture, _super);
  32925. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  32926. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32927. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32928. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  32929. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  32930. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  32931. _this._transformMatrix = BABYLON.Matrix.Zero();
  32932. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  32933. _this.onBeforeRenderObservable.add(function () {
  32934. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  32935. _this._savedViewMatrix = scene.getViewMatrix();
  32936. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  32937. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  32938. scene.clipPlane = _this.mirrorPlane;
  32939. scene.getEngine().cullBackFaces = false;
  32940. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  32941. });
  32942. _this.onAfterRenderObservable.add(function () {
  32943. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  32944. scene.getEngine().cullBackFaces = true;
  32945. scene._mirroredCameraPosition = null;
  32946. delete scene.clipPlane;
  32947. });
  32948. return _this;
  32949. }
  32950. MirrorTexture.prototype.clone = function () {
  32951. var textureSize = this.getSize();
  32952. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  32953. // Base texture
  32954. newTexture.hasAlpha = this.hasAlpha;
  32955. newTexture.level = this.level;
  32956. // Mirror Texture
  32957. newTexture.mirrorPlane = this.mirrorPlane.clone();
  32958. newTexture.renderList = this.renderList.slice(0);
  32959. return newTexture;
  32960. };
  32961. MirrorTexture.prototype.serialize = function () {
  32962. if (!this.name) {
  32963. return null;
  32964. }
  32965. var serializationObject = _super.prototype.serialize.call(this);
  32966. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  32967. return serializationObject;
  32968. };
  32969. return MirrorTexture;
  32970. }(BABYLON.RenderTargetTexture));
  32971. BABYLON.MirrorTexture = MirrorTexture;
  32972. })(BABYLON || (BABYLON = {}));
  32973. //# sourceMappingURL=babylon.mirrorTexture.js.map
  32974. /// <reference path="babylon.renderTargetTexture.ts" />
  32975. var BABYLON;
  32976. (function (BABYLON) {
  32977. /**
  32978. * Creates a refraction texture used by refraction channel of the standard material.
  32979. * @param name the texture name
  32980. * @param size size of the underlying texture
  32981. * @param scene root scene
  32982. */
  32983. var RefractionTexture = (function (_super) {
  32984. __extends(RefractionTexture, _super);
  32985. function RefractionTexture(name, size, scene, generateMipMaps) {
  32986. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  32987. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  32988. _this.depth = 2.0;
  32989. _this.onBeforeRenderObservable.add(function () {
  32990. scene.clipPlane = _this.refractionPlane;
  32991. });
  32992. _this.onAfterRenderObservable.add(function () {
  32993. delete scene.clipPlane;
  32994. });
  32995. return _this;
  32996. }
  32997. RefractionTexture.prototype.clone = function () {
  32998. var textureSize = this.getSize();
  32999. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33000. // Base texture
  33001. newTexture.hasAlpha = this.hasAlpha;
  33002. newTexture.level = this.level;
  33003. // Refraction Texture
  33004. newTexture.refractionPlane = this.refractionPlane.clone();
  33005. newTexture.renderList = this.renderList.slice(0);
  33006. newTexture.depth = this.depth;
  33007. return newTexture;
  33008. };
  33009. RefractionTexture.prototype.serialize = function () {
  33010. if (!this.name) {
  33011. return null;
  33012. }
  33013. var serializationObject = _super.prototype.serialize.call(this);
  33014. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33015. serializationObject.depth = this.depth;
  33016. return serializationObject;
  33017. };
  33018. return RefractionTexture;
  33019. }(BABYLON.RenderTargetTexture));
  33020. BABYLON.RefractionTexture = RefractionTexture;
  33021. })(BABYLON || (BABYLON = {}));
  33022. //# sourceMappingURL=babylon.refractionTexture.js.map
  33023. /// <reference path="babylon.texture.ts" />
  33024. var BABYLON;
  33025. (function (BABYLON) {
  33026. var DynamicTexture = (function (_super) {
  33027. __extends(DynamicTexture, _super);
  33028. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33030. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33031. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33032. _this.name = name;
  33033. var engine = _this.getScene().getEngine();
  33034. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33035. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33036. _this._generateMipMaps = generateMipMaps;
  33037. if (options.getContext) {
  33038. _this._canvas = options;
  33039. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33040. }
  33041. else {
  33042. _this._canvas = document.createElement("canvas");
  33043. if (options.width) {
  33044. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33045. }
  33046. else {
  33047. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33048. }
  33049. }
  33050. var textureSize = _this.getSize();
  33051. _this._canvas.width = textureSize.width;
  33052. _this._canvas.height = textureSize.height;
  33053. _this._context = _this._canvas.getContext("2d");
  33054. return _this;
  33055. }
  33056. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33057. get: function () {
  33058. return true;
  33059. },
  33060. enumerable: true,
  33061. configurable: true
  33062. });
  33063. DynamicTexture.prototype._recreate = function (textureSize) {
  33064. this._canvas.width = textureSize.width;
  33065. this._canvas.height = textureSize.height;
  33066. this.releaseInternalTexture();
  33067. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33068. };
  33069. DynamicTexture.prototype.scale = function (ratio) {
  33070. var textureSize = this.getSize();
  33071. textureSize.width *= ratio;
  33072. textureSize.height *= ratio;
  33073. this._recreate(textureSize);
  33074. };
  33075. DynamicTexture.prototype.scaleTo = function (width, height) {
  33076. var textureSize = this.getSize();
  33077. textureSize.width = width;
  33078. textureSize.height = height;
  33079. this._recreate(textureSize);
  33080. };
  33081. DynamicTexture.prototype.getContext = function () {
  33082. return this._context;
  33083. };
  33084. DynamicTexture.prototype.clear = function () {
  33085. var size = this.getSize();
  33086. this._context.fillRect(0, 0, size.width, size.height);
  33087. };
  33088. DynamicTexture.prototype.update = function (invertY) {
  33089. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  33090. };
  33091. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  33092. if (update === void 0) { update = true; }
  33093. var size = this.getSize();
  33094. if (clearColor) {
  33095. this._context.fillStyle = clearColor;
  33096. this._context.fillRect(0, 0, size.width, size.height);
  33097. }
  33098. this._context.font = font;
  33099. if (x === null || x === undefined) {
  33100. var textSize = this._context.measureText(text);
  33101. x = (size.width - textSize.width) / 2;
  33102. }
  33103. if (y === null || y === undefined) {
  33104. var fontSize = parseInt((font.replace(/\D/g, '')));
  33105. ;
  33106. y = (size.height / 2) + (fontSize / 3.65);
  33107. }
  33108. this._context.fillStyle = color;
  33109. this._context.fillText(text, x, y);
  33110. if (update) {
  33111. this.update(invertY);
  33112. }
  33113. };
  33114. DynamicTexture.prototype.clone = function () {
  33115. var textureSize = this.getSize();
  33116. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  33117. // Base texture
  33118. newTexture.hasAlpha = this.hasAlpha;
  33119. newTexture.level = this.level;
  33120. // Dynamic Texture
  33121. newTexture.wrapU = this.wrapU;
  33122. newTexture.wrapV = this.wrapV;
  33123. return newTexture;
  33124. };
  33125. return DynamicTexture;
  33126. }(BABYLON.Texture));
  33127. BABYLON.DynamicTexture = DynamicTexture;
  33128. })(BABYLON || (BABYLON = {}));
  33129. //# sourceMappingURL=babylon.dynamicTexture.js.map
  33130. var BABYLON;
  33131. (function (BABYLON) {
  33132. var VideoTexture = (function (_super) {
  33133. __extends(VideoTexture, _super);
  33134. /**
  33135. * Creates a video texture.
  33136. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  33137. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  33138. * @param {BABYLON.Scene} scene is obviously the current scene.
  33139. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  33140. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  33141. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  33142. */
  33143. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  33144. if (generateMipMaps === void 0) { generateMipMaps = false; }
  33145. if (invertY === void 0) { invertY = false; }
  33146. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33147. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33148. _this._autoLaunch = true;
  33149. var urls;
  33150. _this.name = name;
  33151. if (urlsOrVideo instanceof HTMLVideoElement) {
  33152. _this.video = urlsOrVideo;
  33153. }
  33154. else {
  33155. urls = urlsOrVideo;
  33156. _this.video = document.createElement("video");
  33157. _this.video.autoplay = false;
  33158. _this.video.loop = true;
  33159. }
  33160. _this._generateMipMaps = generateMipMaps;
  33161. _this._samplingMode = samplingMode;
  33162. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  33163. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33164. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33165. }
  33166. else {
  33167. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33168. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33169. _this._generateMipMaps = false;
  33170. }
  33171. if (urls) {
  33172. _this.video.addEventListener("canplay", function () {
  33173. _this._createTexture();
  33174. });
  33175. urls.forEach(function (url) {
  33176. var source = document.createElement("source");
  33177. source.src = url;
  33178. _this.video.appendChild(source);
  33179. });
  33180. }
  33181. else {
  33182. _this._createTexture();
  33183. }
  33184. _this._lastUpdate = BABYLON.Tools.Now;
  33185. return _this;
  33186. }
  33187. VideoTexture.prototype.__setTextureReady = function () {
  33188. this._texture.isReady = true;
  33189. };
  33190. VideoTexture.prototype._createTexture = function () {
  33191. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  33192. if (this._autoLaunch) {
  33193. this._autoLaunch = false;
  33194. this.video.play();
  33195. }
  33196. this._setTextureReady = this.__setTextureReady.bind(this);
  33197. this.video.addEventListener("playing", this._setTextureReady);
  33198. };
  33199. VideoTexture.prototype.update = function () {
  33200. var now = BABYLON.Tools.Now;
  33201. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  33202. return false;
  33203. }
  33204. this._lastUpdate = now;
  33205. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  33206. return true;
  33207. };
  33208. VideoTexture.prototype.dispose = function () {
  33209. _super.prototype.dispose.call(this);
  33210. this.video.removeEventListener("playing", this._setTextureReady);
  33211. };
  33212. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  33213. var video = document.createElement("video");
  33214. var constraintsDeviceId;
  33215. if (constraints && constraints.deviceId) {
  33216. constraintsDeviceId = {
  33217. exact: constraints.deviceId
  33218. };
  33219. }
  33220. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  33221. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  33222. if (navigator.getUserMedia) {
  33223. navigator.getUserMedia({
  33224. video: {
  33225. deviceId: constraintsDeviceId,
  33226. width: {
  33227. min: (constraints && constraints.minWidth) || 256,
  33228. max: (constraints && constraints.maxWidth) || 640
  33229. },
  33230. height: {
  33231. min: (constraints && constraints.minHeight) || 256,
  33232. max: (constraints && constraints.maxHeight) || 480
  33233. }
  33234. }
  33235. }, function (stream) {
  33236. if (video.mozSrcObject !== undefined) {
  33237. video.mozSrcObject = stream;
  33238. }
  33239. else {
  33240. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  33241. }
  33242. video.play();
  33243. if (onReady) {
  33244. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  33245. }
  33246. }, function (e) {
  33247. BABYLON.Tools.Error(e.name);
  33248. });
  33249. }
  33250. };
  33251. return VideoTexture;
  33252. }(BABYLON.Texture));
  33253. BABYLON.VideoTexture = VideoTexture;
  33254. })(BABYLON || (BABYLON = {}));
  33255. //# sourceMappingURL=babylon.videoTexture.js.map
  33256. var BABYLON;
  33257. (function (BABYLON) {
  33258. var RawTexture = (function (_super) {
  33259. __extends(RawTexture, _super);
  33260. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33261. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33262. if (invertY === void 0) { invertY = false; }
  33263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33264. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33265. _this.format = format;
  33266. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33267. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33268. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33269. return _this;
  33270. }
  33271. RawTexture.prototype.update = function (data) {
  33272. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33273. };
  33274. // Statics
  33275. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33276. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33277. if (invertY === void 0) { invertY = false; }
  33278. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33279. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33280. };
  33281. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33282. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33283. if (invertY === void 0) { invertY = false; }
  33284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33285. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33286. };
  33287. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33288. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33289. if (invertY === void 0) { invertY = false; }
  33290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33291. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33292. };
  33293. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33294. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33295. if (invertY === void 0) { invertY = false; }
  33296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33297. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33298. };
  33299. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33300. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33301. if (invertY === void 0) { invertY = false; }
  33302. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33303. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33304. };
  33305. return RawTexture;
  33306. }(BABYLON.Texture));
  33307. BABYLON.RawTexture = RawTexture;
  33308. })(BABYLON || (BABYLON = {}));
  33309. //# sourceMappingURL=babylon.rawTexture.js.map
  33310. var BABYLON;
  33311. (function (BABYLON) {
  33312. var Internals;
  33313. (function (Internals) {
  33314. /*
  33315. * Based on jsTGALoader - Javascript loader for TGA file
  33316. * By Vincent Thibault
  33317. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  33318. */
  33319. var TGATools = (function () {
  33320. function TGATools() {
  33321. }
  33322. TGATools.GetTGAHeader = function (data) {
  33323. var offset = 0;
  33324. var header = {
  33325. id_length: data[offset++],
  33326. colormap_type: data[offset++],
  33327. image_type: data[offset++],
  33328. colormap_index: data[offset++] | data[offset++] << 8,
  33329. colormap_length: data[offset++] | data[offset++] << 8,
  33330. colormap_size: data[offset++],
  33331. origin: [
  33332. data[offset++] | data[offset++] << 8,
  33333. data[offset++] | data[offset++] << 8
  33334. ],
  33335. width: data[offset++] | data[offset++] << 8,
  33336. height: data[offset++] | data[offset++] << 8,
  33337. pixel_size: data[offset++],
  33338. flags: data[offset++]
  33339. };
  33340. return header;
  33341. };
  33342. TGATools.UploadContent = function (gl, data) {
  33343. // Not enough data to contain header ?
  33344. if (data.length < 19) {
  33345. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  33346. return;
  33347. }
  33348. // Read Header
  33349. var offset = 18;
  33350. var header = TGATools.GetTGAHeader(data);
  33351. // Assume it's a valid Targa file.
  33352. if (header.id_length + offset > data.length) {
  33353. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  33354. return;
  33355. }
  33356. // Skip not needed data
  33357. offset += header.id_length;
  33358. var use_rle = false;
  33359. var use_pal = false;
  33360. var use_rgb = false;
  33361. var use_grey = false;
  33362. // Get some informations.
  33363. switch (header.image_type) {
  33364. case TGATools._TYPE_RLE_INDEXED:
  33365. use_rle = true;
  33366. case TGATools._TYPE_INDEXED:
  33367. use_pal = true;
  33368. break;
  33369. case TGATools._TYPE_RLE_RGB:
  33370. use_rle = true;
  33371. case TGATools._TYPE_RGB:
  33372. use_rgb = true;
  33373. break;
  33374. case TGATools._TYPE_RLE_GREY:
  33375. use_rle = true;
  33376. case TGATools._TYPE_GREY:
  33377. use_grey = true;
  33378. break;
  33379. }
  33380. var pixel_data;
  33381. var numAlphaBits = header.flags & 0xf;
  33382. var pixel_size = header.pixel_size >> 3;
  33383. var pixel_total = header.width * header.height * pixel_size;
  33384. // Read palettes
  33385. var palettes;
  33386. if (use_pal) {
  33387. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  33388. }
  33389. // Read LRE
  33390. if (use_rle) {
  33391. pixel_data = new Uint8Array(pixel_total);
  33392. var c, count, i;
  33393. var localOffset = 0;
  33394. var pixels = new Uint8Array(pixel_size);
  33395. while (offset < pixel_total && localOffset < pixel_total) {
  33396. c = data[offset++];
  33397. count = (c & 0x7f) + 1;
  33398. // RLE pixels
  33399. if (c & 0x80) {
  33400. // Bind pixel tmp array
  33401. for (i = 0; i < pixel_size; ++i) {
  33402. pixels[i] = data[offset++];
  33403. }
  33404. // Copy pixel array
  33405. for (i = 0; i < count; ++i) {
  33406. pixel_data.set(pixels, localOffset + i * pixel_size);
  33407. }
  33408. localOffset += pixel_size * count;
  33409. }
  33410. else {
  33411. count *= pixel_size;
  33412. for (i = 0; i < count; ++i) {
  33413. pixel_data[localOffset + i] = data[offset++];
  33414. }
  33415. localOffset += count;
  33416. }
  33417. }
  33418. }
  33419. else {
  33420. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  33421. }
  33422. // Load to texture
  33423. var x_start, y_start, x_step, y_step, y_end, x_end;
  33424. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  33425. default:
  33426. case TGATools._ORIGIN_UL:
  33427. x_start = 0;
  33428. x_step = 1;
  33429. x_end = header.width;
  33430. y_start = 0;
  33431. y_step = 1;
  33432. y_end = header.height;
  33433. break;
  33434. case TGATools._ORIGIN_BL:
  33435. x_start = 0;
  33436. x_step = 1;
  33437. x_end = header.width;
  33438. y_start = header.height - 1;
  33439. y_step = -1;
  33440. y_end = -1;
  33441. break;
  33442. case TGATools._ORIGIN_UR:
  33443. x_start = header.width - 1;
  33444. x_step = -1;
  33445. x_end = -1;
  33446. y_start = 0;
  33447. y_step = 1;
  33448. y_end = header.height;
  33449. break;
  33450. case TGATools._ORIGIN_BR:
  33451. x_start = header.width - 1;
  33452. x_step = -1;
  33453. x_end = -1;
  33454. y_start = header.height - 1;
  33455. y_step = -1;
  33456. y_end = -1;
  33457. break;
  33458. }
  33459. // Load the specify method
  33460. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  33461. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  33462. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  33463. };
  33464. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33465. var image = pixel_data, colormap = palettes;
  33466. var width = header.width, height = header.height;
  33467. var color, i = 0, x, y;
  33468. var imageData = new Uint8Array(width * height * 4);
  33469. for (y = y_start; y !== y_end; y += y_step) {
  33470. for (x = x_start; x !== x_end; x += x_step, i++) {
  33471. color = image[i];
  33472. imageData[(x + width * y) * 4 + 3] = 255;
  33473. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  33474. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  33475. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  33476. }
  33477. }
  33478. return imageData;
  33479. };
  33480. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33481. var image = pixel_data;
  33482. var width = header.width, height = header.height;
  33483. var color, i = 0, x, y;
  33484. var imageData = new Uint8Array(width * height * 4);
  33485. for (y = y_start; y !== y_end; y += y_step) {
  33486. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33487. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  33488. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  33489. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  33490. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  33491. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  33492. }
  33493. }
  33494. return imageData;
  33495. };
  33496. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33497. var image = pixel_data;
  33498. var width = header.width, height = header.height;
  33499. var i = 0, x, y;
  33500. var imageData = new Uint8Array(width * height * 4);
  33501. for (y = y_start; y !== y_end; y += y_step) {
  33502. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  33503. imageData[(x + width * y) * 4 + 3] = 255;
  33504. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33505. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33506. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33507. }
  33508. }
  33509. return imageData;
  33510. };
  33511. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33512. var image = pixel_data;
  33513. var width = header.width, height = header.height;
  33514. var i = 0, x, y;
  33515. var imageData = new Uint8Array(width * height * 4);
  33516. for (y = y_start; y !== y_end; y += y_step) {
  33517. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  33518. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33519. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33520. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33521. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  33522. }
  33523. }
  33524. return imageData;
  33525. };
  33526. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33527. var image = pixel_data;
  33528. var width = header.width, height = header.height;
  33529. var color, i = 0, x, y;
  33530. var imageData = new Uint8Array(width * height * 4);
  33531. for (y = y_start; y !== y_end; y += y_step) {
  33532. for (x = x_start; x !== x_end; x += x_step, i++) {
  33533. color = image[i];
  33534. imageData[(x + width * y) * 4 + 0] = color;
  33535. imageData[(x + width * y) * 4 + 1] = color;
  33536. imageData[(x + width * y) * 4 + 2] = color;
  33537. imageData[(x + width * y) * 4 + 3] = 255;
  33538. }
  33539. }
  33540. return imageData;
  33541. };
  33542. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33543. var image = pixel_data;
  33544. var width = header.width, height = header.height;
  33545. var i = 0, x, y;
  33546. var imageData = new Uint8Array(width * height * 4);
  33547. for (y = y_start; y !== y_end; y += y_step) {
  33548. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33549. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  33550. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  33551. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33552. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  33553. }
  33554. }
  33555. return imageData;
  33556. };
  33557. return TGATools;
  33558. }());
  33559. TGATools._TYPE_NO_DATA = 0;
  33560. TGATools._TYPE_INDEXED = 1;
  33561. TGATools._TYPE_RGB = 2;
  33562. TGATools._TYPE_GREY = 3;
  33563. TGATools._TYPE_RLE_INDEXED = 9;
  33564. TGATools._TYPE_RLE_RGB = 10;
  33565. TGATools._TYPE_RLE_GREY = 11;
  33566. TGATools._ORIGIN_MASK = 0x30;
  33567. TGATools._ORIGIN_SHIFT = 0x04;
  33568. TGATools._ORIGIN_BL = 0x00;
  33569. TGATools._ORIGIN_BR = 0x01;
  33570. TGATools._ORIGIN_UL = 0x02;
  33571. TGATools._ORIGIN_UR = 0x03;
  33572. Internals.TGATools = TGATools;
  33573. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33574. })(BABYLON || (BABYLON = {}));
  33575. //# sourceMappingURL=babylon.tga.js.map
  33576. var BABYLON;
  33577. (function (BABYLON) {
  33578. var Internals;
  33579. (function (Internals) {
  33580. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  33581. // All values and structures referenced from:
  33582. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  33583. var DDS_MAGIC = 0x20534444;
  33584. 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;
  33585. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  33586. 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;
  33587. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  33588. function FourCCToInt32(value) {
  33589. return value.charCodeAt(0) +
  33590. (value.charCodeAt(1) << 8) +
  33591. (value.charCodeAt(2) << 16) +
  33592. (value.charCodeAt(3) << 24);
  33593. }
  33594. function Int32ToFourCC(value) {
  33595. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  33596. }
  33597. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  33598. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  33599. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  33600. var headerLengthInt = 31; // The header length in 32 bit ints
  33601. // Offsets into the header array
  33602. var off_magic = 0;
  33603. var off_size = 1;
  33604. var off_flags = 2;
  33605. var off_height = 3;
  33606. var off_width = 4;
  33607. var off_mipmapCount = 7;
  33608. var off_pfFlags = 20;
  33609. var off_pfFourCC = 21;
  33610. var off_RGBbpp = 22;
  33611. var off_RMask = 23;
  33612. var off_GMask = 24;
  33613. var off_BMask = 25;
  33614. var off_AMask = 26;
  33615. var off_caps1 = 27;
  33616. var off_caps2 = 28;
  33617. ;
  33618. var DDSTools = (function () {
  33619. function DDSTools() {
  33620. }
  33621. DDSTools.GetDDSInfo = function (arrayBuffer) {
  33622. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  33623. var mipmapCount = 1;
  33624. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  33625. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33626. }
  33627. return {
  33628. width: header[off_width],
  33629. height: header[off_height],
  33630. mipmapCount: mipmapCount,
  33631. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  33632. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  33633. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  33634. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  33635. };
  33636. };
  33637. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33638. var byteArray = new Uint8Array(dataLength);
  33639. var srcData = new Uint8Array(arrayBuffer);
  33640. var index = 0;
  33641. for (var y = height - 1; y >= 0; y--) {
  33642. for (var x = 0; x < width; x++) {
  33643. var srcPos = dataOffset + (x + y * width) * 4;
  33644. byteArray[index + 2] = srcData[srcPos];
  33645. byteArray[index + 1] = srcData[srcPos + 1];
  33646. byteArray[index] = srcData[srcPos + 2];
  33647. byteArray[index + 3] = srcData[srcPos + 3];
  33648. index += 4;
  33649. }
  33650. }
  33651. return byteArray;
  33652. };
  33653. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33654. var byteArray = new Uint8Array(dataLength);
  33655. var srcData = new Uint8Array(arrayBuffer);
  33656. var index = 0;
  33657. for (var y = height - 1; y >= 0; y--) {
  33658. for (var x = 0; x < width; x++) {
  33659. var srcPos = dataOffset + (x + y * width) * 3;
  33660. byteArray[index + 2] = srcData[srcPos];
  33661. byteArray[index + 1] = srcData[srcPos + 1];
  33662. byteArray[index] = srcData[srcPos + 2];
  33663. index += 3;
  33664. }
  33665. }
  33666. return byteArray;
  33667. };
  33668. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33669. var byteArray = new Uint8Array(dataLength);
  33670. var srcData = new Uint8Array(arrayBuffer);
  33671. var index = 0;
  33672. for (var y = height - 1; y >= 0; y--) {
  33673. for (var x = 0; x < width; x++) {
  33674. var srcPos = dataOffset + (x + y * width);
  33675. byteArray[index] = srcData[srcPos];
  33676. index++;
  33677. }
  33678. }
  33679. return byteArray;
  33680. };
  33681. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  33682. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  33683. if (header[off_magic] != DDS_MAGIC) {
  33684. BABYLON.Tools.Error("Invalid magic number in DDS header");
  33685. return;
  33686. }
  33687. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  33688. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  33689. return;
  33690. }
  33691. if (info.isFourCC) {
  33692. fourCC = header[off_pfFourCC];
  33693. switch (fourCC) {
  33694. case FOURCC_DXT1:
  33695. blockBytes = 8;
  33696. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33697. break;
  33698. case FOURCC_DXT3:
  33699. blockBytes = 16;
  33700. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33701. break;
  33702. case FOURCC_DXT5:
  33703. blockBytes = 16;
  33704. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  33705. break;
  33706. default:
  33707. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  33708. return;
  33709. }
  33710. }
  33711. mipmapCount = 1;
  33712. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  33713. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33714. }
  33715. var bpp = header[off_RGBbpp];
  33716. for (var face = 0; face < faces; face++) {
  33717. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33718. width = header[off_width];
  33719. height = header[off_height];
  33720. dataOffset = header[off_size] + 4;
  33721. for (i = 0; i < mipmapCount; ++i) {
  33722. if (info.isRGB) {
  33723. if (bpp === 24) {
  33724. dataLength = width * height * 3;
  33725. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33726. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  33727. }
  33728. else {
  33729. dataLength = width * height * 4;
  33730. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33731. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  33732. }
  33733. }
  33734. else if (info.isLuminance) {
  33735. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  33736. var unpaddedRowSize = width;
  33737. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  33738. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  33739. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33740. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  33741. }
  33742. else {
  33743. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  33744. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  33745. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  33746. }
  33747. dataOffset += dataLength;
  33748. width *= 0.5;
  33749. height *= 0.5;
  33750. width = Math.max(1.0, width);
  33751. height = Math.max(1.0, height);
  33752. }
  33753. }
  33754. };
  33755. return DDSTools;
  33756. }());
  33757. Internals.DDSTools = DDSTools;
  33758. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33759. })(BABYLON || (BABYLON = {}));
  33760. //# sourceMappingURL=babylon.dds.js.map
  33761. var BABYLON;
  33762. (function (BABYLON) {
  33763. var Internals;
  33764. (function (Internals) {
  33765. /**
  33766. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  33767. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  33768. */
  33769. var KhronosTextureContainer = (function () {
  33770. /**
  33771. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  33772. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  33773. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  33774. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  33775. */
  33776. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  33777. this.arrayBuffer = arrayBuffer;
  33778. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  33779. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  33780. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  33781. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  33782. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  33783. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  33784. BABYLON.Tools.Error("texture missing KTX identifier");
  33785. return;
  33786. }
  33787. // load the reset of the header in native 32 bit int
  33788. var header = new Int32Array(this.arrayBuffer, 12, 13);
  33789. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  33790. var oppositeEndianess = header[0] === 0x01020304;
  33791. // read all the header elements in order they exist in the file, without modification (sans endainness)
  33792. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  33793. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  33794. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  33795. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  33796. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  33797. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  33798. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  33799. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  33800. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  33801. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  33802. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  33803. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  33804. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  33805. if (this.glType !== 0) {
  33806. BABYLON.Tools.Error("only compressed formats currently supported");
  33807. return;
  33808. }
  33809. else {
  33810. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  33811. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  33812. }
  33813. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  33814. BABYLON.Tools.Error("only 2D textures currently supported");
  33815. return;
  33816. }
  33817. if (this.numberOfArrayElements !== 0) {
  33818. BABYLON.Tools.Error("texture arrays not currently supported");
  33819. return;
  33820. }
  33821. if (this.numberOfFaces !== facesExpected) {
  33822. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  33823. return;
  33824. }
  33825. // we now have a completely validated file, so could use existence of loadType as success
  33826. // would need to make this more elaborate & adjust checks above to support more than one load type
  33827. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  33828. }
  33829. // not as fast hardware based, but will probably never need to use
  33830. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  33831. return ((val & 0xFF) << 24)
  33832. | ((val & 0xFF00) << 8)
  33833. | ((val >> 8) & 0xFF00)
  33834. | ((val >> 24) & 0xFF);
  33835. };
  33836. /**
  33837. * It is assumed that the texture has already been created & is currently bound
  33838. */
  33839. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  33840. switch (this.loadType) {
  33841. case KhronosTextureContainer.COMPRESSED_2D:
  33842. this._upload2DCompressedLevels(gl, loadMipmaps);
  33843. break;
  33844. case KhronosTextureContainer.TEX_2D:
  33845. case KhronosTextureContainer.COMPRESSED_3D:
  33846. case KhronosTextureContainer.TEX_3D:
  33847. }
  33848. };
  33849. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  33850. // initialize width & height for level 1
  33851. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  33852. var width = this.pixelWidth;
  33853. var height = this.pixelHeight;
  33854. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  33855. for (var level = 0; level < mipmapCount; level++) {
  33856. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  33857. for (var face = 0; face < this.numberOfFaces; face++) {
  33858. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33859. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  33860. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  33861. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  33862. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  33863. }
  33864. width = Math.max(1.0, width * 0.5);
  33865. height = Math.max(1.0, height * 0.5);
  33866. }
  33867. };
  33868. return KhronosTextureContainer;
  33869. }());
  33870. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  33871. // load types
  33872. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  33873. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  33874. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  33875. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  33876. Internals.KhronosTextureContainer = KhronosTextureContainer;
  33877. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33878. })(BABYLON || (BABYLON = {}));
  33879. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  33880. /// <reference path="babylon.mesh.ts" />
  33881. var BABYLON;
  33882. (function (BABYLON) {
  33883. var GroundMesh = (function (_super) {
  33884. __extends(GroundMesh, _super);
  33885. function GroundMesh(name, scene) {
  33886. var _this = _super.call(this, name, scene) || this;
  33887. _this.generateOctree = false;
  33888. _this._worldInverse = new BABYLON.Matrix();
  33889. return _this;
  33890. }
  33891. GroundMesh.prototype.getClassName = function () {
  33892. return "GroundMesh";
  33893. };
  33894. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  33895. get: function () {
  33896. return Math.min(this._subdivisionsX, this._subdivisionsY);
  33897. },
  33898. enumerable: true,
  33899. configurable: true
  33900. });
  33901. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  33902. get: function () {
  33903. return this._subdivisionsX;
  33904. },
  33905. enumerable: true,
  33906. configurable: true
  33907. });
  33908. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  33909. get: function () {
  33910. return this._subdivisionsY;
  33911. },
  33912. enumerable: true,
  33913. configurable: true
  33914. });
  33915. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  33916. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  33917. this._subdivisionsX = chunksCount;
  33918. this._subdivisionsY = chunksCount;
  33919. this.subdivide(chunksCount);
  33920. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  33921. };
  33922. /**
  33923. * Returns a height (y) value in the Worl system :
  33924. * the ground altitude at the coordinates (x, z) expressed in the World system.
  33925. * Returns the ground y position if (x, z) are outside the ground surface.
  33926. */
  33927. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  33928. var world = this.getWorldMatrix();
  33929. var invMat = BABYLON.Tmp.Matrix[5];
  33930. world.invertToRef(invMat);
  33931. var tmpVect = BABYLON.Tmp.Vector3[8];
  33932. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  33933. x = tmpVect.x;
  33934. z = tmpVect.z;
  33935. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33936. return this.position.y;
  33937. }
  33938. if (!this._heightQuads || this._heightQuads.length == 0) {
  33939. this._initHeightQuads();
  33940. this._computeHeightQuads();
  33941. }
  33942. var facet = this._getFacetAt(x, z);
  33943. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  33944. // return y in the World system
  33945. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  33946. return tmpVect.y;
  33947. };
  33948. /**
  33949. * Returns a normalized vector (Vector3) orthogonal to the ground
  33950. * at the ground coordinates (x, z) expressed in the World system.
  33951. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  33952. */
  33953. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  33954. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  33955. this.getNormalAtCoordinatesToRef(x, z, normal);
  33956. return normal;
  33957. };
  33958. /**
  33959. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  33960. * at the ground coordinates (x, z) expressed in the World system.
  33961. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  33962. * Returns the GroundMesh.
  33963. */
  33964. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  33965. var world = this.getWorldMatrix();
  33966. var tmpMat = BABYLON.Tmp.Matrix[5];
  33967. world.invertToRef(tmpMat);
  33968. var tmpVect = BABYLON.Tmp.Vector3[8];
  33969. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  33970. x = tmpVect.x;
  33971. z = tmpVect.z;
  33972. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  33973. return this;
  33974. }
  33975. if (!this._heightQuads || this._heightQuads.length == 0) {
  33976. this._initHeightQuads();
  33977. this._computeHeightQuads();
  33978. }
  33979. var facet = this._getFacetAt(x, z);
  33980. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  33981. return this;
  33982. };
  33983. /**
  33984. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  33985. * if the ground has been updated.
  33986. * This can be used in the render loop.
  33987. * Returns the GroundMesh.
  33988. */
  33989. GroundMesh.prototype.updateCoordinateHeights = function () {
  33990. if (!this._heightQuads || this._heightQuads.length == 0) {
  33991. this._initHeightQuads();
  33992. }
  33993. this._computeHeightQuads();
  33994. return this;
  33995. };
  33996. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  33997. GroundMesh.prototype._getFacetAt = function (x, z) {
  33998. // retrieve col and row from x, z coordinates in the ground local system
  33999. var subdivisionsX = this._subdivisionsX;
  34000. var subdivisionsY = this._subdivisionsY;
  34001. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  34002. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  34003. var quad = this._heightQuads[row * this._subdivisionsX + col];
  34004. var facet;
  34005. if (z < quad.slope.x * x + quad.slope.y) {
  34006. facet = quad.facet1;
  34007. }
  34008. else {
  34009. facet = quad.facet2;
  34010. }
  34011. return facet;
  34012. };
  34013. // Creates and populates the heightMap array with "facet" elements :
  34014. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34015. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34016. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34017. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34018. // Returns the GroundMesh.
  34019. GroundMesh.prototype._initHeightQuads = function () {
  34020. var subdivisionsX = this._subdivisionsX;
  34021. var subdivisionsY = this._subdivisionsY;
  34022. this._heightQuads = new Array();
  34023. for (var row = 0; row < subdivisionsY; row++) {
  34024. for (var col = 0; col < subdivisionsX; col++) {
  34025. 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) };
  34026. this._heightQuads[row * subdivisionsX + col] = quad;
  34027. }
  34028. }
  34029. return this;
  34030. };
  34031. // Compute each quad element values and update the the heightMap array :
  34032. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34033. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34034. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34035. // Returns the GroundMesh.
  34036. GroundMesh.prototype._computeHeightQuads = function () {
  34037. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34038. var v1 = BABYLON.Tmp.Vector3[3];
  34039. var v2 = BABYLON.Tmp.Vector3[2];
  34040. var v3 = BABYLON.Tmp.Vector3[1];
  34041. var v4 = BABYLON.Tmp.Vector3[0];
  34042. var v1v2 = BABYLON.Tmp.Vector3[4];
  34043. var v1v3 = BABYLON.Tmp.Vector3[5];
  34044. var v1v4 = BABYLON.Tmp.Vector3[6];
  34045. var norm1 = BABYLON.Tmp.Vector3[7];
  34046. var norm2 = BABYLON.Tmp.Vector3[8];
  34047. var i = 0;
  34048. var j = 0;
  34049. var k = 0;
  34050. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34051. var h = 0;
  34052. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34053. var d2 = 0;
  34054. var subdivisionsX = this._subdivisionsX;
  34055. var subdivisionsY = this._subdivisionsY;
  34056. for (var row = 0; row < subdivisionsY; row++) {
  34057. for (var col = 0; col < subdivisionsX; col++) {
  34058. i = col * 3;
  34059. j = row * (subdivisionsX + 1) * 3;
  34060. k = (row + 1) * (subdivisionsX + 1) * 3;
  34061. v1.x = positions[j + i];
  34062. v1.y = positions[j + i + 1];
  34063. v1.z = positions[j + i + 2];
  34064. v2.x = positions[j + i + 3];
  34065. v2.y = positions[j + i + 4];
  34066. v2.z = positions[j + i + 5];
  34067. v3.x = positions[k + i];
  34068. v3.y = positions[k + i + 1];
  34069. v3.z = positions[k + i + 2];
  34070. v4.x = positions[k + i + 3];
  34071. v4.y = positions[k + i + 4];
  34072. v4.z = positions[k + i + 5];
  34073. // 2D slope V1V4
  34074. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34075. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34076. // facet equations :
  34077. // we compute each facet normal vector
  34078. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34079. // we compute the value d by applying the equation to v1 which belongs to the plane
  34080. // then we store the facet equation in a Vector4
  34081. v2.subtractToRef(v1, v1v2);
  34082. v3.subtractToRef(v1, v1v3);
  34083. v4.subtractToRef(v1, v1v4);
  34084. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34085. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34086. norm1.normalize();
  34087. norm2.normalize();
  34088. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34089. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34090. var quad = this._heightQuads[row * subdivisionsX + col];
  34091. quad.slope.copyFromFloats(cd, h);
  34092. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34093. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34094. }
  34095. }
  34096. return this;
  34097. };
  34098. GroundMesh.prototype.serialize = function (serializationObject) {
  34099. _super.prototype.serialize.call(this, serializationObject);
  34100. serializationObject.subdivisionsX = this._subdivisionsX;
  34101. serializationObject.subdivisionsY = this._subdivisionsY;
  34102. serializationObject.minX = this._minX;
  34103. serializationObject.maxX = this._maxX;
  34104. serializationObject.minZ = this._minZ;
  34105. serializationObject.maxZ = this._maxZ;
  34106. serializationObject.width = this._width;
  34107. serializationObject.height = this._height;
  34108. };
  34109. GroundMesh.Parse = function (parsedMesh, scene) {
  34110. var result = new GroundMesh(parsedMesh.name, scene);
  34111. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  34112. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  34113. result._minX = parsedMesh.minX;
  34114. result._maxX = parsedMesh.maxX;
  34115. result._minZ = parsedMesh.minZ;
  34116. result._maxZ = parsedMesh.maxZ;
  34117. result._width = parsedMesh.width;
  34118. result._height = parsedMesh.height;
  34119. return result;
  34120. };
  34121. return GroundMesh;
  34122. }(BABYLON.Mesh));
  34123. BABYLON.GroundMesh = GroundMesh;
  34124. })(BABYLON || (BABYLON = {}));
  34125. //# sourceMappingURL=babylon.groundMesh.js.map
  34126. var BABYLON;
  34127. (function (BABYLON) {
  34128. /**
  34129. * Creates an instance based on a source mesh.
  34130. */
  34131. var InstancedMesh = (function (_super) {
  34132. __extends(InstancedMesh, _super);
  34133. function InstancedMesh(name, source) {
  34134. var _this = _super.call(this, name, source.getScene()) || this;
  34135. source.instances.push(_this);
  34136. _this._sourceMesh = source;
  34137. _this.position.copyFrom(source.position);
  34138. _this.rotation.copyFrom(source.rotation);
  34139. _this.scaling.copyFrom(source.scaling);
  34140. if (source.rotationQuaternion) {
  34141. _this.rotationQuaternion = source.rotationQuaternion.clone();
  34142. }
  34143. _this.infiniteDistance = source.infiniteDistance;
  34144. _this.setPivotMatrix(source.getPivotMatrix());
  34145. _this.refreshBoundingInfo();
  34146. _this._syncSubMeshes();
  34147. return _this;
  34148. }
  34149. /**
  34150. * Returns the string "InstancedMesh".
  34151. */
  34152. InstancedMesh.prototype.getClassName = function () {
  34153. return "InstancedMesh";
  34154. };
  34155. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  34156. // Methods
  34157. get: function () {
  34158. return this._sourceMesh.receiveShadows;
  34159. },
  34160. enumerable: true,
  34161. configurable: true
  34162. });
  34163. Object.defineProperty(InstancedMesh.prototype, "material", {
  34164. get: function () {
  34165. return this._sourceMesh.material;
  34166. },
  34167. enumerable: true,
  34168. configurable: true
  34169. });
  34170. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  34171. get: function () {
  34172. return this._sourceMesh.visibility;
  34173. },
  34174. enumerable: true,
  34175. configurable: true
  34176. });
  34177. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  34178. get: function () {
  34179. return this._sourceMesh.skeleton;
  34180. },
  34181. enumerable: true,
  34182. configurable: true
  34183. });
  34184. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  34185. get: function () {
  34186. return this._sourceMesh.renderingGroupId;
  34187. },
  34188. enumerable: true,
  34189. configurable: true
  34190. });
  34191. /**
  34192. * Returns the total number of vertices (integer).
  34193. */
  34194. InstancedMesh.prototype.getTotalVertices = function () {
  34195. return this._sourceMesh.getTotalVertices();
  34196. };
  34197. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  34198. get: function () {
  34199. return this._sourceMesh;
  34200. },
  34201. enumerable: true,
  34202. configurable: true
  34203. });
  34204. /**
  34205. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  34206. */
  34207. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  34208. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  34209. };
  34210. /**
  34211. * Sets the vertex data of the mesh geometry for the requested `kind`.
  34212. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  34213. * The `data` are either a numeric array either a Float32Array.
  34214. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  34215. * 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).
  34216. * Note that a new underlying VertexBuffer object is created each call.
  34217. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  34218. *
  34219. * Possible `kind` values :
  34220. * - BABYLON.VertexBuffer.PositionKind
  34221. * - BABYLON.VertexBuffer.UVKind
  34222. * - BABYLON.VertexBuffer.UV2Kind
  34223. * - BABYLON.VertexBuffer.UV3Kind
  34224. * - BABYLON.VertexBuffer.UV4Kind
  34225. * - BABYLON.VertexBuffer.UV5Kind
  34226. * - BABYLON.VertexBuffer.UV6Kind
  34227. * - BABYLON.VertexBuffer.ColorKind
  34228. * - BABYLON.VertexBuffer.MatricesIndicesKind
  34229. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  34230. * - BABYLON.VertexBuffer.MatricesWeightsKind
  34231. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  34232. *
  34233. * Returns the Mesh.
  34234. */
  34235. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34236. if (this.sourceMesh) {
  34237. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  34238. }
  34239. return this.sourceMesh;
  34240. };
  34241. /**
  34242. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  34243. * If the mesh has no geometry, it is simply returned as it is.
  34244. * The `data` are either a numeric array either a Float32Array.
  34245. * No new underlying VertexBuffer object is created.
  34246. * 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.
  34247. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  34248. *
  34249. * Possible `kind` values :
  34250. * - BABYLON.VertexBuffer.PositionKind
  34251. * - BABYLON.VertexBuffer.UVKind
  34252. * - BABYLON.VertexBuffer.UV2Kind
  34253. * - BABYLON.VertexBuffer.UV3Kind
  34254. * - BABYLON.VertexBuffer.UV4Kind
  34255. * - BABYLON.VertexBuffer.UV5Kind
  34256. * - BABYLON.VertexBuffer.UV6Kind
  34257. * - BABYLON.VertexBuffer.ColorKind
  34258. * - BABYLON.VertexBuffer.MatricesIndicesKind
  34259. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  34260. * - BABYLON.VertexBuffer.MatricesWeightsKind
  34261. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  34262. *
  34263. * Returns the Mesh.
  34264. */
  34265. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  34266. if (this.sourceMesh) {
  34267. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  34268. }
  34269. return this.sourceMesh;
  34270. };
  34271. /**
  34272. * Sets the mesh indices.
  34273. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  34274. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  34275. * This method creates a new index buffer each call.
  34276. * Returns the Mesh.
  34277. */
  34278. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  34279. if (this.sourceMesh) {
  34280. this.sourceMesh.setIndices(indices, totalVertices);
  34281. }
  34282. return this.sourceMesh;
  34283. };
  34284. /**
  34285. * Boolean : True if the mesh owns the requested kind of data.
  34286. */
  34287. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  34288. return this._sourceMesh.isVerticesDataPresent(kind);
  34289. };
  34290. /**
  34291. * Returns an array of indices (IndicesArray).
  34292. */
  34293. InstancedMesh.prototype.getIndices = function () {
  34294. return this._sourceMesh.getIndices();
  34295. };
  34296. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  34297. get: function () {
  34298. return this._sourceMesh._positions;
  34299. },
  34300. enumerable: true,
  34301. configurable: true
  34302. });
  34303. /**
  34304. * Sets a new updated BoundingInfo to the mesh.
  34305. * Returns the mesh.
  34306. */
  34307. InstancedMesh.prototype.refreshBoundingInfo = function () {
  34308. var meshBB = this._sourceMesh.getBoundingInfo();
  34309. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  34310. this._updateBoundingInfo();
  34311. return this;
  34312. };
  34313. InstancedMesh.prototype._preActivate = function () {
  34314. if (this._currentLOD) {
  34315. this._currentLOD._preActivate();
  34316. }
  34317. return this;
  34318. };
  34319. InstancedMesh.prototype._activate = function (renderId) {
  34320. if (this._currentLOD) {
  34321. this._currentLOD._registerInstanceForRenderId(this, renderId);
  34322. }
  34323. return this;
  34324. };
  34325. /**
  34326. * Returns the current associated LOD AbstractMesh.
  34327. */
  34328. InstancedMesh.prototype.getLOD = function (camera) {
  34329. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  34330. if (this._currentLOD === this.sourceMesh) {
  34331. return this;
  34332. }
  34333. return this._currentLOD;
  34334. };
  34335. InstancedMesh.prototype._syncSubMeshes = function () {
  34336. this.releaseSubMeshes();
  34337. if (this._sourceMesh.subMeshes) {
  34338. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  34339. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  34340. }
  34341. }
  34342. return this;
  34343. };
  34344. InstancedMesh.prototype._generatePointsArray = function () {
  34345. return this._sourceMesh._generatePointsArray();
  34346. };
  34347. /**
  34348. * Creates a new InstancedMesh from the current mesh.
  34349. * - name (string) : the cloned mesh name
  34350. * - newParent (optional Node) : the optional Node to parent the clone to.
  34351. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  34352. *
  34353. * Returns the clone.
  34354. */
  34355. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34356. var result = this._sourceMesh.createInstance(name);
  34357. // Deep copy
  34358. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  34359. // Bounding info
  34360. this.refreshBoundingInfo();
  34361. // Parent
  34362. if (newParent) {
  34363. result.parent = newParent;
  34364. }
  34365. if (!doNotCloneChildren) {
  34366. // Children
  34367. for (var index = 0; index < this.getScene().meshes.length; index++) {
  34368. var mesh = this.getScene().meshes[index];
  34369. if (mesh.parent === this) {
  34370. mesh.clone(mesh.name, result);
  34371. }
  34372. }
  34373. }
  34374. result.computeWorldMatrix(true);
  34375. return result;
  34376. };
  34377. /**
  34378. * Disposes the InstancedMesh.
  34379. * Returns nothing.
  34380. */
  34381. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  34382. // Remove from mesh
  34383. var index = this._sourceMesh.instances.indexOf(this);
  34384. this._sourceMesh.instances.splice(index, 1);
  34385. _super.prototype.dispose.call(this, doNotRecurse);
  34386. };
  34387. return InstancedMesh;
  34388. }(BABYLON.AbstractMesh));
  34389. BABYLON.InstancedMesh = InstancedMesh;
  34390. })(BABYLON || (BABYLON = {}));
  34391. //# sourceMappingURL=babylon.instancedMesh.js.map
  34392. /// <reference path="babylon.mesh.ts" />
  34393. var BABYLON;
  34394. (function (BABYLON) {
  34395. var LinesMesh = (function (_super) {
  34396. __extends(LinesMesh, _super);
  34397. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  34398. if (parent === void 0) { parent = null; }
  34399. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  34400. _this.useVertexColor = useVertexColor;
  34401. _this.color = new BABYLON.Color3(1, 1, 1);
  34402. _this.alpha = 1;
  34403. if (source) {
  34404. _this.color = source.color.clone();
  34405. _this.alpha = source.alpha;
  34406. _this.useVertexColor = source.useVertexColor;
  34407. }
  34408. _this._intersectionThreshold = 0.1;
  34409. var options = {
  34410. attributes: [BABYLON.VertexBuffer.PositionKind],
  34411. uniforms: ["world", "viewProjection"],
  34412. needAlphaBlending: false,
  34413. };
  34414. if (!useVertexColor) {
  34415. options.uniforms.push("color");
  34416. options.needAlphaBlending = true;
  34417. }
  34418. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  34419. return _this;
  34420. }
  34421. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34422. /**
  34423. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34424. * This margin is expressed in world space coordinates, so its value may vary.
  34425. * Default value is 0.1
  34426. * @returns the intersection Threshold value.
  34427. */
  34428. get: function () {
  34429. return this._intersectionThreshold;
  34430. },
  34431. /**
  34432. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34433. * This margin is expressed in world space coordinates, so its value may vary.
  34434. * @param value the new threshold to apply
  34435. */
  34436. set: function (value) {
  34437. if (this._intersectionThreshold === value) {
  34438. return;
  34439. }
  34440. this._intersectionThreshold = value;
  34441. if (this.geometry) {
  34442. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34443. }
  34444. },
  34445. enumerable: true,
  34446. configurable: true
  34447. });
  34448. /**
  34449. * Returns the string "LineMesh"
  34450. */
  34451. LinesMesh.prototype.getClassName = function () {
  34452. return "LinesMesh";
  34453. };
  34454. Object.defineProperty(LinesMesh.prototype, "material", {
  34455. get: function () {
  34456. return this._colorShader;
  34457. },
  34458. enumerable: true,
  34459. configurable: true
  34460. });
  34461. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34462. get: function () {
  34463. return false;
  34464. },
  34465. enumerable: true,
  34466. configurable: true
  34467. });
  34468. LinesMesh.prototype.createInstance = function (name) {
  34469. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34470. return null;
  34471. };
  34472. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34473. // VBOs
  34474. this._geometry._bind(this._colorShader.getEffect());
  34475. // Color
  34476. if (!this.useVertexColor) {
  34477. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34478. }
  34479. return this;
  34480. };
  34481. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34482. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34483. return this;
  34484. }
  34485. var engine = this.getScene().getEngine();
  34486. // Draw order
  34487. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34488. return this;
  34489. };
  34490. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34491. this._colorShader.dispose();
  34492. _super.prototype.dispose.call(this, doNotRecurse);
  34493. };
  34494. /**
  34495. * Returns a new LineMesh object cloned from the current one.
  34496. */
  34497. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34498. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34499. };
  34500. return LinesMesh;
  34501. }(BABYLON.Mesh));
  34502. BABYLON.LinesMesh = LinesMesh;
  34503. })(BABYLON || (BABYLON = {}));
  34504. //# sourceMappingURL=babylon.linesMesh.js.map
  34505. var BABYLON;
  34506. (function (BABYLON) {
  34507. var StandardMaterialDefines = (function (_super) {
  34508. __extends(StandardMaterialDefines, _super);
  34509. function StandardMaterialDefines() {
  34510. var _this = _super.call(this) || this;
  34511. _this.DIFFUSE = false;
  34512. _this.AMBIENT = false;
  34513. _this.OPACITY = false;
  34514. _this.OPACITYRGB = false;
  34515. _this.REFLECTION = false;
  34516. _this.EMISSIVE = false;
  34517. _this.SPECULAR = false;
  34518. _this.BUMP = false;
  34519. _this.PARALLAX = false;
  34520. _this.PARALLAXOCCLUSION = false;
  34521. _this.SPECULAROVERALPHA = false;
  34522. _this.CLIPPLANE = false;
  34523. _this.ALPHATEST = false;
  34524. _this.ALPHAFROMDIFFUSE = false;
  34525. _this.POINTSIZE = false;
  34526. _this.FOG = false;
  34527. _this.SPECULARTERM = false;
  34528. _this.DIFFUSEFRESNEL = false;
  34529. _this.OPACITYFRESNEL = false;
  34530. _this.REFLECTIONFRESNEL = false;
  34531. _this.REFRACTIONFRESNEL = false;
  34532. _this.EMISSIVEFRESNEL = false;
  34533. _this.FRESNEL = false;
  34534. _this.NORMAL = false;
  34535. _this.UV1 = false;
  34536. _this.UV2 = false;
  34537. _this.VERTEXCOLOR = false;
  34538. _this.VERTEXALPHA = false;
  34539. _this.NUM_BONE_INFLUENCERS = 0;
  34540. _this.BonesPerMesh = 0;
  34541. _this.INSTANCES = false;
  34542. _this.GLOSSINESS = false;
  34543. _this.ROUGHNESS = false;
  34544. _this.EMISSIVEASILLUMINATION = false;
  34545. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34546. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34547. _this.LIGHTMAP = false;
  34548. _this.USELIGHTMAPASSHADOWMAP = false;
  34549. _this.REFLECTIONMAP_3D = false;
  34550. _this.REFLECTIONMAP_SPHERICAL = false;
  34551. _this.REFLECTIONMAP_PLANAR = false;
  34552. _this.REFLECTIONMAP_CUBIC = false;
  34553. _this.REFLECTIONMAP_PROJECTION = false;
  34554. _this.REFLECTIONMAP_SKYBOX = false;
  34555. _this.REFLECTIONMAP_EXPLICIT = false;
  34556. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34557. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34558. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34559. _this.INVERTCUBICMAP = false;
  34560. _this.LOGARITHMICDEPTH = false;
  34561. _this.REFRACTION = false;
  34562. _this.REFRACTIONMAP_3D = false;
  34563. _this.REFLECTIONOVERALPHA = false;
  34564. _this.INVERTNORMALMAPX = false;
  34565. _this.INVERTNORMALMAPY = false;
  34566. _this.TWOSIDEDLIGHTING = false;
  34567. _this.SHADOWFULLFLOAT = false;
  34568. _this.CAMERACOLORGRADING = false;
  34569. _this.CAMERACOLORCURVES = false;
  34570. _this.MORPHTARGETS = false;
  34571. _this.MORPHTARGETS_NORMAL = false;
  34572. _this.MORPHTARGETS_TANGENT = false;
  34573. _this.NUM_MORPH_INFLUENCERS = 0;
  34574. _this.USERIGHTHANDEDSYSTEM = false;
  34575. _this.rebuild();
  34576. return _this;
  34577. }
  34578. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34579. var modes = [
  34580. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34581. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34582. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34583. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34584. ];
  34585. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34586. var mode = modes_1[_i];
  34587. this[mode] = (mode === modeToEnable);
  34588. }
  34589. };
  34590. return StandardMaterialDefines;
  34591. }(BABYLON.MaterialDefines));
  34592. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34593. var StandardMaterial = (function (_super) {
  34594. __extends(StandardMaterial, _super);
  34595. function StandardMaterial(name, scene) {
  34596. var _this = _super.call(this, name, scene) || this;
  34597. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34598. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34599. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34600. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34601. _this.specularPower = 64;
  34602. _this._useAlphaFromDiffuseTexture = false;
  34603. _this._useEmissiveAsIllumination = false;
  34604. _this._linkEmissiveWithDiffuse = false;
  34605. _this._useSpecularOverAlpha = false;
  34606. _this._useReflectionOverAlpha = false;
  34607. _this._disableLighting = false;
  34608. _this._useParallax = false;
  34609. _this._useParallaxOcclusion = false;
  34610. _this.parallaxScaleBias = 0.05;
  34611. _this._roughness = 0;
  34612. _this.indexOfRefraction = 0.98;
  34613. _this.invertRefractionY = true;
  34614. _this._useLightmapAsShadowmap = false;
  34615. _this._useReflectionFresnelFromSpecular = false;
  34616. _this._useGlossinessFromSpecularMapAlpha = false;
  34617. _this._maxSimultaneousLights = 4;
  34618. /**
  34619. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34620. */
  34621. _this._invertNormalMapX = false;
  34622. /**
  34623. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34624. */
  34625. _this._invertNormalMapY = false;
  34626. /**
  34627. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34628. */
  34629. _this._twoSidedLighting = false;
  34630. /**
  34631. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34632. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34633. * 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;
  34634. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34635. */
  34636. _this._cameraColorCurves = null;
  34637. _this._renderTargets = new BABYLON.SmartArray(16);
  34638. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34639. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34640. _this.getRenderTargetTextures = function () {
  34641. _this._renderTargets.reset();
  34642. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34643. _this._renderTargets.push(_this._reflectionTexture);
  34644. }
  34645. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34646. _this._renderTargets.push(_this._refractionTexture);
  34647. }
  34648. return _this._renderTargets;
  34649. };
  34650. return _this;
  34651. }
  34652. StandardMaterial.prototype.getClassName = function () {
  34653. return "StandardMaterial";
  34654. };
  34655. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34656. get: function () {
  34657. return this._useLogarithmicDepth;
  34658. },
  34659. set: function (value) {
  34660. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34661. this._markAllSubMeshesAsMiscDirty();
  34662. },
  34663. enumerable: true,
  34664. configurable: true
  34665. });
  34666. StandardMaterial.prototype.needAlphaBlending = function () {
  34667. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34668. };
  34669. StandardMaterial.prototype.needAlphaTesting = function () {
  34670. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34671. };
  34672. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34673. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34674. };
  34675. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34676. return this._diffuseTexture;
  34677. };
  34678. /**
  34679. * Child classes can use it to update shaders
  34680. */
  34681. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34682. if (this.isFrozen) {
  34683. if (this._wasPreviouslyReady && subMesh.effect) {
  34684. return true;
  34685. }
  34686. }
  34687. if (!subMesh._materialDefines) {
  34688. subMesh._materialDefines = new StandardMaterialDefines();
  34689. }
  34690. var scene = this.getScene();
  34691. var defines = subMesh._materialDefines;
  34692. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34693. if (defines._renderId === scene.getRenderId()) {
  34694. return true;
  34695. }
  34696. }
  34697. var engine = scene.getEngine();
  34698. // Lights
  34699. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34700. // Textures
  34701. if (defines._areTexturesDirty) {
  34702. defines._needUVs = false;
  34703. if (scene.texturesEnabled) {
  34704. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34705. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34706. return false;
  34707. }
  34708. else {
  34709. defines._needUVs = true;
  34710. defines.DIFFUSE = true;
  34711. }
  34712. }
  34713. else {
  34714. defines.DIFFUSE = false;
  34715. }
  34716. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34717. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34718. return false;
  34719. }
  34720. else {
  34721. defines._needUVs = true;
  34722. defines.AMBIENT = true;
  34723. }
  34724. }
  34725. else {
  34726. defines.AMBIENT = false;
  34727. }
  34728. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34729. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34730. return false;
  34731. }
  34732. else {
  34733. defines._needUVs = true;
  34734. defines.OPACITY = true;
  34735. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34736. }
  34737. }
  34738. else {
  34739. defines.OPACITY = false;
  34740. }
  34741. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34742. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34743. return false;
  34744. }
  34745. else {
  34746. defines._needNormals = true;
  34747. defines.REFLECTION = true;
  34748. defines.ROUGHNESS = (this._roughness > 0);
  34749. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34750. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34751. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34752. switch (this._reflectionTexture.coordinatesMode) {
  34753. case BABYLON.Texture.CUBIC_MODE:
  34754. case BABYLON.Texture.INVCUBIC_MODE:
  34755. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34756. break;
  34757. case BABYLON.Texture.EXPLICIT_MODE:
  34758. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34759. break;
  34760. case BABYLON.Texture.PLANAR_MODE:
  34761. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34762. break;
  34763. case BABYLON.Texture.PROJECTION_MODE:
  34764. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34765. break;
  34766. case BABYLON.Texture.SKYBOX_MODE:
  34767. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34768. break;
  34769. case BABYLON.Texture.SPHERICAL_MODE:
  34770. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34771. break;
  34772. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34773. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34774. break;
  34775. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34776. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34777. break;
  34778. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34779. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34780. break;
  34781. }
  34782. }
  34783. }
  34784. else {
  34785. defines.REFLECTION = false;
  34786. }
  34787. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34788. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34789. return false;
  34790. }
  34791. else {
  34792. defines._needUVs = true;
  34793. defines.EMISSIVE = true;
  34794. }
  34795. }
  34796. else {
  34797. defines.EMISSIVE = false;
  34798. }
  34799. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34800. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34801. return false;
  34802. }
  34803. else {
  34804. defines._needUVs = true;
  34805. defines.LIGHTMAP = true;
  34806. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34807. }
  34808. }
  34809. else {
  34810. defines.LIGHTMAP = false;
  34811. }
  34812. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34813. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34814. return false;
  34815. }
  34816. else {
  34817. defines._needUVs = true;
  34818. defines.SPECULAR = true;
  34819. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34820. }
  34821. }
  34822. else {
  34823. defines.SPECULAR = false;
  34824. }
  34825. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34826. // Bump texure can not be none blocking.
  34827. if (!this._bumpTexture.isReady()) {
  34828. return false;
  34829. }
  34830. else {
  34831. defines._needUVs = true;
  34832. defines.BUMP = true;
  34833. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  34834. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  34835. defines.PARALLAX = this._useParallax;
  34836. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34837. }
  34838. }
  34839. else {
  34840. defines.BUMP = false;
  34841. }
  34842. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34843. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34844. return false;
  34845. }
  34846. else {
  34847. defines._needUVs = true;
  34848. defines.REFRACTION = true;
  34849. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34850. }
  34851. }
  34852. else {
  34853. defines.REFRACTION = false;
  34854. }
  34855. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  34856. // Camera Color Grading can not be none blocking.
  34857. if (!this._cameraColorGradingTexture.isReady()) {
  34858. return false;
  34859. }
  34860. else {
  34861. defines.CAMERACOLORGRADING = true;
  34862. }
  34863. }
  34864. else {
  34865. defines.CAMERACOLORGRADING = false;
  34866. }
  34867. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34868. }
  34869. else {
  34870. defines.DIFFUSE = false;
  34871. defines.AMBIENT = false;
  34872. defines.OPACITY = false;
  34873. defines.REFLECTION = false;
  34874. defines.EMISSIVE = false;
  34875. defines.LIGHTMAP = false;
  34876. defines.BUMP = false;
  34877. defines.REFRACTION = false;
  34878. defines.CAMERACOLORGRADING = false;
  34879. }
  34880. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  34881. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34882. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34883. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34884. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34885. }
  34886. if (defines._areFresnelDirty) {
  34887. if (StandardMaterial.FresnelEnabled) {
  34888. // Fresnel
  34889. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  34890. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  34891. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  34892. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  34893. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  34894. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34895. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34896. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34897. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34898. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34899. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34900. defines._needNormals = true;
  34901. defines.FRESNEL = true;
  34902. }
  34903. }
  34904. else {
  34905. defines.FRESNEL = false;
  34906. }
  34907. }
  34908. // Misc.
  34909. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34910. // Attribs
  34911. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34912. // Values that need to be evaluated on every frame
  34913. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34914. if (scene._mirroredCameraPosition && defines.BUMP) {
  34915. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  34916. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  34917. defines.markAsUnprocessed();
  34918. }
  34919. // Get correct effect
  34920. if (defines.isDirty) {
  34921. defines.markAsProcessed();
  34922. scene.resetCachedMaterial();
  34923. // Fallbacks
  34924. var fallbacks = new BABYLON.EffectFallbacks();
  34925. if (defines.REFLECTION) {
  34926. fallbacks.addFallback(0, "REFLECTION");
  34927. }
  34928. if (defines.SPECULAR) {
  34929. fallbacks.addFallback(0, "SPECULAR");
  34930. }
  34931. if (defines.BUMP) {
  34932. fallbacks.addFallback(0, "BUMP");
  34933. }
  34934. if (defines.PARALLAX) {
  34935. fallbacks.addFallback(1, "PARALLAX");
  34936. }
  34937. if (defines.PARALLAXOCCLUSION) {
  34938. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34939. }
  34940. if (defines.SPECULAROVERALPHA) {
  34941. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34942. }
  34943. if (defines.FOG) {
  34944. fallbacks.addFallback(1, "FOG");
  34945. }
  34946. if (defines.POINTSIZE) {
  34947. fallbacks.addFallback(0, "POINTSIZE");
  34948. }
  34949. if (defines.LOGARITHMICDEPTH) {
  34950. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34951. }
  34952. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34953. if (defines.SPECULARTERM) {
  34954. fallbacks.addFallback(0, "SPECULARTERM");
  34955. }
  34956. if (defines.DIFFUSEFRESNEL) {
  34957. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34958. }
  34959. if (defines.OPACITYFRESNEL) {
  34960. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34961. }
  34962. if (defines.REFLECTIONFRESNEL) {
  34963. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34964. }
  34965. if (defines.EMISSIVEFRESNEL) {
  34966. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34967. }
  34968. if (defines.FRESNEL) {
  34969. fallbacks.addFallback(4, "FRESNEL");
  34970. }
  34971. //Attributes
  34972. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34973. if (defines.NORMAL) {
  34974. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34975. }
  34976. if (defines.UV1) {
  34977. attribs.push(BABYLON.VertexBuffer.UVKind);
  34978. }
  34979. if (defines.UV2) {
  34980. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34981. }
  34982. if (defines.VERTEXCOLOR) {
  34983. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34984. }
  34985. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34986. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34987. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34988. var shaderName = "default";
  34989. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34990. "vFogInfos", "vFogColor", "pointSize",
  34991. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34992. "mBones",
  34993. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34994. "depthValues",
  34995. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34996. "logarithmicDepthConstant"
  34997. ];
  34998. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34999. var uniformBuffers = ["Material", "Scene"];
  35000. if (defines.CAMERACOLORCURVES) {
  35001. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35002. }
  35003. if (defines.CAMERACOLORGRADING) {
  35004. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  35005. }
  35006. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35007. uniformsNames: uniforms,
  35008. uniformBuffersNames: uniformBuffers,
  35009. samplers: samplers,
  35010. defines: defines,
  35011. maxSimultaneousLights: this._maxSimultaneousLights
  35012. });
  35013. if (this.customShaderNameResolve) {
  35014. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35015. }
  35016. var join = defines.toString();
  35017. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35018. attributes: attribs,
  35019. uniformsNames: uniforms,
  35020. uniformBuffersNames: uniformBuffers,
  35021. samplers: samplers,
  35022. defines: join,
  35023. fallbacks: fallbacks,
  35024. onCompiled: this.onCompiled,
  35025. onError: this.onError,
  35026. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35027. }, engine), defines);
  35028. this.buildUniformLayout();
  35029. }
  35030. if (!subMesh.effect.isReady()) {
  35031. return false;
  35032. }
  35033. defines._renderId = scene.getRenderId();
  35034. this._wasPreviouslyReady = true;
  35035. return true;
  35036. };
  35037. StandardMaterial.prototype.buildUniformLayout = function () {
  35038. // Order is important !
  35039. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35040. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35041. this._uniformBuffer.addUniform("opacityParts", 4);
  35042. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35043. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35044. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35045. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35046. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35047. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35048. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35049. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35050. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35051. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35052. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35053. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35054. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35055. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35056. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35057. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35058. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35059. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35060. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35061. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35062. this._uniformBuffer.addUniform("specularMatrix", 16);
  35063. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35064. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35065. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35066. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35067. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35068. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35069. this._uniformBuffer.addUniform("pointSize", 1);
  35070. this._uniformBuffer.create();
  35071. };
  35072. StandardMaterial.prototype.unbind = function () {
  35073. if (this._activeEffect) {
  35074. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35075. this._activeEffect.setTexture("reflection2DSampler", null);
  35076. }
  35077. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35078. this._activeEffect.setTexture("refraction2DSampler", null);
  35079. }
  35080. }
  35081. _super.prototype.unbind.call(this);
  35082. };
  35083. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35084. var scene = this.getScene();
  35085. var defines = subMesh._materialDefines;
  35086. if (!defines) {
  35087. return;
  35088. }
  35089. var effect = subMesh.effect;
  35090. this._activeEffect = effect;
  35091. // Matrices
  35092. this.bindOnlyWorldMatrix(world);
  35093. // Bones
  35094. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35095. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35096. this._uniformBuffer.bindToEffect(effect, "Material");
  35097. this.bindViewProjection(effect);
  35098. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35099. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35100. // Fresnel
  35101. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35102. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35103. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35104. }
  35105. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35106. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35107. }
  35108. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35109. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35110. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35111. }
  35112. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35113. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35114. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35115. }
  35116. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35117. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35118. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35119. }
  35120. }
  35121. // Textures
  35122. if (scene.texturesEnabled) {
  35123. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35124. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35125. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  35126. }
  35127. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35128. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35129. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  35130. }
  35131. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35132. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35133. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  35134. }
  35135. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35136. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35137. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35138. }
  35139. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35140. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35141. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  35142. }
  35143. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35144. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35145. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  35146. }
  35147. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35148. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35149. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  35150. }
  35151. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35152. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35153. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  35154. }
  35155. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35156. var depth = 1.0;
  35157. if (!this._refractionTexture.isCube) {
  35158. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35159. if (this._refractionTexture.depth) {
  35160. depth = this._refractionTexture.depth;
  35161. }
  35162. }
  35163. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35164. }
  35165. }
  35166. // Point size
  35167. if (this.pointsCloud) {
  35168. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35169. }
  35170. if (defines.SPECULARTERM) {
  35171. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35172. }
  35173. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35174. // Diffuse
  35175. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35176. }
  35177. // Textures
  35178. if (scene.texturesEnabled) {
  35179. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35180. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35181. }
  35182. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35183. effect.setTexture("ambientSampler", this._ambientTexture);
  35184. }
  35185. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35186. effect.setTexture("opacitySampler", this._opacityTexture);
  35187. }
  35188. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35189. if (this._reflectionTexture.isCube) {
  35190. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35191. }
  35192. else {
  35193. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35194. }
  35195. }
  35196. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35197. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35198. }
  35199. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35200. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35201. }
  35202. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35203. effect.setTexture("specularSampler", this._specularTexture);
  35204. }
  35205. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35206. effect.setTexture("bumpSampler", this._bumpTexture);
  35207. }
  35208. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35209. var depth = 1.0;
  35210. if (this._refractionTexture.isCube) {
  35211. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35212. }
  35213. else {
  35214. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35215. }
  35216. }
  35217. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  35218. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  35219. }
  35220. }
  35221. // Clip plane
  35222. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35223. // Colors
  35224. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35225. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  35226. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35227. }
  35228. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  35229. // Lights
  35230. if (scene.lightsEnabled && !this._disableLighting) {
  35231. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35232. }
  35233. // View
  35234. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35235. this.bindView(effect);
  35236. }
  35237. // Fog
  35238. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35239. // Morph targets
  35240. if (defines.NUM_MORPH_INFLUENCERS) {
  35241. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35242. }
  35243. // Log. depth
  35244. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35245. // Color Curves
  35246. if (this._cameraColorCurves) {
  35247. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  35248. }
  35249. }
  35250. this._uniformBuffer.update();
  35251. this._afterBind(mesh, this._activeEffect);
  35252. };
  35253. StandardMaterial.prototype.getAnimatables = function () {
  35254. var results = [];
  35255. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35256. results.push(this._diffuseTexture);
  35257. }
  35258. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35259. results.push(this._ambientTexture);
  35260. }
  35261. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35262. results.push(this._opacityTexture);
  35263. }
  35264. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35265. results.push(this._reflectionTexture);
  35266. }
  35267. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35268. results.push(this._emissiveTexture);
  35269. }
  35270. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35271. results.push(this._specularTexture);
  35272. }
  35273. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35274. results.push(this._bumpTexture);
  35275. }
  35276. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35277. results.push(this._lightmapTexture);
  35278. }
  35279. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35280. results.push(this._refractionTexture);
  35281. }
  35282. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  35283. results.push(this._cameraColorGradingTexture);
  35284. }
  35285. return results;
  35286. };
  35287. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35288. if (forceDisposeTextures) {
  35289. if (this._diffuseTexture) {
  35290. this._diffuseTexture.dispose();
  35291. }
  35292. if (this._ambientTexture) {
  35293. this._ambientTexture.dispose();
  35294. }
  35295. if (this._opacityTexture) {
  35296. this._opacityTexture.dispose();
  35297. }
  35298. if (this._reflectionTexture) {
  35299. this._reflectionTexture.dispose();
  35300. }
  35301. if (this._emissiveTexture) {
  35302. this._emissiveTexture.dispose();
  35303. }
  35304. if (this._specularTexture) {
  35305. this._specularTexture.dispose();
  35306. }
  35307. if (this._bumpTexture) {
  35308. this._bumpTexture.dispose();
  35309. }
  35310. if (this._lightmapTexture) {
  35311. this._lightmapTexture.dispose();
  35312. }
  35313. if (this._refractionTexture) {
  35314. this._refractionTexture.dispose();
  35315. }
  35316. if (this._cameraColorGradingTexture) {
  35317. this._cameraColorGradingTexture.dispose();
  35318. }
  35319. }
  35320. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35321. };
  35322. StandardMaterial.prototype.clone = function (name) {
  35323. var _this = this;
  35324. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35325. result.name = name;
  35326. result.id = name;
  35327. return result;
  35328. };
  35329. StandardMaterial.prototype.serialize = function () {
  35330. return BABYLON.SerializationHelper.Serialize(this);
  35331. };
  35332. // Statics
  35333. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35334. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35335. };
  35336. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35337. get: function () {
  35338. return StandardMaterial._DiffuseTextureEnabled;
  35339. },
  35340. set: function (value) {
  35341. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35342. return;
  35343. }
  35344. StandardMaterial._DiffuseTextureEnabled = value;
  35345. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35346. },
  35347. enumerable: true,
  35348. configurable: true
  35349. });
  35350. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35351. get: function () {
  35352. return StandardMaterial._AmbientTextureEnabled;
  35353. },
  35354. set: function (value) {
  35355. if (StandardMaterial._AmbientTextureEnabled === value) {
  35356. return;
  35357. }
  35358. StandardMaterial._AmbientTextureEnabled = value;
  35359. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35360. },
  35361. enumerable: true,
  35362. configurable: true
  35363. });
  35364. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35365. get: function () {
  35366. return StandardMaterial._OpacityTextureEnabled;
  35367. },
  35368. set: function (value) {
  35369. if (StandardMaterial._OpacityTextureEnabled === value) {
  35370. return;
  35371. }
  35372. StandardMaterial._OpacityTextureEnabled = value;
  35373. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35374. },
  35375. enumerable: true,
  35376. configurable: true
  35377. });
  35378. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35379. get: function () {
  35380. return StandardMaterial._ReflectionTextureEnabled;
  35381. },
  35382. set: function (value) {
  35383. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35384. return;
  35385. }
  35386. StandardMaterial._ReflectionTextureEnabled = value;
  35387. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35388. },
  35389. enumerable: true,
  35390. configurable: true
  35391. });
  35392. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35393. get: function () {
  35394. return StandardMaterial._EmissiveTextureEnabled;
  35395. },
  35396. set: function (value) {
  35397. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35398. return;
  35399. }
  35400. StandardMaterial._EmissiveTextureEnabled = value;
  35401. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35402. },
  35403. enumerable: true,
  35404. configurable: true
  35405. });
  35406. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35407. get: function () {
  35408. return StandardMaterial._SpecularTextureEnabled;
  35409. },
  35410. set: function (value) {
  35411. if (StandardMaterial._SpecularTextureEnabled === value) {
  35412. return;
  35413. }
  35414. StandardMaterial._SpecularTextureEnabled = value;
  35415. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35416. },
  35417. enumerable: true,
  35418. configurable: true
  35419. });
  35420. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35421. get: function () {
  35422. return StandardMaterial._BumpTextureEnabled;
  35423. },
  35424. set: function (value) {
  35425. if (StandardMaterial._BumpTextureEnabled === value) {
  35426. return;
  35427. }
  35428. StandardMaterial._BumpTextureEnabled = value;
  35429. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35430. },
  35431. enumerable: true,
  35432. configurable: true
  35433. });
  35434. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35435. get: function () {
  35436. return StandardMaterial._LightmapTextureEnabled;
  35437. },
  35438. set: function (value) {
  35439. if (StandardMaterial._LightmapTextureEnabled === value) {
  35440. return;
  35441. }
  35442. StandardMaterial._LightmapTextureEnabled = value;
  35443. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35444. },
  35445. enumerable: true,
  35446. configurable: true
  35447. });
  35448. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35449. get: function () {
  35450. return StandardMaterial._RefractionTextureEnabled;
  35451. },
  35452. set: function (value) {
  35453. if (StandardMaterial._RefractionTextureEnabled === value) {
  35454. return;
  35455. }
  35456. StandardMaterial._RefractionTextureEnabled = value;
  35457. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35458. },
  35459. enumerable: true,
  35460. configurable: true
  35461. });
  35462. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35463. get: function () {
  35464. return StandardMaterial._ColorGradingTextureEnabled;
  35465. },
  35466. set: function (value) {
  35467. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35468. return;
  35469. }
  35470. StandardMaterial._ColorGradingTextureEnabled = value;
  35471. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35472. },
  35473. enumerable: true,
  35474. configurable: true
  35475. });
  35476. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35477. get: function () {
  35478. return StandardMaterial._FresnelEnabled;
  35479. },
  35480. set: function (value) {
  35481. if (StandardMaterial._FresnelEnabled === value) {
  35482. return;
  35483. }
  35484. StandardMaterial._FresnelEnabled = value;
  35485. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35486. },
  35487. enumerable: true,
  35488. configurable: true
  35489. });
  35490. return StandardMaterial;
  35491. }(BABYLON.PushMaterial));
  35492. // Flags used to enable or disable a type of texture for all Standard Materials
  35493. StandardMaterial._DiffuseTextureEnabled = true;
  35494. StandardMaterial._AmbientTextureEnabled = true;
  35495. StandardMaterial._OpacityTextureEnabled = true;
  35496. StandardMaterial._ReflectionTextureEnabled = true;
  35497. StandardMaterial._EmissiveTextureEnabled = true;
  35498. StandardMaterial._SpecularTextureEnabled = true;
  35499. StandardMaterial._BumpTextureEnabled = true;
  35500. StandardMaterial._LightmapTextureEnabled = true;
  35501. StandardMaterial._RefractionTextureEnabled = true;
  35502. StandardMaterial._ColorGradingTextureEnabled = true;
  35503. StandardMaterial._FresnelEnabled = true;
  35504. __decorate([
  35505. BABYLON.serializeAsTexture("diffuseTexture")
  35506. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35507. __decorate([
  35508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35509. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35510. __decorate([
  35511. BABYLON.serializeAsTexture("ambientTexture")
  35512. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35513. __decorate([
  35514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35515. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35516. __decorate([
  35517. BABYLON.serializeAsTexture("opacityTexture")
  35518. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35519. __decorate([
  35520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35521. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35522. __decorate([
  35523. BABYLON.serializeAsTexture("reflectionTexture")
  35524. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35525. __decorate([
  35526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35527. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35528. __decorate([
  35529. BABYLON.serializeAsTexture("emissiveTexture")
  35530. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35531. __decorate([
  35532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35533. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35534. __decorate([
  35535. BABYLON.serializeAsTexture("specularTexture")
  35536. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35537. __decorate([
  35538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35539. ], StandardMaterial.prototype, "specularTexture", void 0);
  35540. __decorate([
  35541. BABYLON.serializeAsTexture("bumpTexture")
  35542. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35543. __decorate([
  35544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35545. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35546. __decorate([
  35547. BABYLON.serializeAsTexture("lightmapTexture")
  35548. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35549. __decorate([
  35550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35551. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35552. __decorate([
  35553. BABYLON.serializeAsTexture("refractionTexture")
  35554. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35555. __decorate([
  35556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35557. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35558. __decorate([
  35559. BABYLON.serializeAsColor3("ambient")
  35560. ], StandardMaterial.prototype, "ambientColor", void 0);
  35561. __decorate([
  35562. BABYLON.serializeAsColor3("diffuse")
  35563. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35564. __decorate([
  35565. BABYLON.serializeAsColor3("specular")
  35566. ], StandardMaterial.prototype, "specularColor", void 0);
  35567. __decorate([
  35568. BABYLON.serializeAsColor3("emissive")
  35569. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35570. __decorate([
  35571. BABYLON.serialize()
  35572. ], StandardMaterial.prototype, "specularPower", void 0);
  35573. __decorate([
  35574. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35575. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35576. __decorate([
  35577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35578. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35579. __decorate([
  35580. BABYLON.serialize("useEmissiveAsIllumination")
  35581. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35582. __decorate([
  35583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35584. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35585. __decorate([
  35586. BABYLON.serialize("linkEmissiveWithDiffuse")
  35587. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35588. __decorate([
  35589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35590. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35591. __decorate([
  35592. BABYLON.serialize("useSpecularOverAlpha")
  35593. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35594. __decorate([
  35595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35596. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35597. __decorate([
  35598. BABYLON.serialize("useReflectionOverAlpha")
  35599. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35600. __decorate([
  35601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35602. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35603. __decorate([
  35604. BABYLON.serialize("disableLighting")
  35605. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35606. __decorate([
  35607. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35608. ], StandardMaterial.prototype, "disableLighting", void 0);
  35609. __decorate([
  35610. BABYLON.serialize("useParallax")
  35611. ], StandardMaterial.prototype, "_useParallax", void 0);
  35612. __decorate([
  35613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35614. ], StandardMaterial.prototype, "useParallax", void 0);
  35615. __decorate([
  35616. BABYLON.serialize("useParallaxOcclusion")
  35617. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35618. __decorate([
  35619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35620. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35621. __decorate([
  35622. BABYLON.serialize()
  35623. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35624. __decorate([
  35625. BABYLON.serialize("roughness")
  35626. ], StandardMaterial.prototype, "_roughness", void 0);
  35627. __decorate([
  35628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35629. ], StandardMaterial.prototype, "roughness", void 0);
  35630. __decorate([
  35631. BABYLON.serialize()
  35632. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35633. __decorate([
  35634. BABYLON.serialize()
  35635. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35636. __decorate([
  35637. BABYLON.serialize("useLightmapAsShadowmap")
  35638. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35639. __decorate([
  35640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35641. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35642. __decorate([
  35643. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35644. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35645. __decorate([
  35646. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35647. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35648. __decorate([
  35649. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35650. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35651. __decorate([
  35652. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35653. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35654. __decorate([
  35655. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35656. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35657. __decorate([
  35658. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35659. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35660. __decorate([
  35661. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35662. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35663. __decorate([
  35664. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35665. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35666. __decorate([
  35667. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35668. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35669. __decorate([
  35670. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35671. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35672. __decorate([
  35673. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35674. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35675. __decorate([
  35676. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35677. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35678. __decorate([
  35679. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35680. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35681. __decorate([
  35682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35683. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35684. __decorate([
  35685. BABYLON.serialize("maxSimultaneousLights")
  35686. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35687. __decorate([
  35688. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35689. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35690. __decorate([
  35691. BABYLON.serialize("invertNormalMapX")
  35692. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35693. __decorate([
  35694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35695. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35696. __decorate([
  35697. BABYLON.serialize("invertNormalMapY")
  35698. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35699. __decorate([
  35700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35701. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35702. __decorate([
  35703. BABYLON.serialize("twoSidedLighting")
  35704. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35705. __decorate([
  35706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35707. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35708. __decorate([
  35709. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  35710. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  35711. __decorate([
  35712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35713. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  35714. __decorate([
  35715. BABYLON.serializeAsColorCurves("cameraColorCurves")
  35716. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  35717. __decorate([
  35718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35719. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  35720. __decorate([
  35721. BABYLON.serialize()
  35722. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35723. BABYLON.StandardMaterial = StandardMaterial;
  35724. })(BABYLON || (BABYLON = {}));
  35725. //# sourceMappingURL=babylon.standardMaterial.js.map
  35726. var BABYLON;
  35727. (function (BABYLON) {
  35728. /**
  35729. * This class implement a typical dictionary using a string as key and the generic type T as value.
  35730. * The underlying implementation relies on an associative array to ensure the best performances.
  35731. * The value can be anything including 'null' but except 'undefined'
  35732. */
  35733. var StringDictionary = (function () {
  35734. function StringDictionary() {
  35735. this._count = 0;
  35736. this._data = {};
  35737. }
  35738. /**
  35739. * This will clear this dictionary and copy the content from the 'source' one.
  35740. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  35741. * @param source the dictionary to take the content from and copy to this dictionary
  35742. */
  35743. StringDictionary.prototype.copyFrom = function (source) {
  35744. var _this = this;
  35745. this.clear();
  35746. source.forEach(function (t, v) { return _this.add(t, v); });
  35747. };
  35748. /**
  35749. * Get a value based from its key
  35750. * @param key the given key to get the matching value from
  35751. * @return the value if found, otherwise undefined is returned
  35752. */
  35753. StringDictionary.prototype.get = function (key) {
  35754. var val = this._data[key];
  35755. if (val !== undefined) {
  35756. return val;
  35757. }
  35758. return undefined;
  35759. };
  35760. /**
  35761. * Get a value from its key or add it if it doesn't exist.
  35762. * This method will ensure you that a given key/data will be present in the dictionary.
  35763. * @param key the given key to get the matching value from
  35764. * @param factory the factory that will create the value if the key is not present in the dictionary.
  35765. * The factory will only be invoked if there's no data for the given key.
  35766. * @return the value corresponding to the key.
  35767. */
  35768. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  35769. var val = this.get(key);
  35770. if (val !== undefined) {
  35771. return val;
  35772. }
  35773. val = factory(key);
  35774. if (val) {
  35775. this.add(key, val);
  35776. }
  35777. return val;
  35778. };
  35779. /**
  35780. * Get a value from its key if present in the dictionary otherwise add it
  35781. * @param key the key to get the value from
  35782. * @param val if there's no such key/value pair in the dictionary add it with this value
  35783. * @return the value corresponding to the key
  35784. */
  35785. StringDictionary.prototype.getOrAdd = function (key, val) {
  35786. var curVal = this.get(key);
  35787. if (curVal !== undefined) {
  35788. return curVal;
  35789. }
  35790. this.add(key, val);
  35791. return val;
  35792. };
  35793. /**
  35794. * Check if there's a given key in the dictionary
  35795. * @param key the key to check for
  35796. * @return true if the key is present, false otherwise
  35797. */
  35798. StringDictionary.prototype.contains = function (key) {
  35799. return this._data[key] !== undefined;
  35800. };
  35801. /**
  35802. * Add a new key and its corresponding value
  35803. * @param key the key to add
  35804. * @param value the value corresponding to the key
  35805. * @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
  35806. */
  35807. StringDictionary.prototype.add = function (key, value) {
  35808. if (this._data[key] !== undefined) {
  35809. return false;
  35810. }
  35811. this._data[key] = value;
  35812. ++this._count;
  35813. return true;
  35814. };
  35815. StringDictionary.prototype.set = function (key, value) {
  35816. if (this._data[key] === undefined) {
  35817. return false;
  35818. }
  35819. this._data[key] = value;
  35820. return true;
  35821. };
  35822. /**
  35823. * Get the element of the given key and remove it from the dictionary
  35824. * @param key
  35825. */
  35826. StringDictionary.prototype.getAndRemove = function (key) {
  35827. var val = this.get(key);
  35828. if (val !== undefined) {
  35829. delete this._data[key];
  35830. --this._count;
  35831. return val;
  35832. }
  35833. return null;
  35834. };
  35835. /**
  35836. * Remove a key/value from the dictionary.
  35837. * @param key the key to remove
  35838. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  35839. */
  35840. StringDictionary.prototype.remove = function (key) {
  35841. if (this.contains(key)) {
  35842. delete this._data[key];
  35843. --this._count;
  35844. return true;
  35845. }
  35846. return false;
  35847. };
  35848. /**
  35849. * Clear the whole content of the dictionary
  35850. */
  35851. StringDictionary.prototype.clear = function () {
  35852. this._data = {};
  35853. this._count = 0;
  35854. };
  35855. Object.defineProperty(StringDictionary.prototype, "count", {
  35856. get: function () {
  35857. return this._count;
  35858. },
  35859. enumerable: true,
  35860. configurable: true
  35861. });
  35862. /**
  35863. * Execute a callback on each key/val of the dictionary.
  35864. * Note that you can remove any element in this dictionary in the callback implementation
  35865. * @param callback the callback to execute on a given key/value pair
  35866. */
  35867. StringDictionary.prototype.forEach = function (callback) {
  35868. for (var cur in this._data) {
  35869. var val = this._data[cur];
  35870. callback(cur, val);
  35871. }
  35872. };
  35873. /**
  35874. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  35875. * If the callback returns null or undefined the method will iterate to the next key/value pair
  35876. * Note that you can remove any element in this dictionary in the callback implementation
  35877. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  35878. */
  35879. StringDictionary.prototype.first = function (callback) {
  35880. for (var cur in this._data) {
  35881. var val = this._data[cur];
  35882. var res = callback(cur, val);
  35883. if (res) {
  35884. return res;
  35885. }
  35886. }
  35887. return null;
  35888. };
  35889. return StringDictionary;
  35890. }());
  35891. BABYLON.StringDictionary = StringDictionary;
  35892. })(BABYLON || (BABYLON = {}));
  35893. //# sourceMappingURL=babylon.stringDictionary.js.map
  35894. var BABYLON;
  35895. (function (BABYLON) {
  35896. var DynamicFloatArrayElementInfo = (function () {
  35897. function DynamicFloatArrayElementInfo() {
  35898. }
  35899. return DynamicFloatArrayElementInfo;
  35900. }());
  35901. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  35902. /**
  35903. * 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.
  35904. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  35905. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  35906. * 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.
  35907. * 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.
  35908. * 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".
  35909. */
  35910. var DynamicFloatArray = (function () {
  35911. /**
  35912. * Construct an instance of the dynamic float array
  35913. * @param stride size of one element in float (i.e. not bytes!)
  35914. * @param initialElementCount the number of available entries at construction
  35915. */
  35916. function DynamicFloatArray(stride, initialElementCount) {
  35917. this.compareValueOffset = null;
  35918. this.sortingAscending = true;
  35919. this._stride = stride;
  35920. this.buffer = new Float32Array(stride * initialElementCount);
  35921. this._lastUsed = 0;
  35922. this._firstFree = 0;
  35923. this._allEntries = new Array(initialElementCount);
  35924. this._freeEntries = new Array(initialElementCount);
  35925. for (var i = 0; i < initialElementCount; i++) {
  35926. var element = new DynamicFloatArrayElementInfo();
  35927. element.offset = i * stride;
  35928. this._allEntries[i] = element;
  35929. this._freeEntries[initialElementCount - i - 1] = element;
  35930. }
  35931. }
  35932. /**
  35933. * Allocate an element in the array.
  35934. * @return the element info instance that contains the offset into the main buffer of the element's location.
  35935. * Beware, this offset may change when you call pack()
  35936. */
  35937. DynamicFloatArray.prototype.allocElement = function () {
  35938. if (this._freeEntries.length === 0) {
  35939. this._growBuffer();
  35940. }
  35941. var el = this._freeEntries.pop();
  35942. this._lastUsed = Math.max(el.offset, this._lastUsed);
  35943. if (el.offset === this._firstFree) {
  35944. if (this._freeEntries.length > 0) {
  35945. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  35946. }
  35947. else {
  35948. this._firstFree += this._stride;
  35949. }
  35950. }
  35951. return el;
  35952. };
  35953. /**
  35954. * Free the element corresponding to the given element info
  35955. * @param elInfo the element that describe the allocated element
  35956. */
  35957. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  35958. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  35959. this._freeEntries.push(elInfo);
  35960. };
  35961. /**
  35962. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  35963. * 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().
  35964. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  35965. */
  35966. DynamicFloatArray.prototype.pack = function () {
  35967. // no free slot? no need to pack
  35968. if (this._freeEntries.length === 0) {
  35969. return this.buffer;
  35970. }
  35971. // If the buffer is already packed the last used will always be lower than the first free
  35972. // 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.
  35973. if (this._lastUsed < this._firstFree) {
  35974. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  35975. return elementsBuffer_1;
  35976. }
  35977. var s = this._stride;
  35978. // 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
  35979. var lastFree = new DynamicFloatArrayElementInfo();
  35980. lastFree.offset = this.totalElementCount * s;
  35981. this._freeEntries.push(lastFree);
  35982. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  35983. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  35984. var firstFreeSlotOffset = sortedFree[0].offset;
  35985. var freeZoneSize = 1;
  35986. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  35987. var prevOffset = sortedFree[0].offset;
  35988. for (var i = 1; i < sortedFree.length; i++) {
  35989. // 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
  35990. if (firstFreeSlotOffset >= occupiedZoneSize) {
  35991. break;
  35992. }
  35993. var curFree = sortedFree[i];
  35994. var curOffset = curFree.offset;
  35995. // Compute the distance between this offset and the previous
  35996. var distance = curOffset - prevOffset;
  35997. // If the distance is the stride size, they are adjacent, it good, move to the next
  35998. if (distance === s) {
  35999. // Free zone is one element bigger
  36000. ++freeZoneSize;
  36001. // as we're about to iterate to the next, the cur becomes the previous...
  36002. prevOffset = curOffset;
  36003. continue;
  36004. }
  36005. // Distance is bigger, which means there's x element between the previous free and this one
  36006. var usedRange = (distance / s) - 1;
  36007. // Two cases the free zone is smaller than the data to move or bigger
  36008. // Copy what can fit in the free zone
  36009. var curMoveOffset = curOffset - s;
  36010. var copyCount = Math.min(freeZoneSize, usedRange);
  36011. for (var j = 0; j < copyCount; j++) {
  36012. var freeI = firstFreeSlotOffset / s;
  36013. var curI = curMoveOffset / s;
  36014. var moveEl = sortedAll[curI];
  36015. this._moveElement(moveEl, firstFreeSlotOffset);
  36016. var replacedEl = sortedAll[freeI];
  36017. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  36018. replacedEl.offset = curMoveOffset;
  36019. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  36020. sortedAll[freeI] = moveEl;
  36021. sortedAll[curI] = replacedEl;
  36022. curMoveOffset -= s;
  36023. firstFreeSlotOffset += s;
  36024. }
  36025. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  36026. if (freeZoneSize <= usedRange) {
  36027. firstFreeSlotOffset = curMoveOffset + s;
  36028. freeZoneSize = 1 + copyCount;
  36029. }
  36030. else {
  36031. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  36032. }
  36033. // as we're about to iterate to the next, the cur becomes the previous...
  36034. prevOffset = curOffset;
  36035. }
  36036. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  36037. this._lastUsed = firstFreeSlotOffset - s;
  36038. this._firstFree = firstFreeSlotOffset;
  36039. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  36040. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  36041. this._allEntries = sortedAll;
  36042. return elementsBuffer;
  36043. };
  36044. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  36045. for (var i = 0; i < this._stride; i++) {
  36046. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  36047. }
  36048. element.offset = destOffset;
  36049. };
  36050. DynamicFloatArray.prototype._growBuffer = function () {
  36051. // Allocate the new buffer with 50% more entries, copy the content of the current one
  36052. var newElCount = Math.floor(this.totalElementCount * 1.5);
  36053. var newBuffer = new Float32Array(newElCount * this._stride);
  36054. newBuffer.set(this.buffer);
  36055. var curCount = this.totalElementCount;
  36056. var addedCount = newElCount - this.totalElementCount;
  36057. for (var i = 0; i < addedCount; i++) {
  36058. var element = new DynamicFloatArrayElementInfo();
  36059. element.offset = (curCount + i) * this.stride;
  36060. this._allEntries.push(element);
  36061. this._freeEntries[addedCount - i - 1] = element;
  36062. }
  36063. this._firstFree = curCount * this.stride;
  36064. this.buffer = newBuffer;
  36065. };
  36066. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  36067. /**
  36068. * Get the total count of entries that can fit in the current buffer
  36069. * @returns the elements count
  36070. */
  36071. get: function () {
  36072. return this._allEntries.length;
  36073. },
  36074. enumerable: true,
  36075. configurable: true
  36076. });
  36077. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  36078. /**
  36079. * Get the count of free entries that can still be allocated without resizing the buffer
  36080. * @returns the free elements count
  36081. */
  36082. get: function () {
  36083. return this._freeEntries.length;
  36084. },
  36085. enumerable: true,
  36086. configurable: true
  36087. });
  36088. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  36089. /**
  36090. * Get the count of allocated elements
  36091. * @returns the allocated elements count
  36092. */
  36093. get: function () {
  36094. return this._allEntries.length - this._freeEntries.length;
  36095. },
  36096. enumerable: true,
  36097. configurable: true
  36098. });
  36099. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  36100. /**
  36101. * Return the size of one element in float
  36102. * @returns the size in float
  36103. */
  36104. get: function () {
  36105. return this._stride;
  36106. },
  36107. enumerable: true,
  36108. configurable: true
  36109. });
  36110. DynamicFloatArray.prototype.sort = function () {
  36111. var _this = this;
  36112. if (!this.compareValueOffset) {
  36113. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  36114. }
  36115. var count = this.usedElementCount;
  36116. // Do we have to (re)create the sort table?
  36117. if (!this._sortTable || this._sortTable.length < count) {
  36118. // 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...
  36119. var newCount = Math.min(this.totalElementCount, count * 2);
  36120. this._sortTable = new Array(newCount);
  36121. }
  36122. if (!this._sortedTable || this._sortedTable.length !== count) {
  36123. this._sortedTable = new Array(count);
  36124. }
  36125. // Because, you know...
  36126. this.pack();
  36127. //let stride = this.stride;
  36128. //for (let i = 0; i < count; i++) {
  36129. // let si = this._sortTable[i];
  36130. // if (!si) {
  36131. // si = new SortInfo();
  36132. // this._sortTable[i] = si;
  36133. // }
  36134. // si.entry = this._allEntries[i];
  36135. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  36136. // si.swapedOffset = null;
  36137. // this._sortedTable[i] = si;
  36138. //}
  36139. var curOffset = 0;
  36140. var stride = this.stride;
  36141. for (var i = 0; i < count; i++, curOffset += stride) {
  36142. var si = this._sortTable[i];
  36143. if (!si) {
  36144. si = new SortInfo();
  36145. this._sortTable[i] = si;
  36146. }
  36147. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  36148. si.offset = curOffset;
  36149. si.swapedOffset = null;
  36150. this._sortedTable[i] = si;
  36151. }
  36152. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  36153. if (this.sortingAscending) {
  36154. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  36155. }
  36156. else {
  36157. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  36158. }
  36159. var swapElements = function (src, dst) {
  36160. for (var i = 0; i < stride; i++) {
  36161. var tps = _this.buffer[dst + i];
  36162. _this.buffer[dst + i] = _this.buffer[src + i];
  36163. _this.buffer[src + i] = tps;
  36164. }
  36165. };
  36166. // 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:
  36167. // 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),
  36168. // and I still want something with a good algorithm complexity.
  36169. // 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,
  36170. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  36171. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  36172. // 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
  36173. // until we find a SortInfo object without a swapedOffset which means we got the right location
  36174. // 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
  36175. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  36176. for (var i = 0; i < count; i++) {
  36177. // Get the element to move
  36178. var sourceSI = this._sortedTable[i];
  36179. var destSI = this._sortTable[i];
  36180. var sourceOff = sourceSI.offset;
  36181. // If the source changed location, find the new one
  36182. if (sourceSI.swapedOffset) {
  36183. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  36184. var curSI = sourceSI;
  36185. while (curSI.swapedOffset) {
  36186. curSI = this._sortTable[curSI.swapedOffset / stride];
  36187. }
  36188. // Finally get the right location
  36189. sourceOff = curSI.offset;
  36190. }
  36191. // Tag the element being replaced with its new location
  36192. destSI.swapedOffset = sourceOff;
  36193. // Swap elements (only if needed)
  36194. if (sourceOff !== destSI.offset) {
  36195. swapElements(sourceOff, destSI.offset);
  36196. }
  36197. // Update the offset in the corresponding DFAE
  36198. //sourceSI.entry.offset = destSI.entry.offset;
  36199. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  36200. }
  36201. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36202. return true;
  36203. };
  36204. return DynamicFloatArray;
  36205. }());
  36206. BABYLON.DynamicFloatArray = DynamicFloatArray;
  36207. var SortInfo = (function () {
  36208. function SortInfo() {
  36209. this.compareData = this.offset = this.swapedOffset = null;
  36210. }
  36211. return SortInfo;
  36212. }());
  36213. })(BABYLON || (BABYLON = {}));
  36214. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  36215. var BABYLON;
  36216. (function (BABYLON) {
  36217. var Condition = (function () {
  36218. function Condition(actionManager) {
  36219. this._actionManager = actionManager;
  36220. }
  36221. Condition.prototype.isValid = function () {
  36222. return true;
  36223. };
  36224. Condition.prototype._getProperty = function (propertyPath) {
  36225. return this._actionManager._getProperty(propertyPath);
  36226. };
  36227. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  36228. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36229. };
  36230. Condition.prototype.serialize = function () {
  36231. };
  36232. Condition.prototype._serialize = function (serializedCondition) {
  36233. return {
  36234. type: 2,
  36235. children: [],
  36236. name: serializedCondition.name,
  36237. properties: serializedCondition.properties
  36238. };
  36239. };
  36240. return Condition;
  36241. }());
  36242. BABYLON.Condition = Condition;
  36243. var ValueCondition = (function (_super) {
  36244. __extends(ValueCondition, _super);
  36245. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  36246. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  36247. var _this = _super.call(this, actionManager) || this;
  36248. _this.propertyPath = propertyPath;
  36249. _this.value = value;
  36250. _this.operator = operator;
  36251. _this._target = target;
  36252. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  36253. _this._property = _this._getProperty(_this.propertyPath);
  36254. return _this;
  36255. }
  36256. Object.defineProperty(ValueCondition, "IsEqual", {
  36257. get: function () {
  36258. return ValueCondition._IsEqual;
  36259. },
  36260. enumerable: true,
  36261. configurable: true
  36262. });
  36263. Object.defineProperty(ValueCondition, "IsDifferent", {
  36264. get: function () {
  36265. return ValueCondition._IsDifferent;
  36266. },
  36267. enumerable: true,
  36268. configurable: true
  36269. });
  36270. Object.defineProperty(ValueCondition, "IsGreater", {
  36271. get: function () {
  36272. return ValueCondition._IsGreater;
  36273. },
  36274. enumerable: true,
  36275. configurable: true
  36276. });
  36277. Object.defineProperty(ValueCondition, "IsLesser", {
  36278. get: function () {
  36279. return ValueCondition._IsLesser;
  36280. },
  36281. enumerable: true,
  36282. configurable: true
  36283. });
  36284. // Methods
  36285. ValueCondition.prototype.isValid = function () {
  36286. switch (this.operator) {
  36287. case ValueCondition.IsGreater:
  36288. return this._effectiveTarget[this._property] > this.value;
  36289. case ValueCondition.IsLesser:
  36290. return this._effectiveTarget[this._property] < this.value;
  36291. case ValueCondition.IsEqual:
  36292. case ValueCondition.IsDifferent:
  36293. var check;
  36294. if (this.value.equals) {
  36295. check = this.value.equals(this._effectiveTarget[this._property]);
  36296. }
  36297. else {
  36298. check = this.value === this._effectiveTarget[this._property];
  36299. }
  36300. return this.operator === ValueCondition.IsEqual ? check : !check;
  36301. }
  36302. return false;
  36303. };
  36304. ValueCondition.prototype.serialize = function () {
  36305. return this._serialize({
  36306. name: "ValueCondition",
  36307. properties: [
  36308. BABYLON.Action._GetTargetProperty(this._target),
  36309. { name: "propertyPath", value: this.propertyPath },
  36310. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36311. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  36312. ]
  36313. });
  36314. };
  36315. ValueCondition.GetOperatorName = function (operator) {
  36316. switch (operator) {
  36317. case ValueCondition._IsEqual: return "IsEqual";
  36318. case ValueCondition._IsDifferent: return "IsDifferent";
  36319. case ValueCondition._IsGreater: return "IsGreater";
  36320. case ValueCondition._IsLesser: return "IsLesser";
  36321. default: return "";
  36322. }
  36323. };
  36324. return ValueCondition;
  36325. }(Condition));
  36326. // Statics
  36327. ValueCondition._IsEqual = 0;
  36328. ValueCondition._IsDifferent = 1;
  36329. ValueCondition._IsGreater = 2;
  36330. ValueCondition._IsLesser = 3;
  36331. BABYLON.ValueCondition = ValueCondition;
  36332. var PredicateCondition = (function (_super) {
  36333. __extends(PredicateCondition, _super);
  36334. function PredicateCondition(actionManager, predicate) {
  36335. var _this = _super.call(this, actionManager) || this;
  36336. _this.predicate = predicate;
  36337. return _this;
  36338. }
  36339. PredicateCondition.prototype.isValid = function () {
  36340. return this.predicate();
  36341. };
  36342. return PredicateCondition;
  36343. }(Condition));
  36344. BABYLON.PredicateCondition = PredicateCondition;
  36345. var StateCondition = (function (_super) {
  36346. __extends(StateCondition, _super);
  36347. function StateCondition(actionManager, target, value) {
  36348. var _this = _super.call(this, actionManager) || this;
  36349. _this.value = value;
  36350. _this._target = target;
  36351. return _this;
  36352. }
  36353. // Methods
  36354. StateCondition.prototype.isValid = function () {
  36355. return this._target.state === this.value;
  36356. };
  36357. StateCondition.prototype.serialize = function () {
  36358. return this._serialize({
  36359. name: "StateCondition",
  36360. properties: [
  36361. BABYLON.Action._GetTargetProperty(this._target),
  36362. { name: "value", value: this.value }
  36363. ]
  36364. });
  36365. };
  36366. return StateCondition;
  36367. }(Condition));
  36368. BABYLON.StateCondition = StateCondition;
  36369. })(BABYLON || (BABYLON = {}));
  36370. //# sourceMappingURL=babylon.condition.js.map
  36371. var BABYLON;
  36372. (function (BABYLON) {
  36373. var Action = (function () {
  36374. function Action(triggerOptions, condition) {
  36375. this.triggerOptions = triggerOptions;
  36376. if (triggerOptions.parameter) {
  36377. this.trigger = triggerOptions.trigger;
  36378. this._triggerParameter = triggerOptions.parameter;
  36379. }
  36380. else {
  36381. this.trigger = triggerOptions;
  36382. }
  36383. this._nextActiveAction = this;
  36384. this._condition = condition;
  36385. }
  36386. // Methods
  36387. Action.prototype._prepare = function () {
  36388. };
  36389. Action.prototype.getTriggerParameter = function () {
  36390. return this._triggerParameter;
  36391. };
  36392. Action.prototype._executeCurrent = function (evt) {
  36393. if (this._nextActiveAction._condition) {
  36394. var condition = this._nextActiveAction._condition;
  36395. var currentRenderId = this._actionManager.getScene().getRenderId();
  36396. // We cache the current evaluation for the current frame
  36397. if (condition._evaluationId === currentRenderId) {
  36398. if (!condition._currentResult) {
  36399. return;
  36400. }
  36401. }
  36402. else {
  36403. condition._evaluationId = currentRenderId;
  36404. if (!condition.isValid()) {
  36405. condition._currentResult = false;
  36406. return;
  36407. }
  36408. condition._currentResult = true;
  36409. }
  36410. }
  36411. this._nextActiveAction.execute(evt);
  36412. this.skipToNextActiveAction();
  36413. };
  36414. Action.prototype.execute = function (evt) {
  36415. };
  36416. Action.prototype.skipToNextActiveAction = function () {
  36417. if (this._nextActiveAction._child) {
  36418. if (!this._nextActiveAction._child._actionManager) {
  36419. this._nextActiveAction._child._actionManager = this._actionManager;
  36420. }
  36421. this._nextActiveAction = this._nextActiveAction._child;
  36422. }
  36423. else {
  36424. this._nextActiveAction = this;
  36425. }
  36426. };
  36427. Action.prototype.then = function (action) {
  36428. this._child = action;
  36429. action._actionManager = this._actionManager;
  36430. action._prepare();
  36431. return action;
  36432. };
  36433. Action.prototype._getProperty = function (propertyPath) {
  36434. return this._actionManager._getProperty(propertyPath);
  36435. };
  36436. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  36437. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36438. };
  36439. Action.prototype.serialize = function (parent) {
  36440. };
  36441. // Called by BABYLON.Action objects in serialize(...). Internal use
  36442. Action.prototype._serialize = function (serializedAction, parent) {
  36443. var serializationObject = {
  36444. type: 1,
  36445. children: [],
  36446. name: serializedAction.name,
  36447. properties: serializedAction.properties || []
  36448. };
  36449. // Serialize child
  36450. if (this._child) {
  36451. this._child.serialize(serializationObject);
  36452. }
  36453. // Check if "this" has a condition
  36454. if (this._condition) {
  36455. var serializedCondition = this._condition.serialize();
  36456. serializedCondition.children.push(serializationObject);
  36457. if (parent) {
  36458. parent.children.push(serializedCondition);
  36459. }
  36460. return serializedCondition;
  36461. }
  36462. if (parent) {
  36463. parent.children.push(serializationObject);
  36464. }
  36465. return serializationObject;
  36466. };
  36467. return Action;
  36468. }());
  36469. Action._SerializeValueAsString = function (value) {
  36470. if (typeof value === "number") {
  36471. return value.toString();
  36472. }
  36473. if (typeof value === "boolean") {
  36474. return value ? "true" : "false";
  36475. }
  36476. if (value instanceof BABYLON.Vector2) {
  36477. return value.x + ", " + value.y;
  36478. }
  36479. if (value instanceof BABYLON.Vector3) {
  36480. return value.x + ", " + value.y + ", " + value.z;
  36481. }
  36482. if (value instanceof BABYLON.Color3) {
  36483. return value.r + ", " + value.g + ", " + value.b;
  36484. }
  36485. if (value instanceof BABYLON.Color4) {
  36486. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36487. }
  36488. return value; // string
  36489. };
  36490. Action._GetTargetProperty = function (target) {
  36491. return {
  36492. name: "target",
  36493. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36494. : target instanceof BABYLON.Light ? "LightProperties"
  36495. : target instanceof BABYLON.Camera ? "CameraProperties"
  36496. : "SceneProperties",
  36497. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36498. };
  36499. };
  36500. BABYLON.Action = Action;
  36501. })(BABYLON || (BABYLON = {}));
  36502. //# sourceMappingURL=babylon.action.js.map
  36503. var BABYLON;
  36504. (function (BABYLON) {
  36505. /**
  36506. * ActionEvent is the event beint sent when an action is triggered.
  36507. */
  36508. var ActionEvent = (function () {
  36509. /**
  36510. * @constructor
  36511. * @param source The mesh or sprite that triggered the action.
  36512. * @param pointerX The X mouse cursor position at the time of the event
  36513. * @param pointerY The Y mouse cursor position at the time of the event
  36514. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36515. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36516. */
  36517. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36518. this.source = source;
  36519. this.pointerX = pointerX;
  36520. this.pointerY = pointerY;
  36521. this.meshUnderPointer = meshUnderPointer;
  36522. this.sourceEvent = sourceEvent;
  36523. this.additionalData = additionalData;
  36524. }
  36525. /**
  36526. * Helper function to auto-create an ActionEvent from a source mesh.
  36527. * @param source The source mesh that triggered the event
  36528. * @param evt {Event} The original (browser) event
  36529. */
  36530. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36531. var scene = source.getScene();
  36532. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36533. };
  36534. /**
  36535. * Helper function to auto-create an ActionEvent from a source mesh.
  36536. * @param source The source sprite that triggered the event
  36537. * @param scene Scene associated with the sprite
  36538. * @param evt {Event} The original (browser) event
  36539. */
  36540. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36541. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36542. };
  36543. /**
  36544. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36545. * @param scene the scene where the event occurred
  36546. * @param evt {Event} The original (browser) event
  36547. */
  36548. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36549. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36550. };
  36551. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36552. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36553. };
  36554. return ActionEvent;
  36555. }());
  36556. BABYLON.ActionEvent = ActionEvent;
  36557. /**
  36558. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36559. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36560. */
  36561. var ActionManager = (function () {
  36562. function ActionManager(scene) {
  36563. // Members
  36564. this.actions = new Array();
  36565. this.hoverCursor = '';
  36566. this._scene = scene;
  36567. scene._actionManagers.push(this);
  36568. }
  36569. Object.defineProperty(ActionManager, "NothingTrigger", {
  36570. get: function () {
  36571. return ActionManager._NothingTrigger;
  36572. },
  36573. enumerable: true,
  36574. configurable: true
  36575. });
  36576. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36577. get: function () {
  36578. return ActionManager._OnPickTrigger;
  36579. },
  36580. enumerable: true,
  36581. configurable: true
  36582. });
  36583. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36584. get: function () {
  36585. return ActionManager._OnLeftPickTrigger;
  36586. },
  36587. enumerable: true,
  36588. configurable: true
  36589. });
  36590. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36591. get: function () {
  36592. return ActionManager._OnRightPickTrigger;
  36593. },
  36594. enumerable: true,
  36595. configurable: true
  36596. });
  36597. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36598. get: function () {
  36599. return ActionManager._OnCenterPickTrigger;
  36600. },
  36601. enumerable: true,
  36602. configurable: true
  36603. });
  36604. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36605. get: function () {
  36606. return ActionManager._OnPickDownTrigger;
  36607. },
  36608. enumerable: true,
  36609. configurable: true
  36610. });
  36611. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  36612. get: function () {
  36613. return ActionManager._OnDoublePickTrigger;
  36614. },
  36615. enumerable: true,
  36616. configurable: true
  36617. });
  36618. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36619. get: function () {
  36620. return ActionManager._OnPickUpTrigger;
  36621. },
  36622. enumerable: true,
  36623. configurable: true
  36624. });
  36625. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36626. /// This trigger will only be raised if you also declared a OnPickDown
  36627. get: function () {
  36628. return ActionManager._OnPickOutTrigger;
  36629. },
  36630. enumerable: true,
  36631. configurable: true
  36632. });
  36633. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36634. get: function () {
  36635. return ActionManager._OnLongPressTrigger;
  36636. },
  36637. enumerable: true,
  36638. configurable: true
  36639. });
  36640. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36641. get: function () {
  36642. return ActionManager._OnPointerOverTrigger;
  36643. },
  36644. enumerable: true,
  36645. configurable: true
  36646. });
  36647. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36648. get: function () {
  36649. return ActionManager._OnPointerOutTrigger;
  36650. },
  36651. enumerable: true,
  36652. configurable: true
  36653. });
  36654. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36655. get: function () {
  36656. return ActionManager._OnEveryFrameTrigger;
  36657. },
  36658. enumerable: true,
  36659. configurable: true
  36660. });
  36661. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36662. get: function () {
  36663. return ActionManager._OnIntersectionEnterTrigger;
  36664. },
  36665. enumerable: true,
  36666. configurable: true
  36667. });
  36668. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36669. get: function () {
  36670. return ActionManager._OnIntersectionExitTrigger;
  36671. },
  36672. enumerable: true,
  36673. configurable: true
  36674. });
  36675. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36676. get: function () {
  36677. return ActionManager._OnKeyDownTrigger;
  36678. },
  36679. enumerable: true,
  36680. configurable: true
  36681. });
  36682. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36683. get: function () {
  36684. return ActionManager._OnKeyUpTrigger;
  36685. },
  36686. enumerable: true,
  36687. configurable: true
  36688. });
  36689. // Methods
  36690. ActionManager.prototype.dispose = function () {
  36691. var index = this._scene._actionManagers.indexOf(this);
  36692. for (var i = 0; i < this.actions.length; i++) {
  36693. var action = this.actions[i];
  36694. ActionManager.Triggers[action.trigger]--;
  36695. if (ActionManager.Triggers[action.trigger] === 0) {
  36696. delete ActionManager.Triggers[action.trigger];
  36697. }
  36698. }
  36699. if (index > -1) {
  36700. this._scene._actionManagers.splice(index, 1);
  36701. }
  36702. };
  36703. ActionManager.prototype.getScene = function () {
  36704. return this._scene;
  36705. };
  36706. /**
  36707. * Does this action manager handles actions of any of the given triggers
  36708. * @param {number[]} triggers - the triggers to be tested
  36709. * @return {boolean} whether one (or more) of the triggers is handeled
  36710. */
  36711. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36712. for (var index = 0; index < this.actions.length; index++) {
  36713. var action = this.actions[index];
  36714. if (triggers.indexOf(action.trigger) > -1) {
  36715. return true;
  36716. }
  36717. }
  36718. return false;
  36719. };
  36720. /**
  36721. * Does this action manager handles actions of a given trigger
  36722. * @param {number} trigger - the trigger to be tested
  36723. * @return {boolean} whether the trigger is handeled
  36724. */
  36725. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36726. for (var index = 0; index < this.actions.length; index++) {
  36727. var action = this.actions[index];
  36728. if (action.trigger === trigger) {
  36729. return true;
  36730. }
  36731. }
  36732. return false;
  36733. };
  36734. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36735. /**
  36736. * Does this action manager has pointer triggers
  36737. * @return {boolean} whether or not it has pointer triggers
  36738. */
  36739. get: function () {
  36740. for (var index = 0; index < this.actions.length; index++) {
  36741. var action = this.actions[index];
  36742. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36743. return true;
  36744. }
  36745. }
  36746. return false;
  36747. },
  36748. enumerable: true,
  36749. configurable: true
  36750. });
  36751. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36752. /**
  36753. * Does this action manager has pick triggers
  36754. * @return {boolean} whether or not it has pick triggers
  36755. */
  36756. get: function () {
  36757. for (var index = 0; index < this.actions.length; index++) {
  36758. var action = this.actions[index];
  36759. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36760. return true;
  36761. }
  36762. }
  36763. return false;
  36764. },
  36765. enumerable: true,
  36766. configurable: true
  36767. });
  36768. Object.defineProperty(ActionManager, "HasTriggers", {
  36769. /**
  36770. * Does exist one action manager with at least one trigger
  36771. * @return {boolean} whether or not it exists one action manager with one trigger
  36772. **/
  36773. get: function () {
  36774. for (var t in ActionManager.Triggers) {
  36775. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36776. return true;
  36777. }
  36778. }
  36779. return false;
  36780. },
  36781. enumerable: true,
  36782. configurable: true
  36783. });
  36784. Object.defineProperty(ActionManager, "HasPickTriggers", {
  36785. /**
  36786. * Does exist one action manager with at least one pick trigger
  36787. * @return {boolean} whether or not it exists one action manager with one pick trigger
  36788. **/
  36789. get: function () {
  36790. for (var t in ActionManager.Triggers) {
  36791. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36792. var t_int = parseInt(t);
  36793. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  36794. return true;
  36795. }
  36796. }
  36797. }
  36798. return false;
  36799. },
  36800. enumerable: true,
  36801. configurable: true
  36802. });
  36803. /**
  36804. * Does exist one action manager that handles actions of a given trigger
  36805. * @param {number} trigger - the trigger to be tested
  36806. * @return {boolean} whether the trigger is handeled by at least one action manager
  36807. **/
  36808. ActionManager.HasSpecificTrigger = function (trigger) {
  36809. for (var t in ActionManager.Triggers) {
  36810. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36811. var t_int = parseInt(t);
  36812. if (t_int === trigger) {
  36813. return true;
  36814. }
  36815. }
  36816. }
  36817. return false;
  36818. };
  36819. /**
  36820. * Registers an action to this action manager
  36821. * @param {BABYLON.Action} action - the action to be registered
  36822. * @return {BABYLON.Action} the action amended (prepared) after registration
  36823. */
  36824. ActionManager.prototype.registerAction = function (action) {
  36825. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36826. if (this.getScene().actionManager !== this) {
  36827. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36828. return null;
  36829. }
  36830. }
  36831. this.actions.push(action);
  36832. if (ActionManager.Triggers[action.trigger]) {
  36833. ActionManager.Triggers[action.trigger]++;
  36834. }
  36835. else {
  36836. ActionManager.Triggers[action.trigger] = 1;
  36837. }
  36838. action._actionManager = this;
  36839. action._prepare();
  36840. return action;
  36841. };
  36842. /**
  36843. * Process a specific trigger
  36844. * @param {number} trigger - the trigger to process
  36845. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36846. */
  36847. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36848. for (var index = 0; index < this.actions.length; index++) {
  36849. var action = this.actions[index];
  36850. if (action.trigger === trigger) {
  36851. if (trigger === ActionManager.OnKeyUpTrigger
  36852. || trigger === ActionManager.OnKeyDownTrigger) {
  36853. var parameter = action.getTriggerParameter();
  36854. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  36855. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36856. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36857. if (actualkey !== parameter.toLowerCase()) {
  36858. continue;
  36859. }
  36860. }
  36861. }
  36862. action._executeCurrent(evt);
  36863. }
  36864. }
  36865. };
  36866. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36867. var properties = propertyPath.split(".");
  36868. for (var index = 0; index < properties.length - 1; index++) {
  36869. target = target[properties[index]];
  36870. }
  36871. return target;
  36872. };
  36873. ActionManager.prototype._getProperty = function (propertyPath) {
  36874. var properties = propertyPath.split(".");
  36875. return properties[properties.length - 1];
  36876. };
  36877. ActionManager.prototype.serialize = function (name) {
  36878. var root = {
  36879. children: [],
  36880. name: name,
  36881. type: 3,
  36882. properties: [] // Empty for root but required
  36883. };
  36884. for (var i = 0; i < this.actions.length; i++) {
  36885. var triggerObject = {
  36886. type: 0,
  36887. children: [],
  36888. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36889. properties: []
  36890. };
  36891. var triggerOptions = this.actions[i].triggerOptions;
  36892. if (triggerOptions && typeof triggerOptions !== "number") {
  36893. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36894. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36895. }
  36896. else {
  36897. var parameter = {};
  36898. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36899. if (triggerOptions.parameter.mesh) {
  36900. parameter._meshId = triggerOptions.parameter.mesh.id;
  36901. }
  36902. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36903. }
  36904. }
  36905. // Serialize child action, recursively
  36906. this.actions[i].serialize(triggerObject);
  36907. // Add serialized trigger
  36908. root.children.push(triggerObject);
  36909. }
  36910. return root;
  36911. };
  36912. ActionManager.Parse = function (parsedActions, object, scene) {
  36913. var actionManager = new BABYLON.ActionManager(scene);
  36914. if (object === null)
  36915. scene.actionManager = actionManager;
  36916. else
  36917. object.actionManager = actionManager;
  36918. // instanciate a new object
  36919. var instanciate = function (name, params) {
  36920. var newInstance = Object.create(BABYLON[name].prototype);
  36921. newInstance.constructor.apply(newInstance, params);
  36922. return newInstance;
  36923. };
  36924. var parseParameter = function (name, value, target, propertyPath) {
  36925. if (propertyPath === null) {
  36926. // String, boolean or float
  36927. var floatValue = parseFloat(value);
  36928. if (value === "true" || value === "false")
  36929. return value === "true";
  36930. else
  36931. return isNaN(floatValue) ? value : floatValue;
  36932. }
  36933. var effectiveTarget = propertyPath.split(".");
  36934. var values = value.split(",");
  36935. // Get effective Target
  36936. for (var i = 0; i < effectiveTarget.length; i++) {
  36937. target = target[effectiveTarget[i]];
  36938. }
  36939. // Return appropriate value with its type
  36940. if (typeof (target) === "boolean")
  36941. return values[0] === "true";
  36942. if (typeof (target) === "string")
  36943. return values[0];
  36944. // Parameters with multiple values such as Vector3 etc.
  36945. var split = new Array();
  36946. for (var i = 0; i < values.length; i++)
  36947. split.push(parseFloat(values[i]));
  36948. if (target instanceof BABYLON.Vector3)
  36949. return BABYLON.Vector3.FromArray(split);
  36950. if (target instanceof BABYLON.Vector4)
  36951. return BABYLON.Vector4.FromArray(split);
  36952. if (target instanceof BABYLON.Color3)
  36953. return BABYLON.Color3.FromArray(split);
  36954. if (target instanceof BABYLON.Color4)
  36955. return BABYLON.Color4.FromArray(split);
  36956. return parseFloat(values[0]);
  36957. };
  36958. // traverse graph per trigger
  36959. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  36960. if (combineArray === void 0) { combineArray = null; }
  36961. if (parsedAction.detached)
  36962. return;
  36963. var parameters = new Array();
  36964. var target = null;
  36965. var propertyPath = null;
  36966. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  36967. // Parameters
  36968. if (parsedAction.type === 2)
  36969. parameters.push(actionManager);
  36970. else
  36971. parameters.push(trigger);
  36972. if (combine) {
  36973. var actions = new Array();
  36974. for (var j = 0; j < parsedAction.combine.length; j++) {
  36975. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  36976. }
  36977. parameters.push(actions);
  36978. }
  36979. else {
  36980. for (var i = 0; i < parsedAction.properties.length; i++) {
  36981. var value = parsedAction.properties[i].value;
  36982. var name = parsedAction.properties[i].name;
  36983. var targetType = parsedAction.properties[i].targetType;
  36984. if (name === "target")
  36985. if (targetType !== null && targetType === "SceneProperties")
  36986. value = target = scene;
  36987. else
  36988. value = target = scene.getNodeByName(value);
  36989. else if (name === "parent")
  36990. value = scene.getNodeByName(value);
  36991. else if (name === "sound")
  36992. value = scene.getSoundByName(value);
  36993. else if (name !== "propertyPath") {
  36994. if (parsedAction.type === 2 && name === "operator")
  36995. value = BABYLON.ValueCondition[value];
  36996. else
  36997. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  36998. }
  36999. else {
  37000. propertyPath = value;
  37001. }
  37002. parameters.push(value);
  37003. }
  37004. }
  37005. if (combineArray === null) {
  37006. parameters.push(condition);
  37007. }
  37008. else {
  37009. parameters.push(null);
  37010. }
  37011. // If interpolate value action
  37012. if (parsedAction.name === "InterpolateValueAction") {
  37013. var param = parameters[parameters.length - 2];
  37014. parameters[parameters.length - 1] = param;
  37015. parameters[parameters.length - 2] = condition;
  37016. }
  37017. // Action or condition(s) and not CombineAction
  37018. var newAction = instanciate(parsedAction.name, parameters);
  37019. if (newAction instanceof BABYLON.Condition && condition !== null) {
  37020. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  37021. if (action)
  37022. action.then(nothing);
  37023. else
  37024. actionManager.registerAction(nothing);
  37025. action = nothing;
  37026. }
  37027. if (combineArray === null) {
  37028. if (newAction instanceof BABYLON.Condition) {
  37029. condition = newAction;
  37030. newAction = action;
  37031. }
  37032. else {
  37033. condition = null;
  37034. if (action)
  37035. action.then(newAction);
  37036. else
  37037. actionManager.registerAction(newAction);
  37038. }
  37039. }
  37040. else {
  37041. combineArray.push(newAction);
  37042. }
  37043. for (var i = 0; i < parsedAction.children.length; i++)
  37044. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  37045. };
  37046. // triggers
  37047. for (var i = 0; i < parsedActions.children.length; i++) {
  37048. var triggerParams;
  37049. var trigger = parsedActions.children[i];
  37050. if (trigger.properties.length > 0) {
  37051. var param = trigger.properties[0].value;
  37052. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  37053. if (value._meshId) {
  37054. value.mesh = scene.getMeshByID(value._meshId);
  37055. }
  37056. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  37057. }
  37058. else
  37059. triggerParams = BABYLON.ActionManager[trigger.name];
  37060. for (var j = 0; j < trigger.children.length; j++) {
  37061. if (!trigger.detached)
  37062. traverse(trigger.children[j], triggerParams, null, null);
  37063. }
  37064. }
  37065. };
  37066. ActionManager.GetTriggerName = function (trigger) {
  37067. switch (trigger) {
  37068. case 0: return "NothingTrigger";
  37069. case 1: return "OnPickTrigger";
  37070. case 2: return "OnLeftPickTrigger";
  37071. case 3: return "OnRightPickTrigger";
  37072. case 4: return "OnCenterPickTrigger";
  37073. case 5: return "OnPickDownTrigger";
  37074. case 6: return "OnPickUpTrigger";
  37075. case 7: return "OnLongPressTrigger";
  37076. case 8: return "OnPointerOverTrigger";
  37077. case 9: return "OnPointerOutTrigger";
  37078. case 10: return "OnEveryFrameTrigger";
  37079. case 11: return "OnIntersectionEnterTrigger";
  37080. case 12: return "OnIntersectionExitTrigger";
  37081. case 13: return "OnKeyDownTrigger";
  37082. case 14: return "OnKeyUpTrigger";
  37083. case 15: return "OnPickOutTrigger";
  37084. default: return "";
  37085. }
  37086. };
  37087. return ActionManager;
  37088. }());
  37089. // Statics
  37090. ActionManager._NothingTrigger = 0;
  37091. ActionManager._OnPickTrigger = 1;
  37092. ActionManager._OnLeftPickTrigger = 2;
  37093. ActionManager._OnRightPickTrigger = 3;
  37094. ActionManager._OnCenterPickTrigger = 4;
  37095. ActionManager._OnPickDownTrigger = 5;
  37096. ActionManager._OnDoublePickTrigger = 6;
  37097. ActionManager._OnPickUpTrigger = 7;
  37098. ActionManager._OnLongPressTrigger = 8;
  37099. ActionManager._OnPointerOverTrigger = 9;
  37100. ActionManager._OnPointerOutTrigger = 10;
  37101. ActionManager._OnEveryFrameTrigger = 11;
  37102. ActionManager._OnIntersectionEnterTrigger = 12;
  37103. ActionManager._OnIntersectionExitTrigger = 13;
  37104. ActionManager._OnKeyDownTrigger = 14;
  37105. ActionManager._OnKeyUpTrigger = 15;
  37106. ActionManager._OnPickOutTrigger = 16;
  37107. ActionManager.Triggers = {};
  37108. BABYLON.ActionManager = ActionManager;
  37109. })(BABYLON || (BABYLON = {}));
  37110. //# sourceMappingURL=babylon.actionManager.js.map
  37111. var BABYLON;
  37112. (function (BABYLON) {
  37113. var InterpolateValueAction = (function (_super) {
  37114. __extends(InterpolateValueAction, _super);
  37115. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  37116. if (duration === void 0) { duration = 1000; }
  37117. var _this = _super.call(this, triggerOptions, condition) || this;
  37118. _this.propertyPath = propertyPath;
  37119. _this.value = value;
  37120. _this.duration = duration;
  37121. _this.stopOtherAnimations = stopOtherAnimations;
  37122. _this.onInterpolationDone = onInterpolationDone;
  37123. _this._target = _this._effectiveTarget = target;
  37124. return _this;
  37125. }
  37126. InterpolateValueAction.prototype._prepare = function () {
  37127. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37128. this._property = this._getProperty(this.propertyPath);
  37129. };
  37130. InterpolateValueAction.prototype.execute = function () {
  37131. var scene = this._actionManager.getScene();
  37132. var keys = [
  37133. {
  37134. frame: 0,
  37135. value: this._effectiveTarget[this._property]
  37136. }, {
  37137. frame: 100,
  37138. value: this.value
  37139. }
  37140. ];
  37141. var dataType;
  37142. if (typeof this.value === "number") {
  37143. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  37144. }
  37145. else if (this.value instanceof BABYLON.Color3) {
  37146. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  37147. }
  37148. else if (this.value instanceof BABYLON.Vector3) {
  37149. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  37150. }
  37151. else if (this.value instanceof BABYLON.Matrix) {
  37152. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  37153. }
  37154. else if (this.value instanceof BABYLON.Quaternion) {
  37155. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  37156. }
  37157. else {
  37158. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  37159. return;
  37160. }
  37161. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37162. animation.setKeys(keys);
  37163. if (this.stopOtherAnimations) {
  37164. scene.stopAnimation(this._effectiveTarget);
  37165. }
  37166. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  37167. };
  37168. InterpolateValueAction.prototype.serialize = function (parent) {
  37169. return _super.prototype._serialize.call(this, {
  37170. name: "InterpolateValueAction",
  37171. properties: [
  37172. BABYLON.Action._GetTargetProperty(this._target),
  37173. { name: "propertyPath", value: this.propertyPath },
  37174. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37175. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  37176. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  37177. ]
  37178. }, parent);
  37179. };
  37180. return InterpolateValueAction;
  37181. }(BABYLON.Action));
  37182. BABYLON.InterpolateValueAction = InterpolateValueAction;
  37183. })(BABYLON || (BABYLON = {}));
  37184. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  37185. var BABYLON;
  37186. (function (BABYLON) {
  37187. var SwitchBooleanAction = (function (_super) {
  37188. __extends(SwitchBooleanAction, _super);
  37189. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  37190. var _this = _super.call(this, triggerOptions, condition) || this;
  37191. _this.propertyPath = propertyPath;
  37192. _this._target = _this._effectiveTarget = target;
  37193. return _this;
  37194. }
  37195. SwitchBooleanAction.prototype._prepare = function () {
  37196. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37197. this._property = this._getProperty(this.propertyPath);
  37198. };
  37199. SwitchBooleanAction.prototype.execute = function () {
  37200. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  37201. };
  37202. SwitchBooleanAction.prototype.serialize = function (parent) {
  37203. return _super.prototype._serialize.call(this, {
  37204. name: "SwitchBooleanAction",
  37205. properties: [
  37206. BABYLON.Action._GetTargetProperty(this._target),
  37207. { name: "propertyPath", value: this.propertyPath }
  37208. ]
  37209. }, parent);
  37210. };
  37211. return SwitchBooleanAction;
  37212. }(BABYLON.Action));
  37213. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  37214. var SetStateAction = (function (_super) {
  37215. __extends(SetStateAction, _super);
  37216. function SetStateAction(triggerOptions, target, value, condition) {
  37217. var _this = _super.call(this, triggerOptions, condition) || this;
  37218. _this.value = value;
  37219. _this._target = target;
  37220. return _this;
  37221. }
  37222. SetStateAction.prototype.execute = function () {
  37223. this._target.state = this.value;
  37224. };
  37225. SetStateAction.prototype.serialize = function (parent) {
  37226. return _super.prototype._serialize.call(this, {
  37227. name: "SetStateAction",
  37228. properties: [
  37229. BABYLON.Action._GetTargetProperty(this._target),
  37230. { name: "value", value: this.value }
  37231. ]
  37232. }, parent);
  37233. };
  37234. return SetStateAction;
  37235. }(BABYLON.Action));
  37236. BABYLON.SetStateAction = SetStateAction;
  37237. var SetValueAction = (function (_super) {
  37238. __extends(SetValueAction, _super);
  37239. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  37240. var _this = _super.call(this, triggerOptions, condition) || this;
  37241. _this.propertyPath = propertyPath;
  37242. _this.value = value;
  37243. _this._target = _this._effectiveTarget = target;
  37244. return _this;
  37245. }
  37246. SetValueAction.prototype._prepare = function () {
  37247. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37248. this._property = this._getProperty(this.propertyPath);
  37249. };
  37250. SetValueAction.prototype.execute = function () {
  37251. this._effectiveTarget[this._property] = this.value;
  37252. if (this._target.markAsDirty) {
  37253. this._target.markAsDirty(this._property);
  37254. }
  37255. };
  37256. SetValueAction.prototype.serialize = function (parent) {
  37257. return _super.prototype._serialize.call(this, {
  37258. name: "SetValueAction",
  37259. properties: [
  37260. BABYLON.Action._GetTargetProperty(this._target),
  37261. { name: "propertyPath", value: this.propertyPath },
  37262. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37263. ]
  37264. }, parent);
  37265. };
  37266. return SetValueAction;
  37267. }(BABYLON.Action));
  37268. BABYLON.SetValueAction = SetValueAction;
  37269. var IncrementValueAction = (function (_super) {
  37270. __extends(IncrementValueAction, _super);
  37271. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  37272. var _this = _super.call(this, triggerOptions, condition) || this;
  37273. _this.propertyPath = propertyPath;
  37274. _this.value = value;
  37275. _this._target = _this._effectiveTarget = target;
  37276. return _this;
  37277. }
  37278. IncrementValueAction.prototype._prepare = function () {
  37279. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37280. this._property = this._getProperty(this.propertyPath);
  37281. if (typeof this._effectiveTarget[this._property] !== "number") {
  37282. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  37283. }
  37284. };
  37285. IncrementValueAction.prototype.execute = function () {
  37286. this._effectiveTarget[this._property] += this.value;
  37287. if (this._target.markAsDirty) {
  37288. this._target.markAsDirty(this._property);
  37289. }
  37290. };
  37291. IncrementValueAction.prototype.serialize = function (parent) {
  37292. return _super.prototype._serialize.call(this, {
  37293. name: "IncrementValueAction",
  37294. properties: [
  37295. BABYLON.Action._GetTargetProperty(this._target),
  37296. { name: "propertyPath", value: this.propertyPath },
  37297. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37298. ]
  37299. }, parent);
  37300. };
  37301. return IncrementValueAction;
  37302. }(BABYLON.Action));
  37303. BABYLON.IncrementValueAction = IncrementValueAction;
  37304. var PlayAnimationAction = (function (_super) {
  37305. __extends(PlayAnimationAction, _super);
  37306. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  37307. var _this = _super.call(this, triggerOptions, condition) || this;
  37308. _this.from = from;
  37309. _this.to = to;
  37310. _this.loop = loop;
  37311. _this._target = target;
  37312. return _this;
  37313. }
  37314. PlayAnimationAction.prototype._prepare = function () {
  37315. };
  37316. PlayAnimationAction.prototype.execute = function () {
  37317. var scene = this._actionManager.getScene();
  37318. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  37319. };
  37320. PlayAnimationAction.prototype.serialize = function (parent) {
  37321. return _super.prototype._serialize.call(this, {
  37322. name: "PlayAnimationAction",
  37323. properties: [
  37324. BABYLON.Action._GetTargetProperty(this._target),
  37325. { name: "from", value: String(this.from) },
  37326. { name: "to", value: String(this.to) },
  37327. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  37328. ]
  37329. }, parent);
  37330. };
  37331. return PlayAnimationAction;
  37332. }(BABYLON.Action));
  37333. BABYLON.PlayAnimationAction = PlayAnimationAction;
  37334. var StopAnimationAction = (function (_super) {
  37335. __extends(StopAnimationAction, _super);
  37336. function StopAnimationAction(triggerOptions, target, condition) {
  37337. var _this = _super.call(this, triggerOptions, condition) || this;
  37338. _this._target = target;
  37339. return _this;
  37340. }
  37341. StopAnimationAction.prototype._prepare = function () {
  37342. };
  37343. StopAnimationAction.prototype.execute = function () {
  37344. var scene = this._actionManager.getScene();
  37345. scene.stopAnimation(this._target);
  37346. };
  37347. StopAnimationAction.prototype.serialize = function (parent) {
  37348. return _super.prototype._serialize.call(this, {
  37349. name: "StopAnimationAction",
  37350. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  37351. }, parent);
  37352. };
  37353. return StopAnimationAction;
  37354. }(BABYLON.Action));
  37355. BABYLON.StopAnimationAction = StopAnimationAction;
  37356. var DoNothingAction = (function (_super) {
  37357. __extends(DoNothingAction, _super);
  37358. function DoNothingAction(triggerOptions, condition) {
  37359. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  37360. return _super.call(this, triggerOptions, condition) || this;
  37361. }
  37362. DoNothingAction.prototype.execute = function () {
  37363. };
  37364. DoNothingAction.prototype.serialize = function (parent) {
  37365. return _super.prototype._serialize.call(this, {
  37366. name: "DoNothingAction",
  37367. properties: []
  37368. }, parent);
  37369. };
  37370. return DoNothingAction;
  37371. }(BABYLON.Action));
  37372. BABYLON.DoNothingAction = DoNothingAction;
  37373. var CombineAction = (function (_super) {
  37374. __extends(CombineAction, _super);
  37375. function CombineAction(triggerOptions, children, condition) {
  37376. var _this = _super.call(this, triggerOptions, condition) || this;
  37377. _this.children = children;
  37378. return _this;
  37379. }
  37380. CombineAction.prototype._prepare = function () {
  37381. for (var index = 0; index < this.children.length; index++) {
  37382. this.children[index]._actionManager = this._actionManager;
  37383. this.children[index]._prepare();
  37384. }
  37385. };
  37386. CombineAction.prototype.execute = function (evt) {
  37387. for (var index = 0; index < this.children.length; index++) {
  37388. this.children[index].execute(evt);
  37389. }
  37390. };
  37391. CombineAction.prototype.serialize = function (parent) {
  37392. var serializationObject = _super.prototype._serialize.call(this, {
  37393. name: "CombineAction",
  37394. properties: [],
  37395. combine: []
  37396. }, parent);
  37397. for (var i = 0; i < this.children.length; i++) {
  37398. serializationObject.combine.push(this.children[i].serialize(null));
  37399. }
  37400. return serializationObject;
  37401. };
  37402. return CombineAction;
  37403. }(BABYLON.Action));
  37404. BABYLON.CombineAction = CombineAction;
  37405. var ExecuteCodeAction = (function (_super) {
  37406. __extends(ExecuteCodeAction, _super);
  37407. function ExecuteCodeAction(triggerOptions, func, condition) {
  37408. var _this = _super.call(this, triggerOptions, condition) || this;
  37409. _this.func = func;
  37410. return _this;
  37411. }
  37412. ExecuteCodeAction.prototype.execute = function (evt) {
  37413. this.func(evt);
  37414. };
  37415. return ExecuteCodeAction;
  37416. }(BABYLON.Action));
  37417. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  37418. var SetParentAction = (function (_super) {
  37419. __extends(SetParentAction, _super);
  37420. function SetParentAction(triggerOptions, target, parent, condition) {
  37421. var _this = _super.call(this, triggerOptions, condition) || this;
  37422. _this._target = target;
  37423. _this._parent = parent;
  37424. return _this;
  37425. }
  37426. SetParentAction.prototype._prepare = function () {
  37427. };
  37428. SetParentAction.prototype.execute = function () {
  37429. if (this._target.parent === this._parent) {
  37430. return;
  37431. }
  37432. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  37433. invertParentWorldMatrix.invert();
  37434. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  37435. this._target.parent = this._parent;
  37436. };
  37437. SetParentAction.prototype.serialize = function (parent) {
  37438. return _super.prototype._serialize.call(this, {
  37439. name: "SetParentAction",
  37440. properties: [
  37441. BABYLON.Action._GetTargetProperty(this._target),
  37442. BABYLON.Action._GetTargetProperty(this._parent),
  37443. ]
  37444. }, parent);
  37445. };
  37446. return SetParentAction;
  37447. }(BABYLON.Action));
  37448. BABYLON.SetParentAction = SetParentAction;
  37449. var PlaySoundAction = (function (_super) {
  37450. __extends(PlaySoundAction, _super);
  37451. function PlaySoundAction(triggerOptions, sound, condition) {
  37452. var _this = _super.call(this, triggerOptions, condition) || this;
  37453. _this._sound = sound;
  37454. return _this;
  37455. }
  37456. PlaySoundAction.prototype._prepare = function () {
  37457. };
  37458. PlaySoundAction.prototype.execute = function () {
  37459. if (this._sound !== undefined)
  37460. this._sound.play();
  37461. };
  37462. PlaySoundAction.prototype.serialize = function (parent) {
  37463. return _super.prototype._serialize.call(this, {
  37464. name: "PlaySoundAction",
  37465. properties: [{ name: "sound", value: this._sound.name }]
  37466. }, parent);
  37467. };
  37468. return PlaySoundAction;
  37469. }(BABYLON.Action));
  37470. BABYLON.PlaySoundAction = PlaySoundAction;
  37471. var StopSoundAction = (function (_super) {
  37472. __extends(StopSoundAction, _super);
  37473. function StopSoundAction(triggerOptions, sound, condition) {
  37474. var _this = _super.call(this, triggerOptions, condition) || this;
  37475. _this._sound = sound;
  37476. return _this;
  37477. }
  37478. StopSoundAction.prototype._prepare = function () {
  37479. };
  37480. StopSoundAction.prototype.execute = function () {
  37481. if (this._sound !== undefined)
  37482. this._sound.stop();
  37483. };
  37484. StopSoundAction.prototype.serialize = function (parent) {
  37485. return _super.prototype._serialize.call(this, {
  37486. name: "StopSoundAction",
  37487. properties: [{ name: "sound", value: this._sound.name }]
  37488. }, parent);
  37489. };
  37490. return StopSoundAction;
  37491. }(BABYLON.Action));
  37492. BABYLON.StopSoundAction = StopSoundAction;
  37493. })(BABYLON || (BABYLON = {}));
  37494. //# sourceMappingURL=babylon.directActions.js.map
  37495. var BABYLON;
  37496. (function (BABYLON) {
  37497. var Debug;
  37498. (function (Debug) {
  37499. /**
  37500. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  37501. */
  37502. var SkeletonViewer = (function () {
  37503. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  37504. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  37505. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  37506. this.skeleton = skeleton;
  37507. this.mesh = mesh;
  37508. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  37509. this.renderingGroupId = renderingGroupId;
  37510. this.color = BABYLON.Color3.White();
  37511. this._debugLines = [];
  37512. this._isEnabled = false;
  37513. this._scene = scene;
  37514. this.update();
  37515. this._renderFunction = this.update.bind(this);
  37516. }
  37517. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  37518. get: function () {
  37519. return this._isEnabled;
  37520. },
  37521. set: function (value) {
  37522. if (this._isEnabled === value) {
  37523. return;
  37524. }
  37525. this._isEnabled = value;
  37526. if (value) {
  37527. this._scene.registerBeforeRender(this._renderFunction);
  37528. }
  37529. else {
  37530. this._scene.unregisterBeforeRender(this._renderFunction);
  37531. }
  37532. },
  37533. enumerable: true,
  37534. configurable: true
  37535. });
  37536. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  37537. if (x === void 0) { x = 0; }
  37538. if (y === void 0) { y = 0; }
  37539. if (z === void 0) { z = 0; }
  37540. var tmat = BABYLON.Tmp.Matrix[0];
  37541. var parentBone = bone.getParent();
  37542. tmat.copyFrom(bone.getLocalMatrix());
  37543. if (x !== 0 || y !== 0 || z !== 0) {
  37544. var tmat2 = BABYLON.Tmp.Matrix[1];
  37545. BABYLON.Matrix.IdentityToRef(tmat2);
  37546. tmat2.m[12] = x;
  37547. tmat2.m[13] = y;
  37548. tmat2.m[14] = z;
  37549. tmat2.multiplyToRef(tmat, tmat);
  37550. }
  37551. if (parentBone) {
  37552. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  37553. }
  37554. tmat.multiplyToRef(meshMat, tmat);
  37555. position.x = tmat.m[12];
  37556. position.y = tmat.m[13];
  37557. position.z = tmat.m[14];
  37558. };
  37559. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  37560. var len = bones.length;
  37561. var meshPos = this.mesh.position;
  37562. for (var i = 0; i < len; i++) {
  37563. var bone = bones[i];
  37564. var points = this._debugLines[i];
  37565. if (!points) {
  37566. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37567. this._debugLines[i] = points;
  37568. }
  37569. this._getBonePosition(points[0], bone, meshMat);
  37570. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  37571. points[0].subtractInPlace(meshPos);
  37572. points[1].subtractInPlace(meshPos);
  37573. }
  37574. };
  37575. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  37576. var len = bones.length;
  37577. var boneNum = 0;
  37578. var meshPos = this.mesh.position;
  37579. for (var i = len - 1; i >= 0; i--) {
  37580. var childBone = bones[i];
  37581. var parentBone = childBone.getParent();
  37582. if (!parentBone) {
  37583. continue;
  37584. }
  37585. var points = this._debugLines[boneNum];
  37586. if (!points) {
  37587. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37588. this._debugLines[boneNum] = points;
  37589. }
  37590. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  37591. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  37592. points[0].subtractInPlace(meshPos);
  37593. points[1].subtractInPlace(meshPos);
  37594. boneNum++;
  37595. }
  37596. };
  37597. SkeletonViewer.prototype.update = function () {
  37598. if (this.autoUpdateBonesMatrices) {
  37599. this.skeleton.computeAbsoluteTransforms();
  37600. }
  37601. if (this.skeleton.bones[0].length === undefined) {
  37602. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  37603. }
  37604. else {
  37605. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  37606. }
  37607. if (!this._debugMesh) {
  37608. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  37609. this._debugMesh.renderingGroupId = this.renderingGroupId;
  37610. }
  37611. else {
  37612. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  37613. }
  37614. this._debugMesh.position.copyFrom(this.mesh.position);
  37615. this._debugMesh.color = this.color;
  37616. };
  37617. SkeletonViewer.prototype.dispose = function () {
  37618. if (this._debugMesh) {
  37619. this.isEnabled = false;
  37620. this._debugMesh.dispose();
  37621. this._debugMesh = null;
  37622. }
  37623. };
  37624. return SkeletonViewer;
  37625. }());
  37626. Debug.SkeletonViewer = SkeletonViewer;
  37627. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37628. })(BABYLON || (BABYLON = {}));
  37629. //# sourceMappingURL=babylon.skeletonViewer.js.map
  37630. var BABYLON;
  37631. (function (BABYLON) {
  37632. var Debug;
  37633. (function (Debug) {
  37634. var AxesViewer = (function () {
  37635. function AxesViewer(scene, scaleLines) {
  37636. if (scaleLines === void 0) { scaleLines = 1; }
  37637. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37638. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37639. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37640. this.scaleLines = 1;
  37641. this.scaleLines = scaleLines;
  37642. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  37643. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  37644. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  37645. this._xmesh.renderingGroupId = 2;
  37646. this._ymesh.renderingGroupId = 2;
  37647. this._zmesh.renderingGroupId = 2;
  37648. this._xmesh.material.checkReadyOnlyOnce = true;
  37649. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  37650. this._ymesh.material.checkReadyOnlyOnce = true;
  37651. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  37652. this._zmesh.material.checkReadyOnlyOnce = true;
  37653. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  37654. this.scene = scene;
  37655. }
  37656. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  37657. var scaleLines = this.scaleLines;
  37658. this._xmesh.position.copyFrom(position);
  37659. this._ymesh.position.copyFrom(position);
  37660. this._zmesh.position.copyFrom(position);
  37661. var point2 = this._xline[1];
  37662. point2.x = xaxis.x * scaleLines;
  37663. point2.y = xaxis.y * scaleLines;
  37664. point2.z = xaxis.z * scaleLines;
  37665. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  37666. point2 = this._yline[1];
  37667. point2.x = yaxis.x * scaleLines;
  37668. point2.y = yaxis.y * scaleLines;
  37669. point2.z = yaxis.z * scaleLines;
  37670. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  37671. point2 = this._zline[1];
  37672. point2.x = zaxis.x * scaleLines;
  37673. point2.y = zaxis.y * scaleLines;
  37674. point2.z = zaxis.z * scaleLines;
  37675. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  37676. };
  37677. AxesViewer.prototype.dispose = function () {
  37678. if (this._xmesh) {
  37679. this._xmesh.dispose();
  37680. this._ymesh.dispose();
  37681. this._zmesh.dispose();
  37682. this._xmesh = null;
  37683. this._ymesh = null;
  37684. this._zmesh = null;
  37685. this._xline = null;
  37686. this._yline = null;
  37687. this._zline = null;
  37688. this.scene = null;
  37689. }
  37690. };
  37691. return AxesViewer;
  37692. }());
  37693. Debug.AxesViewer = AxesViewer;
  37694. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37695. })(BABYLON || (BABYLON = {}));
  37696. //# sourceMappingURL=babylon.axesViewer.js.map
  37697. var BABYLON;
  37698. (function (BABYLON) {
  37699. var Debug;
  37700. (function (Debug) {
  37701. var BoneAxesViewer = (function (_super) {
  37702. __extends(BoneAxesViewer, _super);
  37703. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  37704. if (scaleLines === void 0) { scaleLines = 1; }
  37705. var _this = _super.call(this, scene, scaleLines) || this;
  37706. _this.pos = BABYLON.Vector3.Zero();
  37707. _this.xaxis = BABYLON.Vector3.Zero();
  37708. _this.yaxis = BABYLON.Vector3.Zero();
  37709. _this.zaxis = BABYLON.Vector3.Zero();
  37710. _this.mesh = mesh;
  37711. _this.bone = bone;
  37712. return _this;
  37713. }
  37714. BoneAxesViewer.prototype.update = function () {
  37715. var bone = this.bone;
  37716. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  37717. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  37718. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  37719. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  37720. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  37721. };
  37722. BoneAxesViewer.prototype.dispose = function () {
  37723. if (this.pos) {
  37724. this.pos = null;
  37725. this.xaxis = null;
  37726. this.yaxis = null;
  37727. this.zaxis = null;
  37728. this.mesh = null;
  37729. this.bone = null;
  37730. _super.prototype.dispose.call(this);
  37731. }
  37732. };
  37733. return BoneAxesViewer;
  37734. }(Debug.AxesViewer));
  37735. Debug.BoneAxesViewer = BoneAxesViewer;
  37736. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37737. })(BABYLON || (BABYLON = {}));
  37738. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  37739. var BABYLON;
  37740. (function (BABYLON) {
  37741. var RayHelper = (function () {
  37742. function RayHelper(ray) {
  37743. this.ray = ray;
  37744. }
  37745. RayHelper.CreateAndShow = function (ray, scene, color) {
  37746. var helper = new RayHelper(ray);
  37747. helper.show(scene, color);
  37748. return helper;
  37749. };
  37750. RayHelper.prototype.show = function (scene, color) {
  37751. if (!this._renderFunction) {
  37752. var ray = this.ray;
  37753. this._renderFunction = this._render.bind(this);
  37754. this._scene = scene;
  37755. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  37756. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  37757. this._scene.registerBeforeRender(this._renderFunction);
  37758. }
  37759. if (color) {
  37760. this._renderLine.color.copyFrom(color);
  37761. }
  37762. };
  37763. RayHelper.prototype.hide = function () {
  37764. if (this._renderFunction) {
  37765. this._scene.unregisterBeforeRender(this._renderFunction);
  37766. this._scene = null;
  37767. this._renderFunction = null;
  37768. this._renderLine.dispose();
  37769. this._renderLine = null;
  37770. this._renderPoints = null;
  37771. }
  37772. };
  37773. RayHelper.prototype._render = function () {
  37774. var ray = this.ray;
  37775. var point = this._renderPoints[1];
  37776. var len = Math.min(ray.length, 1000000);
  37777. point.copyFrom(ray.direction);
  37778. point.scaleInPlace(len);
  37779. point.addInPlace(ray.origin);
  37780. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  37781. };
  37782. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  37783. this._attachedToMesh = mesh;
  37784. var ray = this.ray;
  37785. if (!ray.direction) {
  37786. ray.direction = BABYLON.Vector3.Zero();
  37787. }
  37788. if (!ray.origin) {
  37789. ray.origin = BABYLON.Vector3.Zero();
  37790. }
  37791. if (length) {
  37792. ray.length = length;
  37793. }
  37794. if (!meshSpaceOrigin) {
  37795. meshSpaceOrigin = BABYLON.Vector3.Zero();
  37796. }
  37797. if (!meshSpaceDirection) {
  37798. // -1 so that this will work with Mesh.lookAt
  37799. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  37800. }
  37801. if (!this._meshSpaceDirection) {
  37802. this._meshSpaceDirection = meshSpaceDirection.clone();
  37803. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  37804. }
  37805. else {
  37806. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  37807. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  37808. }
  37809. if (!this._updateToMeshFunction) {
  37810. this._updateToMeshFunction = this._updateToMesh.bind(this);
  37811. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  37812. }
  37813. this._updateToMesh();
  37814. };
  37815. RayHelper.prototype.detachFromMesh = function () {
  37816. if (this._attachedToMesh) {
  37817. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  37818. this._attachedToMesh = null;
  37819. this._updateToMeshFunction = null;
  37820. }
  37821. };
  37822. RayHelper.prototype._updateToMesh = function () {
  37823. var ray = this.ray;
  37824. if (this._attachedToMesh._isDisposed) {
  37825. this.detachFromMesh();
  37826. return;
  37827. }
  37828. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  37829. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  37830. };
  37831. RayHelper.prototype.dispose = function () {
  37832. this.hide();
  37833. this.detachFromMesh();
  37834. this.ray = null;
  37835. };
  37836. return RayHelper;
  37837. }());
  37838. BABYLON.RayHelper = RayHelper;
  37839. })(BABYLON || (BABYLON = {}));
  37840. //# sourceMappingURL=babylon.rayHelper.js.map
  37841. var BABYLON;
  37842. (function (BABYLON) {
  37843. var DebugLayer = (function () {
  37844. function DebugLayer(scene) {
  37845. this._scene = scene;
  37846. }
  37847. /** Creates the inspector window. */
  37848. DebugLayer.prototype._createInspector = function (config) {
  37849. if (config === void 0) { config = {}; }
  37850. var popup = config.popup || false;
  37851. var initialTab = config.initialTab || 0;
  37852. var parentElement = config.parentElement || null;
  37853. if (!this._inspector) {
  37854. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  37855. } // else nothing to do,; instance is already existing
  37856. };
  37857. DebugLayer.prototype.isVisible = function () {
  37858. if (!this._inspector) {
  37859. return false;
  37860. }
  37861. return true;
  37862. };
  37863. DebugLayer.prototype.hide = function () {
  37864. if (this._inspector) {
  37865. try {
  37866. this._inspector.dispose();
  37867. }
  37868. catch (e) {
  37869. // If the inspector has been removed directly from the inspector tool
  37870. }
  37871. this._inspector = null;
  37872. }
  37873. };
  37874. DebugLayer.prototype.show = function (config) {
  37875. if (config === void 0) { config = {}; }
  37876. if (typeof INSPECTOR == 'undefined') {
  37877. // Load inspector and add it to the DOM
  37878. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  37879. }
  37880. else {
  37881. // Otherwise creates the inspector
  37882. this._createInspector(config);
  37883. }
  37884. };
  37885. return DebugLayer;
  37886. }());
  37887. // Get protocol used - http or https
  37888. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  37889. BABYLON.DebugLayer = DebugLayer;
  37890. })(BABYLON || (BABYLON = {}));
  37891. //# sourceMappingURL=babylon.debugLayer.js.map
  37892. var BABYLON;
  37893. (function (BABYLON) {
  37894. var BoundingBoxRenderer = (function () {
  37895. function BoundingBoxRenderer(scene) {
  37896. this.frontColor = new BABYLON.Color3(1, 1, 1);
  37897. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  37898. this.showBackLines = true;
  37899. this.renderList = new BABYLON.SmartArray(32);
  37900. this._vertexBuffers = {};
  37901. this._scene = scene;
  37902. }
  37903. BoundingBoxRenderer.prototype._prepareRessources = function () {
  37904. if (this._colorShader) {
  37905. return;
  37906. }
  37907. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  37908. attributes: [BABYLON.VertexBuffer.PositionKind],
  37909. uniforms: ["world", "viewProjection", "color"]
  37910. });
  37911. var engine = this._scene.getEngine();
  37912. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  37913. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  37914. 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]);
  37915. };
  37916. BoundingBoxRenderer.prototype.reset = function () {
  37917. this.renderList.reset();
  37918. };
  37919. BoundingBoxRenderer.prototype.render = function () {
  37920. if (this.renderList.length === 0) {
  37921. return;
  37922. }
  37923. this._prepareRessources();
  37924. if (!this._colorShader.isReady()) {
  37925. return;
  37926. }
  37927. var engine = this._scene.getEngine();
  37928. engine.setDepthWrite(false);
  37929. this._colorShader._preBind();
  37930. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  37931. var boundingBox = this.renderList.data[boundingBoxIndex];
  37932. var min = boundingBox.minimum;
  37933. var max = boundingBox.maximum;
  37934. var diff = max.subtract(min);
  37935. var median = min.add(diff.scale(0.5));
  37936. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  37937. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  37938. .multiply(boundingBox.getWorldMatrix());
  37939. // VBOs
  37940. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  37941. if (this.showBackLines) {
  37942. // Back
  37943. engine.setDepthFunctionToGreaterOrEqual();
  37944. this._scene.resetCachedMaterial();
  37945. this._colorShader.setColor4("color", this.backColor.toColor4());
  37946. this._colorShader.bind(worldMatrix);
  37947. // Draw order
  37948. engine.draw(false, 0, 24);
  37949. }
  37950. // Front
  37951. engine.setDepthFunctionToLess();
  37952. this._scene.resetCachedMaterial();
  37953. this._colorShader.setColor4("color", this.frontColor.toColor4());
  37954. this._colorShader.bind(worldMatrix);
  37955. // Draw order
  37956. engine.draw(false, 0, 24);
  37957. }
  37958. this._colorShader.unbind();
  37959. engine.setDepthFunctionToLessOrEqual();
  37960. engine.setDepthWrite(true);
  37961. };
  37962. BoundingBoxRenderer.prototype.dispose = function () {
  37963. if (!this._colorShader) {
  37964. return;
  37965. }
  37966. this.renderList.dispose();
  37967. this._colorShader.dispose();
  37968. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37969. if (buffer) {
  37970. buffer.dispose();
  37971. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37972. }
  37973. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37974. };
  37975. return BoundingBoxRenderer;
  37976. }());
  37977. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  37978. })(BABYLON || (BABYLON = {}));
  37979. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  37980. var BABYLON;
  37981. (function (BABYLON) {
  37982. var MultiMaterial = (function (_super) {
  37983. __extends(MultiMaterial, _super);
  37984. function MultiMaterial(name, scene) {
  37985. var _this = _super.call(this, name, scene, true) || this;
  37986. _this.subMaterials = new Array();
  37987. scene.multiMaterials.push(_this);
  37988. return _this;
  37989. }
  37990. // Properties
  37991. MultiMaterial.prototype.getSubMaterial = function (index) {
  37992. if (index < 0 || index >= this.subMaterials.length) {
  37993. return this.getScene().defaultMaterial;
  37994. }
  37995. return this.subMaterials[index];
  37996. };
  37997. // Methods
  37998. MultiMaterial.prototype.getClassName = function () {
  37999. return "MultiMaterial";
  38000. };
  38001. MultiMaterial.prototype.isReady = function (mesh) {
  38002. for (var index = 0; index < this.subMaterials.length; index++) {
  38003. var subMaterial = this.subMaterials[index];
  38004. if (subMaterial) {
  38005. if (!this.subMaterials[index].isReady(mesh)) {
  38006. return false;
  38007. }
  38008. }
  38009. }
  38010. return true;
  38011. };
  38012. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  38013. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  38014. for (var index = 0; index < this.subMaterials.length; index++) {
  38015. var subMaterial = null;
  38016. if (cloneChildren) {
  38017. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  38018. }
  38019. else {
  38020. subMaterial = this.subMaterials[index];
  38021. }
  38022. newMultiMaterial.subMaterials.push(subMaterial);
  38023. }
  38024. return newMultiMaterial;
  38025. };
  38026. MultiMaterial.prototype.serialize = function () {
  38027. var serializationObject = {};
  38028. serializationObject.name = this.name;
  38029. serializationObject.id = this.id;
  38030. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38031. serializationObject.materials = [];
  38032. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  38033. var subMat = this.subMaterials[matIndex];
  38034. if (subMat) {
  38035. serializationObject.materials.push(subMat.id);
  38036. }
  38037. else {
  38038. serializationObject.materials.push(null);
  38039. }
  38040. }
  38041. return serializationObject;
  38042. };
  38043. return MultiMaterial;
  38044. }(BABYLON.Material));
  38045. BABYLON.MultiMaterial = MultiMaterial;
  38046. })(BABYLON || (BABYLON = {}));
  38047. //# sourceMappingURL=babylon.multiMaterial.js.map
  38048. var BABYLON;
  38049. (function (BABYLON) {
  38050. var PBRMaterialDefines = (function (_super) {
  38051. __extends(PBRMaterialDefines, _super);
  38052. function PBRMaterialDefines() {
  38053. var _this = _super.call(this) || this;
  38054. _this.PBR = true;
  38055. _this.ALBEDO = false;
  38056. _this.AMBIENT = false;
  38057. _this.AMBIENTINGRAYSCALE = false;
  38058. _this.OPACITY = false;
  38059. _this.OPACITYRGB = false;
  38060. _this.REFLECTION = false;
  38061. _this.EMISSIVE = false;
  38062. _this.REFLECTIVITY = false;
  38063. _this.BUMP = false;
  38064. _this.PARALLAX = false;
  38065. _this.PARALLAXOCCLUSION = false;
  38066. _this.SPECULAROVERALPHA = false;
  38067. _this.CLIPPLANE = false;
  38068. _this.ALPHATEST = false;
  38069. _this.ALPHAFROMALBEDO = false;
  38070. _this.POINTSIZE = false;
  38071. _this.FOG = false;
  38072. _this.SPECULARTERM = false;
  38073. _this.OPACITYFRESNEL = false;
  38074. _this.EMISSIVEFRESNEL = false;
  38075. _this.FRESNEL = false;
  38076. _this.NORMAL = false;
  38077. _this.TANGENT = false;
  38078. _this.UV1 = false;
  38079. _this.UV2 = false;
  38080. _this.VERTEXCOLOR = false;
  38081. _this.VERTEXALPHA = false;
  38082. _this.NUM_BONE_INFLUENCERS = 0;
  38083. _this.BonesPerMesh = 0;
  38084. _this.INSTANCES = false;
  38085. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38086. _this.MICROSURFACEAUTOMATIC = false;
  38087. _this.EMISSIVEASILLUMINATION = false;
  38088. _this.LIGHTMAP = false;
  38089. _this.USELIGHTMAPASSHADOWMAP = false;
  38090. _this.REFLECTIONMAP_3D = false;
  38091. _this.REFLECTIONMAP_SPHERICAL = false;
  38092. _this.REFLECTIONMAP_PLANAR = false;
  38093. _this.REFLECTIONMAP_CUBIC = false;
  38094. _this.REFLECTIONMAP_PROJECTION = false;
  38095. _this.REFLECTIONMAP_SKYBOX = false;
  38096. _this.REFLECTIONMAP_EXPLICIT = false;
  38097. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38098. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38099. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38100. _this.INVERTCUBICMAP = false;
  38101. _this.LOGARITHMICDEPTH = false;
  38102. _this.CAMERATONEMAP = false;
  38103. _this.CAMERACONTRAST = false;
  38104. _this.CAMERACOLORGRADING = false;
  38105. _this.CAMERACOLORCURVES = false;
  38106. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38107. _this.REFRACTION = false;
  38108. _this.REFRACTIONMAP_3D = false;
  38109. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38110. _this.REFRACTIONMAPINLINEARSPACE = false;
  38111. _this.LODBASEDMICROSFURACE = false;
  38112. _this.USEPHYSICALLIGHTFALLOFF = false;
  38113. _this.RADIANCEOVERALPHA = false;
  38114. _this.USEPMREMREFLECTION = false;
  38115. _this.USEPMREMREFRACTION = false;
  38116. _this.INVERTNORMALMAPX = false;
  38117. _this.INVERTNORMALMAPY = false;
  38118. _this.TWOSIDEDLIGHTING = false;
  38119. _this.SHADOWFULLFLOAT = false;
  38120. _this.NORMALXYSCALE = true;
  38121. _this.USERIGHTHANDEDSYSTEM = false;
  38122. _this.METALLICWORKFLOW = false;
  38123. _this.METALLICMAP = false;
  38124. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38125. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38126. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38127. _this.AOSTOREINMETALMAPRED = false;
  38128. _this.MICROSURFACEMAP = false;
  38129. _this.MORPHTARGETS = false;
  38130. _this.MORPHTARGETS_NORMAL = false;
  38131. _this.MORPHTARGETS_TANGENT = false;
  38132. _this.NUM_MORPH_INFLUENCERS = 0;
  38133. _this.ALPHATESTVALUE = 0.4;
  38134. _this.LDROUTPUT = true;
  38135. _this.rebuild();
  38136. return _this;
  38137. }
  38138. PBRMaterialDefines.prototype.reset = function () {
  38139. _super.prototype.reset.call(this);
  38140. this.ALPHATESTVALUE = 0.4;
  38141. this.PBR = true;
  38142. };
  38143. return PBRMaterialDefines;
  38144. }(BABYLON.MaterialDefines));
  38145. /**
  38146. * The Physically based material base class of BJS.
  38147. *
  38148. * This offers the main features of a standard PBR material.
  38149. * For more information, please refer to the documentation :
  38150. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38151. */
  38152. var PBRBaseMaterial = (function (_super) {
  38153. __extends(PBRBaseMaterial, _super);
  38154. /**
  38155. * Instantiates a new PBRMaterial instance.
  38156. *
  38157. * @param name The material name
  38158. * @param scene The scene the material will be use in.
  38159. */
  38160. function PBRBaseMaterial(name, scene) {
  38161. var _this = _super.call(this, name, scene) || this;
  38162. /**
  38163. * Intensity of the direct lights e.g. the four lights available in your scene.
  38164. * This impacts both the direct diffuse and specular highlights.
  38165. */
  38166. _this._directIntensity = 1.0;
  38167. /**
  38168. * Intensity of the emissive part of the material.
  38169. * This helps controlling the emissive effect without modifying the emissive color.
  38170. */
  38171. _this._emissiveIntensity = 1.0;
  38172. /**
  38173. * Intensity of the environment e.g. how much the environment will light the object
  38174. * either through harmonics for rough material or through the refelction for shiny ones.
  38175. */
  38176. _this._environmentIntensity = 1.0;
  38177. /**
  38178. * This is a special control allowing the reduction of the specular highlights coming from the
  38179. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38180. */
  38181. _this._specularIntensity = 1.0;
  38182. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38183. /**
  38184. * Debug Control allowing disabling the bump map on this material.
  38185. */
  38186. _this._disableBumpMap = false;
  38187. /**
  38188. * The camera exposure used on this material.
  38189. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38190. * This corresponds to a photographic exposure.
  38191. */
  38192. _this._cameraExposure = 1.0;
  38193. /**
  38194. * The camera contrast used on this material.
  38195. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  38196. */
  38197. _this._cameraContrast = 1.0;
  38198. /**
  38199. * Color Grading 2D Lookup Texture.
  38200. * This allows special effects like sepia, black and white to sixties rendering style.
  38201. */
  38202. _this._cameraColorGradingTexture = null;
  38203. /**
  38204. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38205. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38206. * 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;
  38207. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38208. */
  38209. _this._cameraColorCurves = null;
  38210. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  38211. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  38212. /**
  38213. * AKA Occlusion Texture Intensity in other nomenclature.
  38214. */
  38215. _this._ambientTextureStrength = 1.0;
  38216. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38217. /**
  38218. * AKA Diffuse Color in other nomenclature.
  38219. */
  38220. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38221. /**
  38222. * AKA Specular Color in other nomenclature.
  38223. */
  38224. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38225. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  38226. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38227. /**
  38228. * AKA Glossiness in other nomenclature.
  38229. */
  38230. _this._microSurface = 0.9;
  38231. /**
  38232. * source material index of refraction (IOR)' / 'destination material IOR.
  38233. */
  38234. _this._indexOfRefraction = 0.66;
  38235. /**
  38236. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38237. */
  38238. _this._invertRefractionY = false;
  38239. /**
  38240. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38241. * Materials half opaque for instance using refraction could benefit from this control.
  38242. */
  38243. _this._linkRefractionWithTransparency = false;
  38244. _this._useLightmapAsShadowmap = false;
  38245. /**
  38246. * In this mode, the emissive informtaion will always be added to the lighting once.
  38247. * A light for instance can be thought as emissive.
  38248. */
  38249. _this._useEmissiveAsIllumination = false;
  38250. /**
  38251. * Secifies that the alpha is coming form the albedo channel alpha channel.
  38252. */
  38253. _this._useAlphaFromAlbedoTexture = false;
  38254. /**
  38255. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38256. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38257. */
  38258. _this._useSpecularOverAlpha = true;
  38259. /**
  38260. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38261. */
  38262. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38263. /**
  38264. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38265. */
  38266. _this._useRoughnessFromMetallicTextureAlpha = true;
  38267. /**
  38268. * Specifies if the metallic texture contains the roughness information in its green channel.
  38269. */
  38270. _this._useRoughnessFromMetallicTextureGreen = false;
  38271. /**
  38272. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38273. */
  38274. _this._useMetallnessFromMetallicTextureBlue = false;
  38275. /**
  38276. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38277. */
  38278. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38279. /**
  38280. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38281. */
  38282. _this._useAmbientInGrayScale = false;
  38283. /**
  38284. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38285. * The material will try to infer what glossiness each pixel should be.
  38286. */
  38287. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38288. /**
  38289. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  38290. * the creation of the material.
  38291. */
  38292. _this._useScalarInLinearSpace = false;
  38293. /**
  38294. * BJS is using an harcoded light falloff based on a manually sets up range.
  38295. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38296. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38297. */
  38298. _this._usePhysicalLightFalloff = true;
  38299. /**
  38300. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38301. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38302. */
  38303. _this._useRadianceOverAlpha = true;
  38304. /**
  38305. * Allows using the bump map in parallax mode.
  38306. */
  38307. _this._useParallax = false;
  38308. /**
  38309. * Allows using the bump map in parallax occlusion mode.
  38310. */
  38311. _this._useParallaxOcclusion = false;
  38312. /**
  38313. * Controls the scale bias of the parallax mode.
  38314. */
  38315. _this._parallaxScaleBias = 0.05;
  38316. /**
  38317. * If sets to true, disables all the lights affecting the material.
  38318. */
  38319. _this._disableLighting = false;
  38320. /**
  38321. * Number of Simultaneous lights allowed on the material.
  38322. */
  38323. _this._maxSimultaneousLights = 4;
  38324. /**
  38325. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38326. */
  38327. _this._invertNormalMapX = false;
  38328. /**
  38329. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38330. */
  38331. _this._invertNormalMapY = false;
  38332. /**
  38333. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38334. */
  38335. _this._twoSidedLighting = false;
  38336. /**
  38337. * Defines the alpha limits in alpha test mode.
  38338. */
  38339. _this._alphaCutOff = 0.4;
  38340. /**
  38341. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38342. */
  38343. _this._forceAlphaTest = false;
  38344. /**
  38345. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is usefull
  38346. * in combination of post process in float or half float mode.
  38347. */
  38348. _this._ldrOutput = true;
  38349. _this._renderTargets = new BABYLON.SmartArray(16);
  38350. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38351. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38352. _this._tempColor = new BABYLON.Color3();
  38353. _this._defines = new PBRMaterialDefines();
  38354. _this._cachedDefines = new PBRMaterialDefines();
  38355. _this._myScene = null;
  38356. _this._myShadowGenerator = null;
  38357. _this._cachedDefines.BonesPerMesh = -1;
  38358. _this.getRenderTargetTextures = function () {
  38359. _this._renderTargets.reset();
  38360. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38361. _this._renderTargets.push(_this._reflectionTexture);
  38362. }
  38363. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38364. _this._renderTargets.push(_this._refractionTexture);
  38365. }
  38366. return _this._renderTargets;
  38367. };
  38368. return _this;
  38369. }
  38370. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38371. get: function () {
  38372. return this._useLogarithmicDepth;
  38373. },
  38374. set: function (value) {
  38375. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38376. },
  38377. enumerable: true,
  38378. configurable: true
  38379. });
  38380. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38381. if (this._linkRefractionWithTransparency) {
  38382. return false;
  38383. }
  38384. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38385. };
  38386. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38387. if (this._linkRefractionWithTransparency) {
  38388. return false;
  38389. }
  38390. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  38391. };
  38392. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38393. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  38394. };
  38395. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38396. return this._albedoTexture;
  38397. };
  38398. PBRBaseMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38399. if (!mesh) {
  38400. return true;
  38401. }
  38402. if (this._defines.INSTANCES !== useInstances) {
  38403. return false;
  38404. }
  38405. return false;
  38406. };
  38407. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  38408. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  38409. };
  38410. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  38411. if (!useScalarInLinear) {
  38412. color.toLinearSpaceToRef(ref);
  38413. }
  38414. else {
  38415. ref.r = color.r;
  38416. ref.g = color.g;
  38417. ref.b = color.b;
  38418. }
  38419. };
  38420. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  38421. var lightIndex = 0;
  38422. var depthValuesAlreadySet = false;
  38423. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38424. var light = _a[_i];
  38425. var useUbo = light._uniformBuffer.useUbo;
  38426. var scaledIntensity = light.getScaledIntensity();
  38427. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  38428. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  38429. // GAMMA CORRECTION.
  38430. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  38431. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  38432. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  38433. if (defines["SPECULARTERM"]) {
  38434. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  38435. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  38436. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  38437. }
  38438. // Shadows
  38439. if (scene.shadowsEnabled) {
  38440. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  38441. }
  38442. light._uniformBuffer.update();
  38443. lightIndex++;
  38444. if (lightIndex === maxSimultaneousLights)
  38445. break;
  38446. }
  38447. };
  38448. PBRBaseMaterial.prototype.isReady = function (mesh, useInstances) {
  38449. if (this.isFrozen) {
  38450. if (this._wasPreviouslyReady) {
  38451. return true;
  38452. }
  38453. }
  38454. var scene = this.getScene();
  38455. var engine = scene.getEngine();
  38456. var needUVs = false;
  38457. this._defines.reset();
  38458. if (scene.lightsEnabled && !this._disableLighting) {
  38459. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this._maxSimultaneousLights);
  38460. }
  38461. if (!this.checkReadyOnEveryCall) {
  38462. if (this._renderId === scene.getRenderId()) {
  38463. if (this._checkCache(scene, mesh, useInstances)) {
  38464. return true;
  38465. }
  38466. }
  38467. }
  38468. if (scene.texturesEnabled) {
  38469. if (scene.getEngine().getCaps().textureLOD) {
  38470. this._defines.LODBASEDMICROSFURACE = true;
  38471. }
  38472. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38473. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38474. return false;
  38475. }
  38476. needUVs = true;
  38477. this._defines.ALBEDO = true;
  38478. }
  38479. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38480. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38481. return false;
  38482. }
  38483. needUVs = true;
  38484. this._defines.AMBIENT = true;
  38485. this._defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38486. }
  38487. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38488. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38489. return false;
  38490. }
  38491. needUVs = true;
  38492. this._defines.OPACITY = true;
  38493. if (this._opacityTexture.getAlphaFromRGB) {
  38494. this._defines.OPACITYRGB = true;
  38495. }
  38496. }
  38497. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  38498. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38499. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38500. return false;
  38501. }
  38502. this._defines.REFLECTION = true;
  38503. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38504. this._defines.INVERTCUBICMAP = true;
  38505. }
  38506. this._defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38507. switch (reflectionTexture.coordinatesMode) {
  38508. case BABYLON.Texture.CUBIC_MODE:
  38509. case BABYLON.Texture.INVCUBIC_MODE:
  38510. this._defines.REFLECTIONMAP_CUBIC = true;
  38511. break;
  38512. case BABYLON.Texture.EXPLICIT_MODE:
  38513. this._defines.REFLECTIONMAP_EXPLICIT = true;
  38514. break;
  38515. case BABYLON.Texture.PLANAR_MODE:
  38516. this._defines.REFLECTIONMAP_PLANAR = true;
  38517. break;
  38518. case BABYLON.Texture.PROJECTION_MODE:
  38519. this._defines.REFLECTIONMAP_PROJECTION = true;
  38520. break;
  38521. case BABYLON.Texture.SKYBOX_MODE:
  38522. this._defines.REFLECTIONMAP_SKYBOX = true;
  38523. break;
  38524. case BABYLON.Texture.SPHERICAL_MODE:
  38525. this._defines.REFLECTIONMAP_SPHERICAL = true;
  38526. break;
  38527. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38528. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38529. break;
  38530. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38531. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38532. break;
  38533. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38534. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38535. break;
  38536. }
  38537. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  38538. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  38539. if (reflectionTexture.isPMREM) {
  38540. this._defines.USEPMREMREFLECTION = true;
  38541. }
  38542. }
  38543. }
  38544. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38545. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38546. return false;
  38547. }
  38548. needUVs = true;
  38549. this._defines.LIGHTMAP = true;
  38550. this._defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38551. }
  38552. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38553. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38554. return false;
  38555. }
  38556. needUVs = true;
  38557. this._defines.EMISSIVE = true;
  38558. }
  38559. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38560. if (this._metallicTexture) {
  38561. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38562. return false;
  38563. }
  38564. needUVs = true;
  38565. this._defines.METALLICWORKFLOW = true;
  38566. this._defines.METALLICMAP = true;
  38567. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38568. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38569. this._defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38570. this._defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38571. }
  38572. else if (this._reflectivityTexture) {
  38573. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38574. return false;
  38575. }
  38576. needUVs = true;
  38577. this._defines.REFLECTIVITY = true;
  38578. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38579. this._defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38580. }
  38581. if (this._microSurfaceTexture) {
  38582. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38583. return false;
  38584. }
  38585. needUVs = true;
  38586. this._defines.MICROSURFACEMAP = true;
  38587. }
  38588. }
  38589. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38590. // Bump texure can not be none blocking.
  38591. if (!this._bumpTexture.isReady()) {
  38592. return false;
  38593. }
  38594. needUVs = true;
  38595. this._defines.BUMP = true;
  38596. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38597. this._defines.PARALLAX = true;
  38598. if (this._useParallaxOcclusion) {
  38599. this._defines.PARALLAXOCCLUSION = true;
  38600. }
  38601. }
  38602. if (this._invertNormalMapX) {
  38603. this._defines.INVERTNORMALMAPX = true;
  38604. }
  38605. if (this._invertNormalMapY) {
  38606. this._defines.INVERTNORMALMAPY = true;
  38607. }
  38608. if (scene._mirroredCameraPosition) {
  38609. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  38610. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  38611. }
  38612. this._defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  38613. }
  38614. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38615. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38616. return false;
  38617. }
  38618. needUVs = true;
  38619. this._defines.REFRACTION = true;
  38620. this._defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38621. if (this._linkRefractionWithTransparency) {
  38622. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38623. }
  38624. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  38625. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  38626. if (this._refractionTexture.isPMREM) {
  38627. this._defines.USEPMREMREFRACTION = true;
  38628. }
  38629. }
  38630. }
  38631. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  38632. // Color Grading texure can not be none blocking.
  38633. if (!this._cameraColorGradingTexture.isReady()) {
  38634. return false;
  38635. }
  38636. this._defines.CAMERACOLORGRADING = true;
  38637. }
  38638. if (!this.backFaceCulling && this._twoSidedLighting) {
  38639. this._defines.TWOSIDEDLIGHTING = true;
  38640. }
  38641. }
  38642. this._defines.LDROUTPUT = this._ldrOutput;
  38643. // Effect
  38644. if (scene.clipPlane) {
  38645. this._defines.CLIPPLANE = true;
  38646. }
  38647. this._defines.ALPHATESTVALUE = this._alphaCutOff;
  38648. if (engine.getAlphaTesting() || this._forceAlphaTest) {
  38649. this._defines.ALPHATEST = true;
  38650. }
  38651. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38652. this._defines.ALPHAFROMALBEDO = true;
  38653. }
  38654. if (this._useEmissiveAsIllumination) {
  38655. this._defines.EMISSIVEASILLUMINATION = true;
  38656. }
  38657. if (this.useLogarithmicDepth) {
  38658. this._defines.LOGARITHMICDEPTH = true;
  38659. }
  38660. if (this._cameraContrast != 1) {
  38661. this._defines.CAMERACONTRAST = true;
  38662. }
  38663. if (this._cameraExposure != 1) {
  38664. this._defines.CAMERATONEMAP = true;
  38665. }
  38666. if (this._cameraColorCurves) {
  38667. this._defines.CAMERACOLORCURVES = true;
  38668. }
  38669. // Point size
  38670. if (this.pointsCloud || scene.forcePointsCloud) {
  38671. this._defines.POINTSIZE = true;
  38672. }
  38673. // Fog
  38674. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38675. this._defines.FOG = true;
  38676. }
  38677. if (BABYLON.StandardMaterial.FresnelEnabled) {
  38678. // Fresnel
  38679. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  38680. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  38681. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  38682. this._defines.OPACITYFRESNEL = true;
  38683. }
  38684. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  38685. this._defines.EMISSIVEFRESNEL = true;
  38686. }
  38687. this._defines.FRESNEL = true;
  38688. }
  38689. }
  38690. if (this._defines.SPECULARTERM && this._useSpecularOverAlpha) {
  38691. this._defines.SPECULAROVERALPHA = true;
  38692. }
  38693. if (this._usePhysicalLightFalloff) {
  38694. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  38695. }
  38696. if (this._useRadianceOverAlpha) {
  38697. this._defines.RADIANCEOVERALPHA = true;
  38698. }
  38699. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38700. this._defines.METALLICWORKFLOW = true;
  38701. }
  38702. // Attribs
  38703. if (mesh) {
  38704. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38705. mesh.createNormals(true);
  38706. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  38707. }
  38708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38709. this._defines.NORMAL = true;
  38710. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38711. this._defines.TANGENT = true;
  38712. }
  38713. }
  38714. if (needUVs) {
  38715. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38716. this._defines.UV1 = true;
  38717. }
  38718. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38719. this._defines.UV2 = true;
  38720. }
  38721. }
  38722. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38723. this._defines.VERTEXCOLOR = true;
  38724. if (mesh.hasVertexAlpha) {
  38725. this._defines.VERTEXALPHA = true;
  38726. }
  38727. }
  38728. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38729. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  38730. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  38731. }
  38732. // Instances
  38733. if (useInstances) {
  38734. this._defines.INSTANCES = true;
  38735. }
  38736. if (mesh.morphTargetManager) {
  38737. var manager = mesh.morphTargetManager;
  38738. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  38739. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  38740. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  38741. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  38742. }
  38743. }
  38744. // Get correct effect
  38745. if (!this._defines.isEqual(this._cachedDefines)) {
  38746. this._defines.cloneTo(this._cachedDefines);
  38747. scene.resetCachedMaterial();
  38748. // Fallbacks
  38749. var fallbacks = new BABYLON.EffectFallbacks();
  38750. if (this._defines.REFLECTION) {
  38751. fallbacks.addFallback(0, "REFLECTION");
  38752. }
  38753. if (this._defines.REFRACTION) {
  38754. fallbacks.addFallback(0, "REFRACTION");
  38755. }
  38756. if (this._defines.REFLECTIVITY) {
  38757. fallbacks.addFallback(0, "REFLECTIVITY");
  38758. }
  38759. if (this._defines.BUMP) {
  38760. fallbacks.addFallback(0, "BUMP");
  38761. }
  38762. if (this._defines.PARALLAX) {
  38763. fallbacks.addFallback(1, "PARALLAX");
  38764. }
  38765. if (this._defines.PARALLAXOCCLUSION) {
  38766. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38767. }
  38768. if (this._defines.SPECULAROVERALPHA) {
  38769. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38770. }
  38771. if (this._defines.FOG) {
  38772. fallbacks.addFallback(1, "FOG");
  38773. }
  38774. if (this._defines.POINTSIZE) {
  38775. fallbacks.addFallback(0, "POINTSIZE");
  38776. }
  38777. if (this._defines.LOGARITHMICDEPTH) {
  38778. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38779. }
  38780. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this._maxSimultaneousLights);
  38781. if (this._defines.SPECULARTERM) {
  38782. fallbacks.addFallback(0, "SPECULARTERM");
  38783. }
  38784. if (this._defines.OPACITYFRESNEL) {
  38785. fallbacks.addFallback(1, "OPACITYFRESNEL");
  38786. }
  38787. if (this._defines.EMISSIVEFRESNEL) {
  38788. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  38789. }
  38790. if (this._defines.FRESNEL) {
  38791. fallbacks.addFallback(3, "FRESNEL");
  38792. }
  38793. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  38794. fallbacks.addCPUSkinningFallback(0, mesh);
  38795. }
  38796. //Attributes
  38797. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38798. if (this._defines.NORMAL) {
  38799. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38800. }
  38801. if (this._defines.TANGENT) {
  38802. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38803. }
  38804. if (this._defines.UV1) {
  38805. attribs.push(BABYLON.VertexBuffer.UVKind);
  38806. }
  38807. if (this._defines.UV2) {
  38808. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38809. }
  38810. if (this._defines.VERTEXCOLOR) {
  38811. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38812. }
  38813. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  38814. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  38815. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  38816. // Legacy browser patch
  38817. var join = this._defines.toString();
  38818. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38819. "vFogInfos", "vFogColor", "pointSize",
  38820. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38821. "mBones",
  38822. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38823. "depthValues",
  38824. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  38825. "vLightingIntensity",
  38826. "logarithmicDepthConstant",
  38827. "vSphericalX", "vSphericalY", "vSphericalZ",
  38828. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38829. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38830. "vMicrosurfaceTextureLods",
  38831. "vCameraInfos"
  38832. ];
  38833. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38834. var uniformBuffers = ["Material", "Scene"];
  38835. if (this._defines.CAMERACOLORCURVES) {
  38836. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  38837. }
  38838. if (this._defines.CAMERACOLORGRADING) {
  38839. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  38840. }
  38841. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38842. uniformsNames: uniforms,
  38843. uniformBuffersNames: uniformBuffers,
  38844. samplers: samplers,
  38845. defines: this._defines,
  38846. maxSimultaneousLights: this._maxSimultaneousLights
  38847. });
  38848. var onCompiled = function (effect) {
  38849. if (this.onCompiled) {
  38850. this.onCompiled(effect);
  38851. }
  38852. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38853. }.bind(this);
  38854. this._effect = scene.getEngine().createEffect("pbr", {
  38855. attributes: attribs,
  38856. uniformsNames: uniforms,
  38857. uniformBuffersNames: uniformBuffers,
  38858. samplers: samplers,
  38859. defines: join,
  38860. fallbacks: fallbacks,
  38861. onCompiled: onCompiled,
  38862. onError: this.onError,
  38863. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  38864. }, engine);
  38865. this.buildUniformLayout();
  38866. }
  38867. if (!this._effect.isReady()) {
  38868. return false;
  38869. }
  38870. this._renderId = scene.getRenderId();
  38871. this._wasPreviouslyReady = true;
  38872. return true;
  38873. };
  38874. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38875. // Order is important !
  38876. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38877. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38878. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38879. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38880. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38881. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38882. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38883. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38884. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38885. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38886. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38887. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38888. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38889. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38890. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38891. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38892. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38893. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38894. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38895. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38896. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38897. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38898. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38899. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  38900. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38901. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38902. this._uniformBuffer.addUniform("opacityParts", 4);
  38903. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38904. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38905. this._uniformBuffer.addUniform("pointSize", 1);
  38906. this._uniformBuffer.create();
  38907. };
  38908. PBRBaseMaterial.prototype.unbind = function () {
  38909. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38910. this._uniformBuffer.setTexture("reflection2DSampler", null);
  38911. }
  38912. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38913. this._uniformBuffer.setTexture("refraction2DSampler", null);
  38914. }
  38915. _super.prototype.unbind.call(this);
  38916. };
  38917. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38918. this._effect.setMatrix("world", world);
  38919. };
  38920. PBRBaseMaterial.prototype.bind = function (world, mesh) {
  38921. this._myScene = this.getScene();
  38922. var effect = this._effect;
  38923. // Matrices
  38924. this.bindOnlyWorldMatrix(world);
  38925. // Bones
  38926. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38927. if (this._myScene.getCachedMaterial() !== this) {
  38928. this._uniformBuffer.bindToEffect(effect, "Material");
  38929. this.bindViewProjection(effect);
  38930. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38931. // Fresnel
  38932. if (BABYLON.StandardMaterial.FresnelEnabled) {
  38933. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  38934. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  38935. }
  38936. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  38937. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  38938. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  38939. }
  38940. }
  38941. // Texture uniforms
  38942. if (this._myScene.texturesEnabled) {
  38943. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38944. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  38945. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  38946. }
  38947. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38948. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  38949. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  38950. }
  38951. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38952. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38953. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  38954. }
  38955. var reflectionTexture = this._reflectionTexture || this._myScene.environmentTexture;
  38956. ;
  38957. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38958. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  38959. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  38960. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  38961. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  38962. this._effect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  38963. this._effect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  38964. this._effect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  38965. this._effect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  38966. this._effect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  38967. this._effect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  38968. this._effect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  38969. this._effect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  38970. this._effect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  38971. }
  38972. }
  38973. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38974. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38975. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  38976. }
  38977. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38978. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38979. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  38980. }
  38981. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38982. if (this._metallicTexture) {
  38983. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  38984. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  38985. }
  38986. else if (this._reflectivityTexture) {
  38987. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  38988. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  38989. }
  38990. if (this._microSurfaceTexture) {
  38991. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  38992. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  38993. }
  38994. }
  38995. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38996. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  38997. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  38998. }
  38999. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39000. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  39001. var depth = 1.0;
  39002. if (!this._refractionTexture.isCube) {
  39003. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39004. if (this._refractionTexture.depth) {
  39005. depth = this._refractionTexture.depth;
  39006. }
  39007. }
  39008. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39009. }
  39010. if ((reflectionTexture || this._refractionTexture)) {
  39011. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  39012. }
  39013. }
  39014. // Point size
  39015. if (this.pointsCloud) {
  39016. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39017. }
  39018. // Colors
  39019. if (this._defines.METALLICWORKFLOW) {
  39020. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39021. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39022. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39023. }
  39024. else {
  39025. // GAMMA CORRECTION.
  39026. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  39027. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  39028. }
  39029. // GAMMA CORRECTION.
  39030. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  39031. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  39032. // GAMMA CORRECTION.
  39033. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  39034. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  39035. // GAMMA CORRECTION.
  39036. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  39037. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  39038. // Misc
  39039. this._lightingInfos.x = this._directIntensity;
  39040. this._lightingInfos.y = this._emissiveIntensity;
  39041. this._lightingInfos.z = this._environmentIntensity;
  39042. this._lightingInfos.w = this._specularIntensity;
  39043. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39044. }
  39045. // Textures
  39046. if (this._myScene.texturesEnabled) {
  39047. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39048. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39049. }
  39050. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39051. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39052. }
  39053. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39054. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39055. }
  39056. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39057. if (reflectionTexture.isCube) {
  39058. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  39059. }
  39060. else {
  39061. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  39062. }
  39063. }
  39064. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39065. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39066. }
  39067. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39068. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39069. }
  39070. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39071. if (this._metallicTexture) {
  39072. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39073. }
  39074. else if (this._reflectivityTexture) {
  39075. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39076. }
  39077. if (this._microSurfaceTexture) {
  39078. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39079. }
  39080. }
  39081. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39082. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39083. }
  39084. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39085. if (this._refractionTexture.isCube) {
  39086. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  39087. }
  39088. else {
  39089. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  39090. }
  39091. }
  39092. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  39093. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._effect);
  39094. }
  39095. }
  39096. // Clip plane
  39097. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  39098. // Colors
  39099. this._myScene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39100. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  39101. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39102. }
  39103. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  39104. // Lights
  39105. if (this._myScene.lightsEnabled && !this._disableLighting) {
  39106. BABYLON.PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39107. }
  39108. // View
  39109. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39110. this.bindView(effect);
  39111. }
  39112. // Fog
  39113. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  39114. // Morph targets
  39115. if (this._defines.NUM_MORPH_INFLUENCERS) {
  39116. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  39117. }
  39118. this._cameraInfos.x = this._cameraExposure;
  39119. this._cameraInfos.y = this._cameraContrast;
  39120. effect.setVector4("vCameraInfos", this._cameraInfos);
  39121. if (this._cameraColorCurves) {
  39122. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._effect);
  39123. }
  39124. // Log. depth
  39125. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  39126. }
  39127. this._uniformBuffer.update();
  39128. this._afterBind(mesh);
  39129. this._myScene = null;
  39130. };
  39131. PBRBaseMaterial.prototype.getAnimatables = function () {
  39132. var results = [];
  39133. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39134. results.push(this._albedoTexture);
  39135. }
  39136. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39137. results.push(this._ambientTexture);
  39138. }
  39139. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39140. results.push(this._opacityTexture);
  39141. }
  39142. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39143. results.push(this._reflectionTexture);
  39144. }
  39145. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39146. results.push(this._emissiveTexture);
  39147. }
  39148. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39149. results.push(this._metallicTexture);
  39150. }
  39151. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39152. results.push(this._reflectivityTexture);
  39153. }
  39154. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39155. results.push(this._bumpTexture);
  39156. }
  39157. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39158. results.push(this._lightmapTexture);
  39159. }
  39160. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39161. results.push(this._refractionTexture);
  39162. }
  39163. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  39164. results.push(this._cameraColorGradingTexture);
  39165. }
  39166. return results;
  39167. };
  39168. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39169. if (forceDisposeTextures) {
  39170. if (this._albedoTexture) {
  39171. this._albedoTexture.dispose();
  39172. }
  39173. if (this._ambientTexture) {
  39174. this._ambientTexture.dispose();
  39175. }
  39176. if (this._opacityTexture) {
  39177. this._opacityTexture.dispose();
  39178. }
  39179. if (this._reflectionTexture) {
  39180. this._reflectionTexture.dispose();
  39181. }
  39182. if (this._emissiveTexture) {
  39183. this._emissiveTexture.dispose();
  39184. }
  39185. if (this._metallicTexture) {
  39186. this._metallicTexture.dispose();
  39187. }
  39188. if (this._reflectivityTexture) {
  39189. this._reflectivityTexture.dispose();
  39190. }
  39191. if (this._bumpTexture) {
  39192. this._bumpTexture.dispose();
  39193. }
  39194. if (this._lightmapTexture) {
  39195. this._lightmapTexture.dispose();
  39196. }
  39197. if (this._refractionTexture) {
  39198. this._refractionTexture.dispose();
  39199. }
  39200. if (this._cameraColorGradingTexture) {
  39201. this._cameraColorGradingTexture.dispose();
  39202. }
  39203. }
  39204. this._renderTargets.dispose();
  39205. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39206. };
  39207. return PBRBaseMaterial;
  39208. }(BABYLON.Material));
  39209. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  39210. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39211. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  39212. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  39213. __decorate([
  39214. BABYLON.serialize()
  39215. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39216. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39217. })(BABYLON || (BABYLON = {}));
  39218. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39219. var BABYLON;
  39220. (function (BABYLON) {
  39221. var Internals;
  39222. (function (Internals) {
  39223. /**
  39224. * The Physically based simple base material of BJS.
  39225. *
  39226. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39227. * It is used as the base class for both the specGloss and metalRough conventions.
  39228. */
  39229. var PBRBaseSimpleMaterial = (function (_super) {
  39230. __extends(PBRBaseSimpleMaterial, _super);
  39231. /**
  39232. * Instantiates a new PBRMaterial instance.
  39233. *
  39234. * @param name The material name
  39235. * @param scene The scene the material will be use in.
  39236. */
  39237. function PBRBaseSimpleMaterial(name, scene) {
  39238. var _this = _super.call(this, name, scene) || this;
  39239. /**
  39240. * Number of Simultaneous lights allowed on the material.
  39241. */
  39242. _this.maxSimultaneousLights = 4;
  39243. /**
  39244. * If sets to true, disables all the lights affecting the material.
  39245. */
  39246. _this.disableLighting = false;
  39247. /**
  39248. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39249. */
  39250. _this.invertNormalMapX = false;
  39251. /**
  39252. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39253. */
  39254. _this.invertNormalMapY = false;
  39255. /**
  39256. * Emissivie color used to self-illuminate the model.
  39257. */
  39258. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39259. /**
  39260. * Occlusion Channel Strenght.
  39261. */
  39262. _this.occlusionStrength = 1.0;
  39263. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39264. _this._useEmissiveAsIllumination = true;
  39265. _this._useAmbientInGrayScale = true;
  39266. _this._useScalarInLinearSpace = true;
  39267. return _this;
  39268. }
  39269. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  39270. /**
  39271. * Gets the current transparency mode.
  39272. */
  39273. get: function () {
  39274. return this._transparencyMode;
  39275. },
  39276. /**
  39277. * Sets the transparency mode of the material.
  39278. */
  39279. set: function (value) {
  39280. this._transparencyMode = value;
  39281. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  39282. this._forceAlphaTest = true;
  39283. }
  39284. else {
  39285. this._forceAlphaTest = false;
  39286. }
  39287. },
  39288. enumerable: true,
  39289. configurable: true
  39290. });
  39291. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39292. /**
  39293. * Gets the current double sided mode.
  39294. */
  39295. get: function () {
  39296. return this._twoSidedLighting;
  39297. },
  39298. /**
  39299. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39300. */
  39301. set: function (value) {
  39302. this._twoSidedLighting = value;
  39303. this.backFaceCulling = !value;
  39304. },
  39305. enumerable: true,
  39306. configurable: true
  39307. });
  39308. /**
  39309. * Specifies wether or not the alpha value of the albedo texture should be used.
  39310. */
  39311. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  39312. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39313. };
  39314. /**
  39315. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  39316. */
  39317. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  39318. if (this._linkRefractionWithTransparency) {
  39319. return false;
  39320. }
  39321. return (this.alpha < 1.0) ||
  39322. (this._shouldUseAlphaFromAlbedoTexture() &&
  39323. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  39324. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  39325. };
  39326. /**
  39327. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  39328. */
  39329. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  39330. if (this._linkRefractionWithTransparency) {
  39331. return false;
  39332. }
  39333. return this._shouldUseAlphaFromAlbedoTexture() &&
  39334. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  39335. };
  39336. return PBRBaseSimpleMaterial;
  39337. }(BABYLON.PBRBaseMaterial));
  39338. __decorate([
  39339. BABYLON.serialize(),
  39340. BABYLON.expandToProperty(null)
  39341. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39342. __decorate([
  39343. BABYLON.serialize(),
  39344. BABYLON.expandToProperty(null)
  39345. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39346. __decorate([
  39347. BABYLON.serializeAsTexture(),
  39348. BABYLON.expandToProperty(null, "_reflectionTexture")
  39349. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39350. __decorate([
  39351. BABYLON.serialize(),
  39352. BABYLON.expandToProperty(null)
  39353. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39354. __decorate([
  39355. BABYLON.serialize(),
  39356. BABYLON.expandToProperty(null)
  39357. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39358. __decorate([
  39359. BABYLON.serializeAsTexture(),
  39360. BABYLON.expandToProperty(null, "_bumpTexture")
  39361. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39362. __decorate([
  39363. BABYLON.serializeAsColor3("emissive"),
  39364. BABYLON.expandToProperty(null)
  39365. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39366. __decorate([
  39367. BABYLON.serializeAsTexture(),
  39368. BABYLON.expandToProperty(null)
  39369. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39370. __decorate([
  39371. BABYLON.serialize(),
  39372. BABYLON.expandToProperty(null, "_ambientTextureStrength")
  39373. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39374. __decorate([
  39375. BABYLON.serializeAsTexture(),
  39376. BABYLON.expandToProperty(null, "_ambientTexture")
  39377. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39378. __decorate([
  39379. BABYLON.serialize(),
  39380. BABYLON.expandToProperty(null, "_alphaCutOff")
  39381. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39382. __decorate([
  39383. BABYLON.serialize()
  39384. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  39385. __decorate([
  39386. BABYLON.serialize()
  39387. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39388. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39389. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39390. })(BABYLON || (BABYLON = {}));
  39391. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39392. var BABYLON;
  39393. (function (BABYLON) {
  39394. /**
  39395. * The Physically based material of BJS.
  39396. *
  39397. * This offers the main features of a standard PBR material.
  39398. * For more information, please refer to the documentation :
  39399. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39400. */
  39401. var PBRMaterial = (function (_super) {
  39402. __extends(PBRMaterial, _super);
  39403. /**
  39404. * Instantiates a new PBRMaterial instance.
  39405. *
  39406. * @param name The material name
  39407. * @param scene The scene the material will be use in.
  39408. */
  39409. function PBRMaterial(name, scene) {
  39410. var _this = _super.call(this, name, scene) || this;
  39411. /**
  39412. * Intensity of the direct lights e.g. the four lights available in your scene.
  39413. * This impacts both the direct diffuse and specular highlights.
  39414. */
  39415. _this.directIntensity = 1.0;
  39416. /**
  39417. * Intensity of the emissive part of the material.
  39418. * This helps controlling the emissive effect without modifying the emissive color.
  39419. */
  39420. _this.emissiveIntensity = 1.0;
  39421. /**
  39422. * Intensity of the environment e.g. how much the environment will light the object
  39423. * either through harmonics for rough material or through the refelction for shiny ones.
  39424. */
  39425. _this.environmentIntensity = 1.0;
  39426. /**
  39427. * This is a special control allowing the reduction of the specular highlights coming from the
  39428. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39429. */
  39430. _this.specularIntensity = 1.0;
  39431. /**
  39432. * Debug Control allowing disabling the bump map on this material.
  39433. */
  39434. _this.disableBumpMap = false;
  39435. /**
  39436. * The camera exposure used on this material.
  39437. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39438. * This corresponds to a photographic exposure.
  39439. */
  39440. _this.cameraExposure = 1.0;
  39441. /**
  39442. * The camera contrast used on this material.
  39443. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  39444. */
  39445. _this.cameraContrast = 1.0;
  39446. /**
  39447. * Color Grading 2D Lookup Texture.
  39448. * This allows special effects like sepia, black and white to sixties rendering style.
  39449. */
  39450. _this.cameraColorGradingTexture = null;
  39451. /**
  39452. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39453. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39454. * 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;
  39455. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39456. */
  39457. _this.cameraColorCurves = null;
  39458. /**
  39459. * AKA Occlusion Texture Intensity in other nomenclature.
  39460. */
  39461. _this.ambientTextureStrength = 1.0;
  39462. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39463. /**
  39464. * AKA Diffuse Color in other nomenclature.
  39465. */
  39466. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39467. /**
  39468. * AKA Specular Color in other nomenclature.
  39469. */
  39470. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39471. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39472. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39473. /**
  39474. * AKA Glossiness in other nomenclature.
  39475. */
  39476. _this.microSurface = 0.9;
  39477. /**
  39478. * source material index of refraction (IOR)' / 'destination material IOR.
  39479. */
  39480. _this.indexOfRefraction = 0.66;
  39481. /**
  39482. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39483. */
  39484. _this.invertRefractionY = false;
  39485. /**
  39486. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39487. * Materials half opaque for instance using refraction could benefit from this control.
  39488. */
  39489. _this.linkRefractionWithTransparency = false;
  39490. _this.useLightmapAsShadowmap = false;
  39491. /**
  39492. * In this mode, the emissive informtaion will always be added to the lighting once.
  39493. * A light for instance can be thought as emissive.
  39494. */
  39495. _this.useEmissiveAsIllumination = false;
  39496. /**
  39497. * Secifies that the alpha is coming form the albedo channel alpha channel.
  39498. */
  39499. _this.useAlphaFromAlbedoTexture = false;
  39500. /**
  39501. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39502. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39503. */
  39504. _this.useSpecularOverAlpha = true;
  39505. /**
  39506. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39507. */
  39508. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39509. /**
  39510. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39511. */
  39512. _this.useRoughnessFromMetallicTextureAlpha = true;
  39513. /**
  39514. * Specifies if the metallic texture contains the roughness information in its green channel.
  39515. */
  39516. _this.useRoughnessFromMetallicTextureGreen = false;
  39517. /**
  39518. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39519. */
  39520. _this.useMetallnessFromMetallicTextureBlue = false;
  39521. /**
  39522. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39523. */
  39524. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39525. /**
  39526. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39527. */
  39528. _this.useAmbientInGrayScale = false;
  39529. /**
  39530. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39531. * The material will try to infer what glossiness each pixel should be.
  39532. */
  39533. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39534. /**
  39535. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  39536. * the creation of the material.
  39537. */
  39538. _this.useScalarInLinearSpace = false;
  39539. /**
  39540. * BJS is using an harcoded light falloff based on a manually sets up range.
  39541. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39542. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39543. */
  39544. _this.usePhysicalLightFalloff = true;
  39545. /**
  39546. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39547. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39548. */
  39549. _this.useRadianceOverAlpha = true;
  39550. /**
  39551. * Allows using the bump map in parallax mode.
  39552. */
  39553. _this.useParallax = false;
  39554. /**
  39555. * Allows using the bump map in parallax occlusion mode.
  39556. */
  39557. _this.useParallaxOcclusion = false;
  39558. /**
  39559. * Controls the scale bias of the parallax mode.
  39560. */
  39561. _this.parallaxScaleBias = 0.05;
  39562. /**
  39563. * If sets to true, disables all the lights affecting the material.
  39564. */
  39565. _this.disableLighting = false;
  39566. /**
  39567. * Number of Simultaneous lights allowed on the material.
  39568. */
  39569. _this.maxSimultaneousLights = 4;
  39570. /**
  39571. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39572. */
  39573. _this.invertNormalMapX = false;
  39574. /**
  39575. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39576. */
  39577. _this.invertNormalMapY = false;
  39578. /**
  39579. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39580. */
  39581. _this.twoSidedLighting = false;
  39582. return _this;
  39583. }
  39584. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39585. /**
  39586. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39587. */
  39588. get: function () {
  39589. return this._PBRMATERIAL_OPAQUE;
  39590. },
  39591. enumerable: true,
  39592. configurable: true
  39593. });
  39594. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39595. /**
  39596. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39597. */
  39598. get: function () {
  39599. return this._PBRMATERIAL_ALPHATEST;
  39600. },
  39601. enumerable: true,
  39602. configurable: true
  39603. });
  39604. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39605. /**
  39606. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39607. */
  39608. get: function () {
  39609. return this._PBRMATERIAL_ALPHABLEND;
  39610. },
  39611. enumerable: true,
  39612. configurable: true
  39613. });
  39614. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39615. /**
  39616. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39617. * They are also discarded below the alpha cutoff threshold to improve performances.
  39618. */
  39619. get: function () {
  39620. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39621. },
  39622. enumerable: true,
  39623. configurable: true
  39624. });
  39625. PBRMaterial.prototype.getClassName = function () {
  39626. return "PBRMaterial";
  39627. };
  39628. PBRMaterial.prototype.clone = function (name) {
  39629. var _this = this;
  39630. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39631. };
  39632. PBRMaterial.prototype.serialize = function () {
  39633. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39634. serializationObject.customType = "BABYLON.PBRMaterial";
  39635. return serializationObject;
  39636. };
  39637. // Statics
  39638. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39639. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39640. };
  39641. return PBRMaterial;
  39642. }(BABYLON.PBRBaseMaterial));
  39643. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39644. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39645. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39646. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39647. __decorate([
  39648. BABYLON.serialize(),
  39649. BABYLON.expandToProperty(null)
  39650. ], PBRMaterial.prototype, "directIntensity", void 0);
  39651. __decorate([
  39652. BABYLON.serialize(),
  39653. BABYLON.expandToProperty(null)
  39654. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39655. __decorate([
  39656. BABYLON.serialize(),
  39657. BABYLON.expandToProperty(null)
  39658. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39659. __decorate([
  39660. BABYLON.serialize(),
  39661. BABYLON.expandToProperty(null)
  39662. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39663. __decorate([
  39664. BABYLON.serialize(),
  39665. BABYLON.expandToProperty(null)
  39666. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39667. __decorate([
  39668. BABYLON.serialize(),
  39669. BABYLON.expandToProperty(null)
  39670. ], PBRMaterial.prototype, "cameraExposure", void 0);
  39671. __decorate([
  39672. BABYLON.serialize(),
  39673. BABYLON.expandToProperty(null)
  39674. ], PBRMaterial.prototype, "cameraContrast", void 0);
  39675. __decorate([
  39676. BABYLON.serializeAsTexture(),
  39677. BABYLON.expandToProperty(null)
  39678. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  39679. __decorate([
  39680. BABYLON.serializeAsColorCurves(),
  39681. BABYLON.expandToProperty(null)
  39682. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  39683. __decorate([
  39684. BABYLON.serializeAsTexture(),
  39685. BABYLON.expandToProperty(null)
  39686. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39687. __decorate([
  39688. BABYLON.serializeAsTexture(),
  39689. BABYLON.expandToProperty(null)
  39690. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39691. __decorate([
  39692. BABYLON.serialize(),
  39693. BABYLON.expandToProperty(null)
  39694. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39695. __decorate([
  39696. BABYLON.serializeAsTexture(),
  39697. BABYLON.expandToProperty(null)
  39698. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39699. __decorate([
  39700. BABYLON.serializeAsTexture(),
  39701. BABYLON.expandToProperty(null)
  39702. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39703. __decorate([
  39704. BABYLON.serializeAsTexture(),
  39705. BABYLON.expandToProperty(null)
  39706. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39707. __decorate([
  39708. BABYLON.serializeAsTexture(),
  39709. BABYLON.expandToProperty(null)
  39710. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39711. __decorate([
  39712. BABYLON.serializeAsTexture(),
  39713. BABYLON.expandToProperty(null)
  39714. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39715. __decorate([
  39716. BABYLON.serialize(),
  39717. BABYLON.expandToProperty(null)
  39718. ], PBRMaterial.prototype, "metallic", void 0);
  39719. __decorate([
  39720. BABYLON.serialize(),
  39721. BABYLON.expandToProperty(null)
  39722. ], PBRMaterial.prototype, "roughness", void 0);
  39723. __decorate([
  39724. BABYLON.serializeAsTexture(),
  39725. BABYLON.expandToProperty(null)
  39726. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39727. __decorate([
  39728. BABYLON.serializeAsTexture(),
  39729. BABYLON.expandToProperty(null)
  39730. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39731. __decorate([
  39732. BABYLON.serializeAsTexture(),
  39733. BABYLON.expandToProperty(null)
  39734. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39735. __decorate([
  39736. BABYLON.serializeAsTexture(),
  39737. BABYLON.expandToProperty(null)
  39738. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39739. __decorate([
  39740. BABYLON.serializeAsColor3("ambient"),
  39741. BABYLON.expandToProperty(null)
  39742. ], PBRMaterial.prototype, "ambientColor", void 0);
  39743. __decorate([
  39744. BABYLON.serializeAsColor3("albedo"),
  39745. BABYLON.expandToProperty(null)
  39746. ], PBRMaterial.prototype, "albedoColor", void 0);
  39747. __decorate([
  39748. BABYLON.serializeAsColor3("reflectivity"),
  39749. BABYLON.expandToProperty(null)
  39750. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39751. __decorate([
  39752. BABYLON.serializeAsColor3("reflection"),
  39753. BABYLON.expandToProperty(null)
  39754. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39755. __decorate([
  39756. BABYLON.serializeAsColor3("emissive"),
  39757. BABYLON.expandToProperty(null)
  39758. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39759. __decorate([
  39760. BABYLON.serialize(),
  39761. BABYLON.expandToProperty(null)
  39762. ], PBRMaterial.prototype, "microSurface", void 0);
  39763. __decorate([
  39764. BABYLON.serialize(),
  39765. BABYLON.expandToProperty(null)
  39766. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39767. __decorate([
  39768. BABYLON.serialize(),
  39769. BABYLON.expandToProperty(null)
  39770. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39771. __decorate([
  39772. BABYLON.serializeAsFresnelParameters(),
  39773. BABYLON.expandToProperty(null)
  39774. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  39775. __decorate([
  39776. BABYLON.serializeAsFresnelParameters(),
  39777. BABYLON.expandToProperty(null)
  39778. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  39779. __decorate([
  39780. BABYLON.serialize(),
  39781. BABYLON.expandToProperty(null)
  39782. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39783. __decorate([
  39784. BABYLON.serialize(),
  39785. BABYLON.expandToProperty(null)
  39786. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39787. __decorate([
  39788. BABYLON.serialize(),
  39789. BABYLON.expandToProperty(null)
  39790. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39791. __decorate([
  39792. BABYLON.serialize(),
  39793. BABYLON.expandToProperty(null)
  39794. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39795. __decorate([
  39796. BABYLON.serialize(),
  39797. BABYLON.expandToProperty(null)
  39798. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39799. __decorate([
  39800. BABYLON.serialize(),
  39801. BABYLON.expandToProperty(null)
  39802. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39803. __decorate([
  39804. BABYLON.serialize(),
  39805. BABYLON.expandToProperty(null)
  39806. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39807. __decorate([
  39808. BABYLON.serialize(),
  39809. BABYLON.expandToProperty(null)
  39810. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39811. __decorate([
  39812. BABYLON.serialize(),
  39813. BABYLON.expandToProperty(null)
  39814. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39815. __decorate([
  39816. BABYLON.serialize(),
  39817. BABYLON.expandToProperty(null)
  39818. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39819. __decorate([
  39820. BABYLON.serialize(),
  39821. BABYLON.expandToProperty(null)
  39822. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39823. __decorate([
  39824. BABYLON.serialize(),
  39825. BABYLON.expandToProperty(null)
  39826. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39827. __decorate([
  39828. BABYLON.serialize(),
  39829. BABYLON.expandToProperty(null)
  39830. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  39831. __decorate([
  39832. BABYLON.serialize(),
  39833. BABYLON.expandToProperty(null)
  39834. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39835. __decorate([
  39836. BABYLON.serialize(),
  39837. BABYLON.expandToProperty(null)
  39838. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39839. __decorate([
  39840. BABYLON.serialize(),
  39841. BABYLON.expandToProperty(null)
  39842. ], PBRMaterial.prototype, "useParallax", void 0);
  39843. __decorate([
  39844. BABYLON.serialize(),
  39845. BABYLON.expandToProperty(null)
  39846. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39847. __decorate([
  39848. BABYLON.serialize(),
  39849. BABYLON.expandToProperty(null)
  39850. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39851. __decorate([
  39852. BABYLON.serialize(),
  39853. BABYLON.expandToProperty(null)
  39854. ], PBRMaterial.prototype, "disableLighting", void 0);
  39855. __decorate([
  39856. BABYLON.serialize(),
  39857. BABYLON.expandToProperty(null)
  39858. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  39859. __decorate([
  39860. BABYLON.serialize(),
  39861. BABYLON.expandToProperty(null)
  39862. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  39863. __decorate([
  39864. BABYLON.serialize(),
  39865. BABYLON.expandToProperty(null)
  39866. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  39867. __decorate([
  39868. BABYLON.serialize(),
  39869. BABYLON.expandToProperty(null)
  39870. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  39871. BABYLON.PBRMaterial = PBRMaterial;
  39872. })(BABYLON || (BABYLON = {}));
  39873. //# sourceMappingURL=babylon.pbrMaterial.js.map
  39874. var BABYLON;
  39875. (function (BABYLON) {
  39876. /**
  39877. * The PBR material of BJS following the metal roughness convention.
  39878. *
  39879. * This fits to the define PBR convention in the GLTF definition:
  39880. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  39881. */
  39882. var PBRMetallicRoughnessMaterial = (function (_super) {
  39883. __extends(PBRMetallicRoughnessMaterial, _super);
  39884. /**
  39885. * Instantiates a new PBRMetalRoughnessMaterial instance.
  39886. *
  39887. * @param name The material name
  39888. * @param scene The scene the material will be use in.
  39889. */
  39890. function PBRMetallicRoughnessMaterial(name, scene) {
  39891. var _this = _super.call(this, name, scene) || this;
  39892. _this._useRoughnessFromMetallicTextureGreen = true;
  39893. _this._useMetallnessFromMetallicTextureBlue = true;
  39894. return _this;
  39895. }
  39896. /**
  39897. * Return the currrent class name of the material.
  39898. */
  39899. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39900. return "PBRMetallicRoughnessMaterial";
  39901. };
  39902. /**
  39903. * Serialize the material to a parsable JSON object.
  39904. */
  39905. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39906. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39907. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39908. return serializationObject;
  39909. };
  39910. /**
  39911. * Parses a JSON object correponding to the serialize function.
  39912. */
  39913. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39914. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39915. };
  39916. return PBRMetallicRoughnessMaterial;
  39917. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39918. __decorate([
  39919. BABYLON.serializeAsTexture(),
  39920. BABYLON.expandToProperty(null, "_albedoColor")
  39921. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39922. __decorate([
  39923. BABYLON.serializeAsTexture(),
  39924. BABYLON.expandToProperty(null, "_albedoTexture")
  39925. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39926. __decorate([
  39927. BABYLON.serialize(),
  39928. BABYLON.expandToProperty(null)
  39929. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39930. __decorate([
  39931. BABYLON.serialize(),
  39932. BABYLON.expandToProperty(null)
  39933. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39934. __decorate([
  39935. BABYLON.serializeAsTexture(),
  39936. BABYLON.expandToProperty(null, "_metallicTexture")
  39937. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39938. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39939. })(BABYLON || (BABYLON = {}));
  39940. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39941. var BABYLON;
  39942. (function (BABYLON) {
  39943. /**
  39944. * The PBR material of BJS following the specular glossiness convention.
  39945. *
  39946. * This fits to the define PBR convention in the GLTF definition:
  39947. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39948. */
  39949. var PBRSpecularGlossinessMaterial = (function (_super) {
  39950. __extends(PBRSpecularGlossinessMaterial, _super);
  39951. /**
  39952. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39953. *
  39954. * @param name The material name
  39955. * @param scene The scene the material will be use in.
  39956. */
  39957. function PBRSpecularGlossinessMaterial(name, scene) {
  39958. var _this = _super.call(this, name, scene) || this;
  39959. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39960. return _this;
  39961. }
  39962. /**
  39963. * Return the currrent class name of the material.
  39964. */
  39965. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39966. return "PBRSpecularGlossinessMaterial";
  39967. };
  39968. /**
  39969. * Serialize the material to a parsable JSON object.
  39970. */
  39971. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39972. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39973. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39974. return serializationObject;
  39975. };
  39976. /**
  39977. * Parses a JSON object correponding to the serialize function.
  39978. */
  39979. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39980. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39981. };
  39982. return PBRSpecularGlossinessMaterial;
  39983. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39984. __decorate([
  39985. BABYLON.serializeAsColor3(),
  39986. BABYLON.expandToProperty(null, "_albedoColor")
  39987. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39988. __decorate([
  39989. BABYLON.serializeAsTexture(),
  39990. BABYLON.expandToProperty(null, "_albedoTexture")
  39991. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39992. __decorate([
  39993. BABYLON.serializeAsColor3(),
  39994. BABYLON.expandToProperty(null, "_reflectivityColor")
  39995. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39996. __decorate([
  39997. BABYLON.serialize(),
  39998. BABYLON.expandToProperty(null, "_microSurface")
  39999. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40000. __decorate([
  40001. BABYLON.serializeAsTexture(),
  40002. BABYLON.expandToProperty(null, "_reflectivityTexture")
  40003. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40004. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40005. })(BABYLON || (BABYLON = {}));
  40006. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40007. var BABYLON;
  40008. (function (BABYLON) {
  40009. var ShadowLight = (function (_super) {
  40010. __extends(ShadowLight, _super);
  40011. function ShadowLight() {
  40012. var _this = _super !== null && _super.apply(this, arguments) || this;
  40013. _this._needProjectionMatrixCompute = true;
  40014. return _this;
  40015. }
  40016. Object.defineProperty(ShadowLight.prototype, "direction", {
  40017. get: function () {
  40018. return this._direction;
  40019. },
  40020. set: function (value) {
  40021. this._direction = value;
  40022. },
  40023. enumerable: true,
  40024. configurable: true
  40025. });
  40026. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40027. get: function () {
  40028. return this._shadowMinZ;
  40029. },
  40030. set: function (value) {
  40031. this._shadowMinZ = value;
  40032. this.forceProjectionMatrixCompute();
  40033. },
  40034. enumerable: true,
  40035. configurable: true
  40036. });
  40037. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40038. get: function () {
  40039. return this._shadowMaxZ;
  40040. },
  40041. set: function (value) {
  40042. this._shadowMaxZ = value;
  40043. this.forceProjectionMatrixCompute();
  40044. },
  40045. enumerable: true,
  40046. configurable: true
  40047. });
  40048. /**
  40049. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40050. */
  40051. ShadowLight.prototype.computeTransformedInformation = function () {
  40052. if (this.parent && this.parent.getWorldMatrix) {
  40053. if (!this.transformedPosition) {
  40054. this.transformedPosition = BABYLON.Vector3.Zero();
  40055. }
  40056. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40057. // In case the direction is present.
  40058. if (this.direction) {
  40059. if (!this.transformedDirection) {
  40060. this.transformedDirection = BABYLON.Vector3.Zero();
  40061. }
  40062. BABYLON.Vector3.TransformCoordinatesToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40063. }
  40064. return true;
  40065. }
  40066. return false;
  40067. };
  40068. /**
  40069. * Return the depth scale used for the shadow map.
  40070. */
  40071. ShadowLight.prototype.getDepthScale = function () {
  40072. return 30.0;
  40073. };
  40074. /**
  40075. * Returns the light direction (Vector3) for any passed face index.
  40076. */
  40077. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40078. return this.transformedDirection ? this.transformedDirection : this.direction;
  40079. };
  40080. /**
  40081. * Returns the DirectionalLight absolute position in the World.
  40082. */
  40083. ShadowLight.prototype.getAbsolutePosition = function () {
  40084. return this.transformedPosition ? this.transformedPosition : this.position;
  40085. };
  40086. /**
  40087. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40088. * Returns the updated DirectionalLight direction (Vector3).
  40089. */
  40090. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40091. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40092. return this.direction;
  40093. };
  40094. /**
  40095. * Returns the light rotation (Vector3).
  40096. */
  40097. ShadowLight.prototype.getRotation = function () {
  40098. this.direction.normalize();
  40099. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40100. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40101. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40102. };
  40103. /**
  40104. * Boolean : false by default.
  40105. */
  40106. ShadowLight.prototype.needCube = function () {
  40107. return false;
  40108. };
  40109. /**
  40110. * Specifies wether or not the projection matrix should be recomputed this frame.
  40111. */
  40112. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40113. return this._needProjectionMatrixCompute;
  40114. };
  40115. /**
  40116. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40117. */
  40118. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40119. this._needProjectionMatrixCompute = true;
  40120. };
  40121. /**
  40122. * Get the world matrix of the sahdow lights.
  40123. */
  40124. ShadowLight.prototype._getWorldMatrix = function () {
  40125. if (!this._worldMatrix) {
  40126. this._worldMatrix = BABYLON.Matrix.Identity();
  40127. }
  40128. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40129. return this._worldMatrix;
  40130. };
  40131. /**
  40132. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40133. * Returns the light.
  40134. */
  40135. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40136. if (this.customProjectionMatrixBuilder) {
  40137. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40138. }
  40139. else {
  40140. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40141. }
  40142. return this;
  40143. };
  40144. return ShadowLight;
  40145. }(BABYLON.Light));
  40146. __decorate([
  40147. BABYLON.serializeAsVector3()
  40148. ], ShadowLight.prototype, "position", void 0);
  40149. __decorate([
  40150. BABYLON.serializeAsVector3()
  40151. ], ShadowLight.prototype, "direction", null);
  40152. __decorate([
  40153. BABYLON.serialize()
  40154. ], ShadowLight.prototype, "shadowMinZ", null);
  40155. __decorate([
  40156. BABYLON.serialize()
  40157. ], ShadowLight.prototype, "shadowMaxZ", null);
  40158. BABYLON.ShadowLight = ShadowLight;
  40159. })(BABYLON || (BABYLON = {}));
  40160. //# sourceMappingURL=babylon.shadowLight.js.map
  40161. var BABYLON;
  40162. (function (BABYLON) {
  40163. var PointLight = (function (_super) {
  40164. __extends(PointLight, _super);
  40165. /**
  40166. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40167. * A PointLight emits the light in every direction.
  40168. * It can cast shadows.
  40169. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40170. * ```javascript
  40171. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40172. * ```
  40173. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40174. */
  40175. function PointLight(name, position, scene) {
  40176. var _this = _super.call(this, name, scene) || this;
  40177. _this._shadowAngle = Math.PI / 2;
  40178. _this.position = position;
  40179. return _this;
  40180. }
  40181. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40182. /**
  40183. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40184. * This specifies what angle the shadow will use to be created.
  40185. *
  40186. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40187. */
  40188. get: function () {
  40189. return this._shadowAngle;
  40190. },
  40191. /**
  40192. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40193. * This specifies what angle the shadow will use to be created.
  40194. *
  40195. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40196. */
  40197. set: function (value) {
  40198. this._shadowAngle = value;
  40199. this.forceProjectionMatrixCompute();
  40200. },
  40201. enumerable: true,
  40202. configurable: true
  40203. });
  40204. Object.defineProperty(PointLight.prototype, "direction", {
  40205. get: function () {
  40206. return this._direction;
  40207. },
  40208. /**
  40209. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40210. */
  40211. set: function (value) {
  40212. var previousNeedCube = this.needCube();
  40213. this._direction = value;
  40214. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40215. this._shadowGenerator.recreateShadowMap();
  40216. }
  40217. },
  40218. enumerable: true,
  40219. configurable: true
  40220. });
  40221. /**
  40222. * Returns the string "PointLight"
  40223. */
  40224. PointLight.prototype.getClassName = function () {
  40225. return "PointLight";
  40226. };
  40227. /**
  40228. * Returns the integer 0.
  40229. */
  40230. PointLight.prototype.getTypeID = function () {
  40231. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40232. };
  40233. /**
  40234. * Specifies wether or not the shadowmap should be a cube texture.
  40235. */
  40236. PointLight.prototype.needCube = function () {
  40237. return !this.direction;
  40238. };
  40239. /**
  40240. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40241. */
  40242. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40243. if (this.direction) {
  40244. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40245. }
  40246. else {
  40247. switch (faceIndex) {
  40248. case 0:
  40249. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40250. case 1:
  40251. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40252. case 2:
  40253. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40254. case 3:
  40255. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40256. case 4:
  40257. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40258. case 5:
  40259. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40260. }
  40261. }
  40262. return BABYLON.Vector3.Zero();
  40263. };
  40264. /**
  40265. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40266. * - fov = PI / 2
  40267. * - aspect ratio : 1.0
  40268. * - z-near and far equal to the active camera minZ and maxZ.
  40269. * Returns the PointLight.
  40270. */
  40271. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40272. var activeCamera = this.getScene().activeCamera;
  40273. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40274. };
  40275. PointLight.prototype._buildUniformLayout = function () {
  40276. this._uniformBuffer.addUniform("vLightData", 4);
  40277. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40278. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40279. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40280. this._uniformBuffer.create();
  40281. };
  40282. /**
  40283. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40284. * Returns the PointLight.
  40285. */
  40286. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40287. if (this.computeTransformedInformation()) {
  40288. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40289. return this;
  40290. }
  40291. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40292. return this;
  40293. };
  40294. return PointLight;
  40295. }(BABYLON.ShadowLight));
  40296. __decorate([
  40297. BABYLON.serialize()
  40298. ], PointLight.prototype, "shadowAngle", null);
  40299. BABYLON.PointLight = PointLight;
  40300. })(BABYLON || (BABYLON = {}));
  40301. //# sourceMappingURL=babylon.pointLight.js.map
  40302. /// <reference path="babylon.light.ts" />
  40303. var BABYLON;
  40304. (function (BABYLON) {
  40305. var DirectionalLight = (function (_super) {
  40306. __extends(DirectionalLight, _super);
  40307. /**
  40308. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40309. * The directional light is emitted from everywhere in the given direction.
  40310. * It can cast shawdows.
  40311. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40312. */
  40313. function DirectionalLight(name, direction, scene) {
  40314. var _this = _super.call(this, name, scene) || this;
  40315. _this._shadowOrthoScale = 0.5;
  40316. _this.autoUpdateExtends = true;
  40317. // Cache
  40318. _this._orthoLeft = Number.MAX_VALUE;
  40319. _this._orthoRight = Number.MIN_VALUE;
  40320. _this._orthoTop = Number.MIN_VALUE;
  40321. _this._orthoBottom = Number.MAX_VALUE;
  40322. _this.position = direction.scale(-1.0);
  40323. _this.direction = direction;
  40324. return _this;
  40325. }
  40326. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40327. get: function () {
  40328. return this._shadowOrthoScale;
  40329. },
  40330. set: function (value) {
  40331. this._shadowOrthoScale = value;
  40332. this.forceProjectionMatrixCompute();
  40333. },
  40334. enumerable: true,
  40335. configurable: true
  40336. });
  40337. /**
  40338. * Returns the string "DirectionalLight".
  40339. */
  40340. DirectionalLight.prototype.getClassName = function () {
  40341. return "DirectionalLight";
  40342. };
  40343. /**
  40344. * Returns the integer 1.
  40345. */
  40346. DirectionalLight.prototype.getTypeID = function () {
  40347. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40348. };
  40349. /**
  40350. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40351. * Returns the DirectionalLight.
  40352. */
  40353. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40354. var activeCamera = this.getScene().activeCamera;
  40355. // Check extends
  40356. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40357. var tempVector3 = BABYLON.Vector3.Zero();
  40358. this._orthoLeft = Number.MAX_VALUE;
  40359. this._orthoRight = Number.MIN_VALUE;
  40360. this._orthoTop = Number.MIN_VALUE;
  40361. this._orthoBottom = Number.MAX_VALUE;
  40362. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40363. var mesh = renderList[meshIndex];
  40364. if (!mesh) {
  40365. continue;
  40366. }
  40367. var boundingInfo = mesh.getBoundingInfo();
  40368. if (!boundingInfo) {
  40369. continue;
  40370. }
  40371. var boundingBox = boundingInfo.boundingBox;
  40372. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40373. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40374. if (tempVector3.x < this._orthoLeft)
  40375. this._orthoLeft = tempVector3.x;
  40376. if (tempVector3.y < this._orthoBottom)
  40377. this._orthoBottom = tempVector3.y;
  40378. if (tempVector3.x > this._orthoRight)
  40379. this._orthoRight = tempVector3.x;
  40380. if (tempVector3.y > this._orthoTop)
  40381. this._orthoTop = tempVector3.y;
  40382. }
  40383. }
  40384. }
  40385. var xOffset = this._orthoRight - this._orthoLeft;
  40386. var yOffset = this._orthoTop - this._orthoBottom;
  40387. 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);
  40388. };
  40389. DirectionalLight.prototype._buildUniformLayout = function () {
  40390. this._uniformBuffer.addUniform("vLightData", 4);
  40391. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40392. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40393. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40394. this._uniformBuffer.create();
  40395. };
  40396. /**
  40397. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40398. * Returns the DirectionalLight.
  40399. */
  40400. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40401. if (this.computeTransformedInformation()) {
  40402. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40403. return this;
  40404. }
  40405. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40406. return this;
  40407. };
  40408. return DirectionalLight;
  40409. }(BABYLON.ShadowLight));
  40410. __decorate([
  40411. BABYLON.serialize()
  40412. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40413. __decorate([
  40414. BABYLON.serialize()
  40415. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40416. BABYLON.DirectionalLight = DirectionalLight;
  40417. })(BABYLON || (BABYLON = {}));
  40418. //# sourceMappingURL=babylon.directionalLight.js.map
  40419. var BABYLON;
  40420. (function (BABYLON) {
  40421. var SpotLight = (function (_super) {
  40422. __extends(SpotLight, _super);
  40423. /**
  40424. * Creates a SpotLight object in the scene with the passed parameters :
  40425. * - `position` (Vector3) is the initial SpotLight position,
  40426. * - `direction` (Vector3) is the initial SpotLight direction,
  40427. * - `angle` (float, in radians) is the spot light cone angle,
  40428. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40429. * A spot light is a simply light oriented cone.
  40430. * It can cast shadows.
  40431. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40432. */
  40433. function SpotLight(name, position, direction, angle, exponent, scene) {
  40434. var _this = _super.call(this, name, scene) || this;
  40435. _this.position = position;
  40436. _this.direction = direction;
  40437. _this.angle = angle;
  40438. _this.exponent = exponent;
  40439. return _this;
  40440. }
  40441. Object.defineProperty(SpotLight.prototype, "angle", {
  40442. get: function () {
  40443. return this._angle;
  40444. },
  40445. set: function (value) {
  40446. this._angle = value;
  40447. this.forceProjectionMatrixCompute();
  40448. },
  40449. enumerable: true,
  40450. configurable: true
  40451. });
  40452. /**
  40453. * Returns the string "SpotLight".
  40454. */
  40455. SpotLight.prototype.getClassName = function () {
  40456. return "SpotLight";
  40457. };
  40458. /**
  40459. * Returns the integer 2.
  40460. */
  40461. SpotLight.prototype.getTypeID = function () {
  40462. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40463. };
  40464. /**
  40465. * 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.
  40466. * Returns the SpotLight.
  40467. */
  40468. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40469. var activeCamera = this.getScene().activeCamera;
  40470. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40471. };
  40472. SpotLight.prototype._buildUniformLayout = function () {
  40473. this._uniformBuffer.addUniform("vLightData", 4);
  40474. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40475. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40476. this._uniformBuffer.addUniform("vLightDirection", 3);
  40477. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40478. this._uniformBuffer.create();
  40479. };
  40480. /**
  40481. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40482. * Return the SpotLight.
  40483. */
  40484. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40485. var normalizeDirection;
  40486. if (this.computeTransformedInformation()) {
  40487. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40488. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40489. }
  40490. else {
  40491. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40492. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40493. }
  40494. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40495. return this;
  40496. };
  40497. return SpotLight;
  40498. }(BABYLON.ShadowLight));
  40499. __decorate([
  40500. BABYLON.serialize()
  40501. ], SpotLight.prototype, "angle", null);
  40502. __decorate([
  40503. BABYLON.serialize()
  40504. ], SpotLight.prototype, "exponent", void 0);
  40505. BABYLON.SpotLight = SpotLight;
  40506. })(BABYLON || (BABYLON = {}));
  40507. //# sourceMappingURL=babylon.spotLight.js.map
  40508. var BABYLON;
  40509. (function (BABYLON) {
  40510. var PostProcess = (function () {
  40511. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  40512. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  40513. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40514. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  40515. if (blockCompilation === void 0) { blockCompilation = false; }
  40516. this.name = name;
  40517. this.width = -1;
  40518. this.height = -1;
  40519. this.autoClear = true;
  40520. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  40521. /*
  40522. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  40523. Can only be used on a single postprocess or on the last one of a chain.
  40524. */
  40525. this.enablePixelPerfectMode = false;
  40526. this.samples = 1;
  40527. this._reusable = false;
  40528. this._textures = new BABYLON.SmartArray(2);
  40529. this._currentRenderTextureInd = 0;
  40530. this._scaleRatio = new BABYLON.Vector2(1, 1);
  40531. this._texelSize = BABYLON.Vector2.Zero();
  40532. // Events
  40533. /**
  40534. * An event triggered when the postprocess is activated.
  40535. * @type {BABYLON.Observable}
  40536. */
  40537. this.onActivateObservable = new BABYLON.Observable();
  40538. /**
  40539. * An event triggered when the postprocess changes its size.
  40540. * @type {BABYLON.Observable}
  40541. */
  40542. this.onSizeChangedObservable = new BABYLON.Observable();
  40543. /**
  40544. * An event triggered when the postprocess applies its effect.
  40545. * @type {BABYLON.Observable}
  40546. */
  40547. this.onApplyObservable = new BABYLON.Observable();
  40548. /**
  40549. * An event triggered before rendering the postprocess
  40550. * @type {BABYLON.Observable}
  40551. */
  40552. this.onBeforeRenderObservable = new BABYLON.Observable();
  40553. /**
  40554. * An event triggered after rendering the postprocess
  40555. * @type {BABYLON.Observable}
  40556. */
  40557. this.onAfterRenderObservable = new BABYLON.Observable();
  40558. if (camera != null) {
  40559. this._camera = camera;
  40560. this._scene = camera.getScene();
  40561. camera.attachPostProcess(this);
  40562. this._engine = this._scene.getEngine();
  40563. }
  40564. else {
  40565. this._engine = engine;
  40566. }
  40567. this._options = options;
  40568. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  40569. this._reusable = reusable || false;
  40570. this._textureType = textureType;
  40571. this._samplers = samplers || [];
  40572. this._samplers.push("textureSampler");
  40573. this._fragmentUrl = fragmentUrl;
  40574. this._vertexUrl = vertexUrl;
  40575. this._parameters = parameters || [];
  40576. this._parameters.push("scale");
  40577. this._indexParameters = indexParameters;
  40578. if (!blockCompilation) {
  40579. this.updateEffect(defines);
  40580. }
  40581. }
  40582. Object.defineProperty(PostProcess.prototype, "onActivate", {
  40583. set: function (callback) {
  40584. if (this._onActivateObserver) {
  40585. this.onActivateObservable.remove(this._onActivateObserver);
  40586. }
  40587. this._onActivateObserver = this.onActivateObservable.add(callback);
  40588. },
  40589. enumerable: true,
  40590. configurable: true
  40591. });
  40592. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  40593. set: function (callback) {
  40594. if (this._onSizeChangedObserver) {
  40595. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  40596. }
  40597. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  40598. },
  40599. enumerable: true,
  40600. configurable: true
  40601. });
  40602. Object.defineProperty(PostProcess.prototype, "onApply", {
  40603. set: function (callback) {
  40604. if (this._onApplyObserver) {
  40605. this.onApplyObservable.remove(this._onApplyObserver);
  40606. }
  40607. this._onApplyObserver = this.onApplyObservable.add(callback);
  40608. },
  40609. enumerable: true,
  40610. configurable: true
  40611. });
  40612. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  40613. set: function (callback) {
  40614. if (this._onBeforeRenderObserver) {
  40615. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40616. }
  40617. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40618. },
  40619. enumerable: true,
  40620. configurable: true
  40621. });
  40622. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  40623. set: function (callback) {
  40624. if (this._onAfterRenderObserver) {
  40625. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40626. }
  40627. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40628. },
  40629. enumerable: true,
  40630. configurable: true
  40631. });
  40632. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  40633. get: function () {
  40634. return this._textures.data[this._currentRenderTextureInd];
  40635. },
  40636. enumerable: true,
  40637. configurable: true
  40638. });
  40639. PostProcess.prototype.getCamera = function () {
  40640. return this._camera;
  40641. };
  40642. Object.defineProperty(PostProcess.prototype, "texelSize", {
  40643. get: function () {
  40644. if (this._shareOutputWithPostProcess) {
  40645. return this._shareOutputWithPostProcess.texelSize;
  40646. }
  40647. return this._texelSize;
  40648. },
  40649. enumerable: true,
  40650. configurable: true
  40651. });
  40652. PostProcess.prototype.getEngine = function () {
  40653. return this._engine;
  40654. };
  40655. PostProcess.prototype.shareOutputWith = function (postProcess) {
  40656. this._disposeTextures();
  40657. this._shareOutputWithPostProcess = postProcess;
  40658. return this;
  40659. };
  40660. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters) {
  40661. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, null, null, indexParameters || this._indexParameters);
  40662. };
  40663. PostProcess.prototype.isReusable = function () {
  40664. return this._reusable;
  40665. };
  40666. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  40667. PostProcess.prototype.markTextureDirty = function () {
  40668. this.width = -1;
  40669. };
  40670. PostProcess.prototype.activate = function (camera, sourceTexture) {
  40671. var _this = this;
  40672. if (!this._shareOutputWithPostProcess) {
  40673. camera = camera || this._camera;
  40674. var scene = camera.getScene();
  40675. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  40676. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  40677. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  40678. var desiredWidth = this._options.width || requiredWidth;
  40679. var desiredHeight = this._options.height || requiredHeight;
  40680. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  40681. if (!this._options.width) {
  40682. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  40683. }
  40684. if (!this._options.height) {
  40685. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  40686. }
  40687. }
  40688. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  40689. if (this._textures.length > 0) {
  40690. for (var i = 0; i < this._textures.length; i++) {
  40691. this._engine._releaseTexture(this._textures.data[i]);
  40692. }
  40693. this._textures.reset();
  40694. }
  40695. this.width = desiredWidth;
  40696. this.height = desiredHeight;
  40697. var textureSize = { width: this.width, height: this.height };
  40698. var textureOptions = {
  40699. generateMipMaps: false,
  40700. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  40701. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  40702. samplingMode: this.renderTargetSamplingMode,
  40703. type: this._textureType
  40704. };
  40705. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40706. if (this._reusable) {
  40707. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40708. }
  40709. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  40710. this.onSizeChangedObservable.notifyObservers(this);
  40711. }
  40712. this._textures.forEach(function (texture) {
  40713. if (texture.samples !== _this.samples) {
  40714. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  40715. }
  40716. });
  40717. }
  40718. var target = this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.outputTexture : this.outputTexture;
  40719. if (this.enablePixelPerfectMode) {
  40720. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  40721. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  40722. }
  40723. else {
  40724. this._scaleRatio.copyFromFloats(1, 1);
  40725. this._engine.bindFramebuffer(target);
  40726. }
  40727. this.onActivateObservable.notifyObservers(camera);
  40728. // Clear
  40729. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  40730. if (this.clearColor) {
  40731. this._engine.clear(this.clearColor, true, true, true);
  40732. }
  40733. else {
  40734. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  40735. }
  40736. }
  40737. if (this._reusable) {
  40738. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  40739. }
  40740. };
  40741. Object.defineProperty(PostProcess.prototype, "isSupported", {
  40742. get: function () {
  40743. return this._effect.isSupported;
  40744. },
  40745. enumerable: true,
  40746. configurable: true
  40747. });
  40748. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  40749. get: function () {
  40750. if (this._shareOutputWithPostProcess) {
  40751. return this._shareOutputWithPostProcess.aspectRatio;
  40752. }
  40753. return this.width / this.height;
  40754. },
  40755. enumerable: true,
  40756. configurable: true
  40757. });
  40758. PostProcess.prototype.apply = function () {
  40759. // Check
  40760. if (!this._effect || !this._effect.isReady())
  40761. return null;
  40762. // States
  40763. this._engine.enableEffect(this._effect);
  40764. this._engine.setState(false);
  40765. this._engine.setDepthBuffer(false);
  40766. this._engine.setDepthWrite(false);
  40767. // Alpha
  40768. this._engine.setAlphaMode(this.alphaMode);
  40769. if (this.alphaConstants) {
  40770. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  40771. }
  40772. // Texture
  40773. var source = this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.outputTexture : this.outputTexture;
  40774. this._effect._bindTexture("textureSampler", source);
  40775. // Parameters
  40776. this._effect.setVector2("scale", this._scaleRatio);
  40777. this.onApplyObservable.notifyObservers(this._effect);
  40778. return this._effect;
  40779. };
  40780. PostProcess.prototype._disposeTextures = function () {
  40781. if (this._shareOutputWithPostProcess) {
  40782. return;
  40783. }
  40784. if (this._textures.length > 0) {
  40785. for (var i = 0; i < this._textures.length; i++) {
  40786. this._engine._releaseTexture(this._textures.data[i]);
  40787. }
  40788. }
  40789. this._textures.dispose();
  40790. };
  40791. PostProcess.prototype.dispose = function (camera) {
  40792. camera = camera || this._camera;
  40793. this._disposeTextures();
  40794. if (!camera) {
  40795. return;
  40796. }
  40797. camera.detachPostProcess(this);
  40798. var index = camera._postProcesses.indexOf(this);
  40799. if (index === 0 && camera._postProcesses.length > 0) {
  40800. this._camera._postProcesses[0].markTextureDirty();
  40801. }
  40802. this.onActivateObservable.clear();
  40803. this.onAfterRenderObservable.clear();
  40804. this.onApplyObservable.clear();
  40805. this.onBeforeRenderObservable.clear();
  40806. this.onSizeChangedObservable.clear();
  40807. };
  40808. return PostProcess;
  40809. }());
  40810. BABYLON.PostProcess = PostProcess;
  40811. })(BABYLON || (BABYLON = {}));
  40812. //# sourceMappingURL=babylon.postProcess.js.map
  40813. var BABYLON;
  40814. (function (BABYLON) {
  40815. var PassPostProcess = (function (_super) {
  40816. __extends(PassPostProcess, _super);
  40817. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40818. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40819. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  40820. }
  40821. return PassPostProcess;
  40822. }(BABYLON.PostProcess));
  40823. BABYLON.PassPostProcess = PassPostProcess;
  40824. })(BABYLON || (BABYLON = {}));
  40825. //# sourceMappingURL=babylon.passPostProcess.js.map
  40826. var BABYLON;
  40827. (function (BABYLON) {
  40828. var BlurPostProcess = (function (_super) {
  40829. __extends(BlurPostProcess, _super);
  40830. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40832. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40833. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40834. _this.direction = direction;
  40835. _this.onApplyObservable.add(function (effect) {
  40836. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  40837. });
  40838. _this.kernel = kernel;
  40839. return _this;
  40840. }
  40841. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  40842. /**
  40843. * Gets the length in pixels of the blur sample region
  40844. */
  40845. get: function () {
  40846. return this._idealKernel;
  40847. },
  40848. /**
  40849. * Sets the length in pixels of the blur sample region
  40850. */
  40851. set: function (v) {
  40852. v = Math.max(v, 1);
  40853. this._idealKernel = v;
  40854. this._kernel = this._nearestBestKernel(v);
  40855. this._updateParameters();
  40856. },
  40857. enumerable: true,
  40858. configurable: true
  40859. });
  40860. BlurPostProcess.prototype._updateParameters = function () {
  40861. // Generate sampling offsets and weights
  40862. var N = this._kernel;
  40863. var centerIndex = (N - 1) / 2;
  40864. // Generate Gaussian sampling weights over kernel
  40865. var offsets = [];
  40866. var weights = [];
  40867. var totalWeight = 0;
  40868. for (var i = 0; i < N; i++) {
  40869. var u = i / (N - 1);
  40870. var w = this._gaussianWeight(u * 2.0 - 1);
  40871. offsets[i] = (i - centerIndex);
  40872. weights[i] = w;
  40873. totalWeight += w;
  40874. }
  40875. // Normalize weights
  40876. for (var i = 0; i < weights.length; i++) {
  40877. weights[i] /= totalWeight;
  40878. }
  40879. // Optimize: combine samples to take advantage of hardware linear sampling
  40880. // Walk from left to center, combining pairs (symmetrically)
  40881. var linearSamplingWeights = [];
  40882. var linearSamplingOffsets = [];
  40883. var linearSamplingMap = [];
  40884. for (var i = 0; i <= centerIndex; i += 2) {
  40885. var j = Math.min(i + 1, Math.floor(centerIndex));
  40886. var singleCenterSample = i === j;
  40887. if (singleCenterSample) {
  40888. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40889. }
  40890. else {
  40891. var sharedCell = j === centerIndex;
  40892. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  40893. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  40894. if (offsetLinear === 0) {
  40895. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40896. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  40897. }
  40898. else {
  40899. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  40900. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  40901. }
  40902. }
  40903. }
  40904. for (var i = 0; i < linearSamplingMap.length; i++) {
  40905. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  40906. linearSamplingWeights[i] = linearSamplingMap[i].w;
  40907. }
  40908. // Replace with optimized
  40909. offsets = linearSamplingOffsets;
  40910. weights = linearSamplingWeights;
  40911. // Generate shaders
  40912. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  40913. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  40914. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  40915. var defines = "";
  40916. for (var i = 0; i < varyingCount; i++) {
  40917. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  40918. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  40919. }
  40920. var depCount = 0;
  40921. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  40922. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  40923. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  40924. depCount++;
  40925. }
  40926. this._indexParameters.varyingCount = varyingCount;
  40927. this._indexParameters.depCount = depCount;
  40928. this.updateEffect(defines);
  40929. };
  40930. /**
  40931. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  40932. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  40933. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  40934. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  40935. * The gaps between physical kernels are compensated for in the weighting of the samples
  40936. * @param idealKernel Ideal blur kernel.
  40937. * @return Nearest best kernel.
  40938. */
  40939. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  40940. var v = Math.round(idealKernel);
  40941. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  40942. var k = _a[_i];
  40943. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  40944. return Math.max(k, 3);
  40945. }
  40946. }
  40947. return Math.max(v, 3);
  40948. };
  40949. /**
  40950. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  40951. * @param x The point on the Gaussian distribution to sample.
  40952. * @return the value of the Gaussian function at x.
  40953. */
  40954. BlurPostProcess.prototype._gaussianWeight = function (x) {
  40955. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  40956. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  40957. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  40958. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  40959. // truncated at around 1.3% of peak strength.
  40960. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  40961. var sigma = (1 / 3);
  40962. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  40963. var exponent = -((x * x) / (2.0 * sigma * sigma));
  40964. var weight = (1.0 / denominator) * Math.exp(exponent);
  40965. return weight;
  40966. };
  40967. /**
  40968. * Generates a string that can be used as a floating point number in GLSL.
  40969. * @param x Value to print.
  40970. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  40971. * @return GLSL float string.
  40972. */
  40973. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  40974. if (decimalFigures === void 0) { decimalFigures = 8; }
  40975. return x.toFixed(decimalFigures).replace(/0+$/, '');
  40976. };
  40977. return BlurPostProcess;
  40978. }(BABYLON.PostProcess));
  40979. BABYLON.BlurPostProcess = BlurPostProcess;
  40980. })(BABYLON || (BABYLON = {}));
  40981. //# sourceMappingURL=babylon.blurPostProcess.js.map
  40982. var BABYLON;
  40983. (function (BABYLON) {
  40984. var FxaaPostProcess = (function (_super) {
  40985. __extends(FxaaPostProcess, _super);
  40986. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40987. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40988. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType) || this;
  40989. _this.onApplyObservable.add(function (effect) {
  40990. var texelSize = _this.texelSize;
  40991. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  40992. });
  40993. return _this;
  40994. }
  40995. return FxaaPostProcess;
  40996. }(BABYLON.PostProcess));
  40997. BABYLON.FxaaPostProcess = FxaaPostProcess;
  40998. })(BABYLON || (BABYLON = {}));
  40999. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  41000. var BABYLON;
  41001. (function (BABYLON) {
  41002. var HighlightsPostProcess = (function (_super) {
  41003. __extends(HighlightsPostProcess, _super);
  41004. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41005. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41006. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41007. }
  41008. return HighlightsPostProcess;
  41009. }(BABYLON.PostProcess));
  41010. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  41011. })(BABYLON || (BABYLON = {}));
  41012. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  41013. var BABYLON;
  41014. (function (BABYLON) {
  41015. var ImageProcessingPostProcess = (function (_super) {
  41016. __extends(ImageProcessingPostProcess, _super);
  41017. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41018. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41019. var _this = _super.call(this, name, "imageProcessing", [
  41020. 'contrast',
  41021. 'vignetteSettings1',
  41022. 'vignetteSettings2',
  41023. 'cameraExposureLinear',
  41024. 'vCameraColorCurveNegative',
  41025. 'vCameraColorCurveNeutral',
  41026. 'vCameraColorCurvePositive',
  41027. 'colorTransformSettings'
  41028. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  41029. _this.colorGradingWeight = 1.0;
  41030. _this.colorCurves = new BABYLON.ColorCurves();
  41031. _this.vignetteStretch = 0;
  41032. _this.vignetteCentreX = 0;
  41033. _this.vignetteCentreY = 0;
  41034. _this.vignetteWeight = 1.5;
  41035. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41036. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  41037. _this.cameraContrast = 1.0;
  41038. _this.cameraExposureValue = 1.5;
  41039. _this._cameraToneMappingEnabled = true;
  41040. _this._updateParameters();
  41041. _this.onApply = function (effect) {
  41042. var aspectRatio = _this.aspectRatio;
  41043. // Color
  41044. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  41045. // Vignette
  41046. var vignetteScaleY = Math.tan(_this.getCamera().fov * 0.5);
  41047. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41048. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41049. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  41050. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  41051. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  41052. var vignettePower = -2.0 * _this.vignetteWeight;
  41053. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  41054. // Contrast and exposure
  41055. effect.setFloat('contrast', _this.cameraContrast);
  41056. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposureValue) * Math.PI);
  41057. // Color transform settings
  41058. if (_this._colorGradingTexture) {
  41059. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  41060. var textureSize = _this.colorGradingTexture.getSize().height;
  41061. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41062. 0.5 / textureSize, // textureOffset
  41063. textureSize, // textureSize
  41064. _this.colorGradingWeight // weight
  41065. );
  41066. }
  41067. };
  41068. return _this;
  41069. }
  41070. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41071. get: function () {
  41072. return this._colorGradingTexture;
  41073. },
  41074. set: function (value) {
  41075. if (this._colorGradingTexture === value) {
  41076. return;
  41077. }
  41078. this._colorGradingTexture = value;
  41079. this._updateParameters();
  41080. },
  41081. enumerable: true,
  41082. configurable: true
  41083. });
  41084. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41085. get: function () {
  41086. return this._vignetteBlendMode;
  41087. },
  41088. set: function (value) {
  41089. if (this._vignetteBlendMode === value) {
  41090. return;
  41091. }
  41092. this._vignetteBlendMode = value;
  41093. this._updateParameters();
  41094. },
  41095. enumerable: true,
  41096. configurable: true
  41097. });
  41098. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  41099. get: function () {
  41100. return this._cameraToneMappingEnabled;
  41101. },
  41102. set: function (value) {
  41103. if (this._cameraToneMappingEnabled === value) {
  41104. return;
  41105. }
  41106. this._cameraToneMappingEnabled = value;
  41107. this._updateParameters();
  41108. },
  41109. enumerable: true,
  41110. configurable: true
  41111. });
  41112. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41113. var defines = "";
  41114. if (this.colorGradingTexture) {
  41115. defines = "#define COLORGRADING\r\n";
  41116. }
  41117. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  41118. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  41119. }
  41120. else {
  41121. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  41122. }
  41123. if (this.cameraToneMappingEnabled) {
  41124. defines += "#define TONEMAPPING\r\n";
  41125. }
  41126. this.updateEffect(defines);
  41127. };
  41128. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  41129. get: function () {
  41130. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  41131. },
  41132. enumerable: true,
  41133. configurable: true
  41134. });
  41135. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  41136. get: function () {
  41137. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  41138. },
  41139. enumerable: true,
  41140. configurable: true
  41141. });
  41142. return ImageProcessingPostProcess;
  41143. }(BABYLON.PostProcess));
  41144. // Statics
  41145. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  41146. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  41147. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41148. })(BABYLON || (BABYLON = {}));
  41149. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41150. var BABYLON;
  41151. (function (BABYLON) {
  41152. /**
  41153. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41154. * It can help converting any input color in a desired output one. This can then be used to create effects
  41155. * from sepia, black and white to sixties or futuristic rendering...
  41156. *
  41157. * The only supported format is currently 3dl.
  41158. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41159. */
  41160. var ColorGradingTexture = (function (_super) {
  41161. __extends(ColorGradingTexture, _super);
  41162. /**
  41163. * Instantiates a ColorGradingTexture from the following parameters.
  41164. *
  41165. * @param url The location of the color gradind data (currently only supporting 3dl)
  41166. * @param scene The scene the texture will be used in
  41167. */
  41168. function ColorGradingTexture(url, scene) {
  41169. var _this = _super.call(this, scene) || this;
  41170. if (!url) {
  41171. return _this;
  41172. }
  41173. _this._textureMatrix = BABYLON.Matrix.Identity();
  41174. _this.name = url;
  41175. _this.url = url;
  41176. _this.hasAlpha = false;
  41177. _this.isCube = false;
  41178. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41179. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41180. _this.anisotropicFilteringLevel = 1;
  41181. _this._texture = _this._getFromCache(url, true);
  41182. if (!_this._texture) {
  41183. if (!scene.useDelayedTextureLoading) {
  41184. _this.loadTexture();
  41185. }
  41186. else {
  41187. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41188. }
  41189. }
  41190. return _this;
  41191. }
  41192. /**
  41193. * Returns the texture matrix used in most of the material.
  41194. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41195. */
  41196. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41197. return this._textureMatrix;
  41198. };
  41199. /**
  41200. * Occurs when the file being loaded is a .3dl LUT file.
  41201. */
  41202. ColorGradingTexture.prototype.load3dlTexture = function () {
  41203. var _this = this;
  41204. var mipLevels = 0;
  41205. var floatArrayView = null;
  41206. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41207. this._texture = texture;
  41208. var callback = function (text) {
  41209. var data;
  41210. var tempData;
  41211. var line;
  41212. var lines = text.split('\n');
  41213. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41214. var maxColor = 0;
  41215. for (var i = 0; i < lines.length; i++) {
  41216. line = lines[i];
  41217. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41218. continue;
  41219. if (line.indexOf('#') === 0)
  41220. continue;
  41221. var words = line.split(" ");
  41222. if (size === 0) {
  41223. // Number of space + one
  41224. size = words.length;
  41225. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41226. tempData = new Float32Array(size * size * size * 4);
  41227. continue;
  41228. }
  41229. if (size != 0) {
  41230. var r = Math.max(parseInt(words[0]), 0);
  41231. var g = Math.max(parseInt(words[1]), 0);
  41232. var b = Math.max(parseInt(words[2]), 0);
  41233. maxColor = Math.max(r, maxColor);
  41234. maxColor = Math.max(g, maxColor);
  41235. maxColor = Math.max(b, maxColor);
  41236. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41237. tempData[pixelStorageIndex + 0] = r;
  41238. tempData[pixelStorageIndex + 1] = g;
  41239. tempData[pixelStorageIndex + 2] = b;
  41240. tempData[pixelStorageIndex + 3] = 0;
  41241. pixelIndexSlice++;
  41242. if (pixelIndexSlice % size == 0) {
  41243. pixelIndexH++;
  41244. pixelIndexSlice = 0;
  41245. if (pixelIndexH % size == 0) {
  41246. pixelIndexW++;
  41247. pixelIndexH = 0;
  41248. }
  41249. }
  41250. }
  41251. }
  41252. for (var i = 0; i < tempData.length; i++) {
  41253. var value = tempData[i];
  41254. data[i] = (value / maxColor * 255);
  41255. }
  41256. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  41257. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41258. };
  41259. BABYLON.Tools.LoadFile(this.url, callback);
  41260. return this._texture;
  41261. };
  41262. /**
  41263. * Starts the loading process of the texture.
  41264. */
  41265. ColorGradingTexture.prototype.loadTexture = function () {
  41266. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41267. this.load3dlTexture();
  41268. }
  41269. };
  41270. /**
  41271. * Clones the color gradind texture.
  41272. */
  41273. ColorGradingTexture.prototype.clone = function () {
  41274. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41275. // Base texture
  41276. newTexture.level = this.level;
  41277. return newTexture;
  41278. };
  41279. /**
  41280. * Called during delayed load for textures.
  41281. */
  41282. ColorGradingTexture.prototype.delayLoad = function () {
  41283. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41284. return;
  41285. }
  41286. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41287. this._texture = this._getFromCache(this.url, true);
  41288. if (!this._texture) {
  41289. this.loadTexture();
  41290. }
  41291. };
  41292. /**
  41293. * Binds the color grading to the shader.
  41294. * @param colorGrading The texture to bind
  41295. * @param effect The effect to bind to
  41296. */
  41297. ColorGradingTexture.Bind = function (colorGrading, effect) {
  41298. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  41299. var x = colorGrading.level; // Texture Level
  41300. var y = colorGrading.getSize().height; // Texture Size example with 8
  41301. var z = y - 1.0; // SizeMinusOne 8 - 1
  41302. var w = 1 / y; // Space of 1 slice 1 / 8
  41303. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  41304. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  41305. 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
  41306. 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
  41307. 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
  41308. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  41309. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  41310. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  41311. };
  41312. /**
  41313. * Prepare the list of uniforms associated with the ColorGrading effects.
  41314. * @param uniformsList The list of uniforms used in the effect
  41315. * @param samplersList The list of samplers used in the effect
  41316. */
  41317. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  41318. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  41319. samplersList.push("cameraColorGrading2DSampler");
  41320. };
  41321. /**
  41322. * Parses a color grading texture serialized by Babylon.
  41323. * @param parsedTexture The texture information being parsedTexture
  41324. * @param scene The scene to load the texture in
  41325. * @param rootUrl The root url of the data assets to load
  41326. * @return A color gradind texture
  41327. */
  41328. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41329. var texture = null;
  41330. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41331. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41332. texture.name = parsedTexture.name;
  41333. texture.level = parsedTexture.level;
  41334. }
  41335. return texture;
  41336. };
  41337. /**
  41338. * Serializes the LUT texture to json format.
  41339. */
  41340. ColorGradingTexture.prototype.serialize = function () {
  41341. if (!this.name) {
  41342. return null;
  41343. }
  41344. var serializationObject = {};
  41345. serializationObject.name = this.name;
  41346. serializationObject.level = this.level;
  41347. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41348. return serializationObject;
  41349. };
  41350. return ColorGradingTexture;
  41351. }(BABYLON.BaseTexture));
  41352. /**
  41353. * Empty line regex stored for GC.
  41354. */
  41355. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41356. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41357. })(BABYLON || (BABYLON = {}));
  41358. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41359. var BABYLON;
  41360. (function (BABYLON) {
  41361. /**
  41362. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41363. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41364. * 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;
  41365. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41366. */
  41367. var ColorCurves = (function () {
  41368. function ColorCurves() {
  41369. this._dirty = true;
  41370. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41371. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41372. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41373. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41374. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41375. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41376. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41377. this._globalHue = 30;
  41378. this._globalDensity = 0;
  41379. this._globalSaturation = 0;
  41380. this._globalExposure = 0;
  41381. this._highlightsHue = 30;
  41382. this._highlightsDensity = 0;
  41383. this._highlightsSaturation = 0;
  41384. this._highlightsExposure = 0;
  41385. this._midtonesHue = 30;
  41386. this._midtonesDensity = 0;
  41387. this._midtonesSaturation = 0;
  41388. this._midtonesExposure = 0;
  41389. this._shadowsHue = 30;
  41390. this._shadowsDensity = 0;
  41391. this._shadowsSaturation = 0;
  41392. this._shadowsExposure = 0;
  41393. }
  41394. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41395. /**
  41396. * Gets the global Hue value.
  41397. * 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).
  41398. */
  41399. get: function () {
  41400. return this._globalHue;
  41401. },
  41402. /**
  41403. * Sets the global Hue value.
  41404. * 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).
  41405. */
  41406. set: function (value) {
  41407. this._globalHue = value;
  41408. this._dirty = true;
  41409. },
  41410. enumerable: true,
  41411. configurable: true
  41412. });
  41413. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41414. /**
  41415. * Gets the global Density value.
  41416. * 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.
  41417. * Values less than zero provide a filter of opposite hue.
  41418. */
  41419. get: function () {
  41420. return this._globalDensity;
  41421. },
  41422. /**
  41423. * Sets the global Density value.
  41424. * 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.
  41425. * Values less than zero provide a filter of opposite hue.
  41426. */
  41427. set: function (value) {
  41428. this._globalDensity = value;
  41429. this._dirty = true;
  41430. },
  41431. enumerable: true,
  41432. configurable: true
  41433. });
  41434. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41435. /**
  41436. * Gets the global Saturation value.
  41437. * 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.
  41438. */
  41439. get: function () {
  41440. return this._globalSaturation;
  41441. },
  41442. /**
  41443. * Sets the global Saturation value.
  41444. * 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.
  41445. */
  41446. set: function (value) {
  41447. this._globalSaturation = value;
  41448. this._dirty = true;
  41449. },
  41450. enumerable: true,
  41451. configurable: true
  41452. });
  41453. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41454. /**
  41455. * Gets the highlights Hue value.
  41456. * 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).
  41457. */
  41458. get: function () {
  41459. return this._highlightsHue;
  41460. },
  41461. /**
  41462. * Sets the highlights Hue value.
  41463. * 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).
  41464. */
  41465. set: function (value) {
  41466. this._highlightsHue = value;
  41467. this._dirty = true;
  41468. },
  41469. enumerable: true,
  41470. configurable: true
  41471. });
  41472. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41473. /**
  41474. * Gets the highlights Density value.
  41475. * 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.
  41476. * Values less than zero provide a filter of opposite hue.
  41477. */
  41478. get: function () {
  41479. return this._highlightsDensity;
  41480. },
  41481. /**
  41482. * Sets the highlights Density value.
  41483. * 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.
  41484. * Values less than zero provide a filter of opposite hue.
  41485. */
  41486. set: function (value) {
  41487. this._highlightsDensity = value;
  41488. this._dirty = true;
  41489. },
  41490. enumerable: true,
  41491. configurable: true
  41492. });
  41493. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41494. /**
  41495. * Gets the highlights Saturation value.
  41496. * 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.
  41497. */
  41498. get: function () {
  41499. return this._highlightsSaturation;
  41500. },
  41501. /**
  41502. * Sets the highlights Saturation value.
  41503. * 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.
  41504. */
  41505. set: function (value) {
  41506. this._highlightsSaturation = value;
  41507. this._dirty = true;
  41508. },
  41509. enumerable: true,
  41510. configurable: true
  41511. });
  41512. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41513. /**
  41514. * Gets the highlights Exposure value.
  41515. * 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.
  41516. */
  41517. get: function () {
  41518. return this._highlightsExposure;
  41519. },
  41520. /**
  41521. * Sets the highlights Exposure value.
  41522. * 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.
  41523. */
  41524. set: function (value) {
  41525. this._highlightsExposure = value;
  41526. this._dirty = true;
  41527. },
  41528. enumerable: true,
  41529. configurable: true
  41530. });
  41531. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41532. /**
  41533. * Gets the midtones Hue value.
  41534. * 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).
  41535. */
  41536. get: function () {
  41537. return this._midtonesHue;
  41538. },
  41539. /**
  41540. * Sets the midtones Hue value.
  41541. * 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).
  41542. */
  41543. set: function (value) {
  41544. this._midtonesHue = value;
  41545. this._dirty = true;
  41546. },
  41547. enumerable: true,
  41548. configurable: true
  41549. });
  41550. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41551. /**
  41552. * Gets the midtones Density value.
  41553. * 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.
  41554. * Values less than zero provide a filter of opposite hue.
  41555. */
  41556. get: function () {
  41557. return this._midtonesDensity;
  41558. },
  41559. /**
  41560. * Sets the midtones Density value.
  41561. * 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.
  41562. * Values less than zero provide a filter of opposite hue.
  41563. */
  41564. set: function (value) {
  41565. this._midtonesDensity = value;
  41566. this._dirty = true;
  41567. },
  41568. enumerable: true,
  41569. configurable: true
  41570. });
  41571. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41572. /**
  41573. * Gets the midtones Saturation value.
  41574. * 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.
  41575. */
  41576. get: function () {
  41577. return this._midtonesSaturation;
  41578. },
  41579. /**
  41580. * Sets the midtones Saturation value.
  41581. * 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.
  41582. */
  41583. set: function (value) {
  41584. this._midtonesSaturation = value;
  41585. this._dirty = true;
  41586. },
  41587. enumerable: true,
  41588. configurable: true
  41589. });
  41590. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41591. /**
  41592. * Gets the midtones Exposure value.
  41593. * 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.
  41594. */
  41595. get: function () {
  41596. return this._midtonesExposure;
  41597. },
  41598. /**
  41599. * Sets the midtones Exposure value.
  41600. * 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.
  41601. */
  41602. set: function (value) {
  41603. this._midtonesExposure = value;
  41604. this._dirty = true;
  41605. },
  41606. enumerable: true,
  41607. configurable: true
  41608. });
  41609. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41610. /**
  41611. * Gets the shadows Hue value.
  41612. * 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).
  41613. */
  41614. get: function () {
  41615. return this._shadowsHue;
  41616. },
  41617. /**
  41618. * Sets the shadows Hue value.
  41619. * 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).
  41620. */
  41621. set: function (value) {
  41622. this._shadowsHue = value;
  41623. this._dirty = true;
  41624. },
  41625. enumerable: true,
  41626. configurable: true
  41627. });
  41628. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41629. /**
  41630. * Gets the shadows Density value.
  41631. * 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.
  41632. * Values less than zero provide a filter of opposite hue.
  41633. */
  41634. get: function () {
  41635. return this._shadowsDensity;
  41636. },
  41637. /**
  41638. * Sets the shadows Density value.
  41639. * 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.
  41640. * Values less than zero provide a filter of opposite hue.
  41641. */
  41642. set: function (value) {
  41643. this._shadowsDensity = value;
  41644. this._dirty = true;
  41645. },
  41646. enumerable: true,
  41647. configurable: true
  41648. });
  41649. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41650. /**
  41651. * Gets the shadows Saturation value.
  41652. * 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.
  41653. */
  41654. get: function () {
  41655. return this._shadowsSaturation;
  41656. },
  41657. /**
  41658. * Sets the shadows Saturation value.
  41659. * 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.
  41660. */
  41661. set: function (value) {
  41662. this._shadowsSaturation = value;
  41663. this._dirty = true;
  41664. },
  41665. enumerable: true,
  41666. configurable: true
  41667. });
  41668. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41669. /**
  41670. * Gets the shadows Exposure value.
  41671. * 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.
  41672. */
  41673. get: function () {
  41674. return this._shadowsExposure;
  41675. },
  41676. /**
  41677. * Sets the shadows Exposure value.
  41678. * 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.
  41679. */
  41680. set: function (value) {
  41681. this._shadowsExposure = value;
  41682. this._dirty = true;
  41683. },
  41684. enumerable: true,
  41685. configurable: true
  41686. });
  41687. /**
  41688. * Binds the color curves to the shader.
  41689. * @param colorCurves The color curve to bind
  41690. * @param effect The effect to bind to
  41691. */
  41692. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41693. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41694. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41695. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41696. if (colorCurves._dirty) {
  41697. colorCurves._dirty = false;
  41698. // Fill in global info.
  41699. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41700. // Compute highlights info.
  41701. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41702. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41703. // Compute midtones info.
  41704. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41705. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41706. // Compute shadows info.
  41707. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41708. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41709. // Compute deltas (neutral is midtones).
  41710. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41711. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41712. }
  41713. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41714. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41715. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41716. };
  41717. /**
  41718. * Prepare the list of uniforms associated with the ColorCurves effects.
  41719. * @param uniformsList The list of uniforms used in the effect
  41720. */
  41721. ColorCurves.PrepareUniforms = function (uniformsList) {
  41722. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41723. };
  41724. /**
  41725. * Returns color grading data based on a hue, density, saturation and exposure value.
  41726. * @param filterHue The hue of the color filter.
  41727. * @param filterDensity The density of the color filter.
  41728. * @param saturation The saturation.
  41729. * @param exposure The exposure.
  41730. * @param result The result data container.
  41731. */
  41732. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41733. if (hue == null) {
  41734. return;
  41735. }
  41736. hue = ColorCurves.clamp(hue, 0, 360);
  41737. density = ColorCurves.clamp(density, -100, 100);
  41738. saturation = ColorCurves.clamp(saturation, -100, 100);
  41739. exposure = ColorCurves.clamp(exposure, -100, 100);
  41740. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41741. // so that the maximum filter density is only 50% control. This provides fine control
  41742. // for small values and reasonable range.
  41743. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41744. density *= 0.5;
  41745. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41746. if (density < 0) {
  41747. density *= -1;
  41748. hue = (hue + 180) % 360;
  41749. }
  41750. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41751. result.scaleToRef(2, result);
  41752. result.a = 1 + 0.01 * saturation;
  41753. };
  41754. /**
  41755. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41756. * @param value The input slider value in range [-100,100].
  41757. * @returns Adjusted value.
  41758. */
  41759. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41760. value /= 100;
  41761. var x = Math.abs(value);
  41762. x = Math.pow(x, 2);
  41763. if (value < 0) {
  41764. x *= -1;
  41765. }
  41766. x *= 100;
  41767. return x;
  41768. };
  41769. /**
  41770. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41771. * @param hue The hue (H) input.
  41772. * @param saturation The saturation (S) input.
  41773. * @param brightness The brightness (B) input.
  41774. * @result An RGBA color represented as Vector4.
  41775. */
  41776. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41777. var h = ColorCurves.clamp(hue, 0, 360);
  41778. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41779. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41780. if (s === 0) {
  41781. result.r = v;
  41782. result.g = v;
  41783. result.b = v;
  41784. }
  41785. else {
  41786. // sector 0 to 5
  41787. h /= 60;
  41788. var i = Math.floor(h);
  41789. // fractional part of h
  41790. var f = h - i;
  41791. var p = v * (1 - s);
  41792. var q = v * (1 - s * f);
  41793. var t = v * (1 - s * (1 - f));
  41794. switch (i) {
  41795. case 0:
  41796. result.r = v;
  41797. result.g = t;
  41798. result.b = p;
  41799. break;
  41800. case 1:
  41801. result.r = q;
  41802. result.g = v;
  41803. result.b = p;
  41804. break;
  41805. case 2:
  41806. result.r = p;
  41807. result.g = v;
  41808. result.b = t;
  41809. break;
  41810. case 3:
  41811. result.r = p;
  41812. result.g = q;
  41813. result.b = v;
  41814. break;
  41815. case 4:
  41816. result.r = t;
  41817. result.g = p;
  41818. result.b = v;
  41819. break;
  41820. default:
  41821. result.r = v;
  41822. result.g = p;
  41823. result.b = q;
  41824. break;
  41825. }
  41826. }
  41827. result.a = 1;
  41828. };
  41829. /**
  41830. * Returns a value clamped between min and max
  41831. * @param value The value to clamp
  41832. * @param min The minimum of value
  41833. * @param max The maximum of value
  41834. * @returns The clamped value.
  41835. */
  41836. ColorCurves.clamp = function (value, min, max) {
  41837. return Math.min(Math.max(value, min), max);
  41838. };
  41839. /**
  41840. * Clones the current color curve instance.
  41841. * @return The cloned curves
  41842. */
  41843. ColorCurves.prototype.clone = function () {
  41844. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41845. };
  41846. /**
  41847. * Serializes the current color curve instance to a json representation.
  41848. * @return a JSON representation
  41849. */
  41850. ColorCurves.prototype.serialize = function () {
  41851. return BABYLON.SerializationHelper.Serialize(this);
  41852. };
  41853. /**
  41854. * Parses the color curve from a json representation.
  41855. * @param source the JSON source to parse
  41856. * @return The parsed curves
  41857. */
  41858. ColorCurves.Parse = function (source) {
  41859. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41860. };
  41861. return ColorCurves;
  41862. }());
  41863. __decorate([
  41864. BABYLON.serialize()
  41865. ], ColorCurves.prototype, "_globalHue", void 0);
  41866. __decorate([
  41867. BABYLON.serialize()
  41868. ], ColorCurves.prototype, "_globalDensity", void 0);
  41869. __decorate([
  41870. BABYLON.serialize()
  41871. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41872. __decorate([
  41873. BABYLON.serialize()
  41874. ], ColorCurves.prototype, "_globalExposure", void 0);
  41875. __decorate([
  41876. BABYLON.serialize()
  41877. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41878. __decorate([
  41879. BABYLON.serialize()
  41880. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41881. __decorate([
  41882. BABYLON.serialize()
  41883. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41884. __decorate([
  41885. BABYLON.serialize()
  41886. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41887. __decorate([
  41888. BABYLON.serialize()
  41889. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41890. __decorate([
  41891. BABYLON.serialize()
  41892. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41893. __decorate([
  41894. BABYLON.serialize()
  41895. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41896. __decorate([
  41897. BABYLON.serialize()
  41898. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41899. BABYLON.ColorCurves = ColorCurves;
  41900. })(BABYLON || (BABYLON = {}));
  41901. //# sourceMappingURL=babylon.colorCurves.js.map
  41902. BABYLON.Effect.ShadersStore={"colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","defaultVertexShader":"#include<__decl__defaultVertex>\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>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\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#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\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) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#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;\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<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\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#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\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>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\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#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\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) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,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 MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*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}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\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;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n\n#ifdef REFLECTION\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#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=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#ifdef ALPHAFROMALBEDO\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#if defined(ALPHATEST) && defined(ALPHATESTVALUE)\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\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#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\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\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.; \n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 lightDiffuseContribution=diffuseBase;\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=specularBase*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\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=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=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 EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=lightDiffuseContribution;\n#ifndef EMISSIVEASILLUMINATION\nfinalDiffuse+=surfaceEmissiveColor;\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nfinalSpecular*=vLightingIntensity.x;\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\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\n#ifdef LDROUTPUT\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#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nvoid main(void)\n{\nvec4 blend=vec4(0.);\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\ngl_FragColor=blend;\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}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst float GammaEncodePowerApprox=1.0/2.2;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nuniform float contrast;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\nuniform float cameraExposureLinear;\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color)\n{\nfloat sliceSize=2.0*colorTransformSettings.y; \nfloat sliceContinuous=(color.y-colorTransformSettings.y)*colorTransformSettings.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\nvec2 sliceUV=color.xz;\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=result.bgr;\nreturn color;\n}\nvec4 applyImageProcessing(vec4 result,vec2 viewportXY){\nresult.rgb*=cameraExposureLinear;\n\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#ifdef TONEMAPPING \nfloat tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\nresult.rgb=pow(result.rgb,vec3(GammaEncodePowerApprox));\nresult.rgb=clamp(result.rgb,0.0,1.0);\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n\nfloat luma=dot(result.rgb,RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\nreturn result;\n}\nvoid main(void) \n{\nvec4 result=texture2D(textureSampler,vUV);\nvec2 viewportXY=vUV*2.0-1.0;\nresult=applyImageProcessing(result,viewportXY);\ngl_FragColor=result;\n}"};
  41903. 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","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\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","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\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}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D 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#ifdef NDOTL\nfloat ndl;\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));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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\n#ifdef NDOTL\nresult.ndl=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;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\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_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\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{\nreturn darkness;\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\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \nreturn esm;\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{\nreturn darkness;\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\nreturn min(1.0,visibility+darkness);\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\nreturn esm;\n}\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","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}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","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}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","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}","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\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#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\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","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\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","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,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","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif 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","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\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\n#else\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","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","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","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}","kernelBlurFragment":"blend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n","kernelBlurFragment2":"blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  41904. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  41905. module.exports = BABYLON;
  41906. };