babylon.engine.ts 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string, shaderVersion: string): WebGLShader => {
  3. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  5. gl.compileShader(shader);
  6. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7. throw new Error(gl.getShaderInfoLog(shader));
  8. }
  9. return shader;
  10. };
  11. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  12. var magFilter = gl.NEAREST;
  13. var minFilter = gl.NEAREST;
  14. switch (samplingMode) {
  15. case Texture.BILINEAR_SAMPLINGMODE:
  16. magFilter = gl.LINEAR;
  17. if (generateMipMaps) {
  18. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  19. } else {
  20. minFilter = gl.LINEAR;
  21. }
  22. break;
  23. case Texture.TRILINEAR_SAMPLINGMODE:
  24. magFilter = gl.LINEAR;
  25. if (generateMipMaps) {
  26. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  27. } else {
  28. minFilter = gl.LINEAR;
  29. }
  30. break;
  31. case Texture.NEAREST_SAMPLINGMODE:
  32. magFilter = gl.NEAREST;
  33. if (generateMipMaps) {
  34. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  35. } else {
  36. minFilter = gl.NEAREST;
  37. }
  38. break;
  39. case Texture.NEAREST_NEAREST_MIPNEAREST:
  40. magFilter = gl.NEAREST;
  41. if (generateMipMaps) {
  42. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  43. } else {
  44. minFilter = gl.NEAREST;
  45. }
  46. break;
  47. case Texture.NEAREST_LINEAR_MIPNEAREST:
  48. magFilter = gl.NEAREST;
  49. if (generateMipMaps) {
  50. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  51. } else {
  52. minFilter = gl.LINEAR;
  53. }
  54. break;
  55. case Texture.NEAREST_LINEAR_MIPLINEAR:
  56. magFilter = gl.NEAREST;
  57. if (generateMipMaps) {
  58. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  59. } else {
  60. minFilter = gl.LINEAR;
  61. }
  62. break;
  63. case Texture.NEAREST_LINEAR:
  64. magFilter = gl.NEAREST;
  65. minFilter = gl.LINEAR;
  66. break;
  67. case Texture.NEAREST_NEAREST:
  68. magFilter = gl.NEAREST;
  69. minFilter = gl.NEAREST;
  70. break;
  71. case Texture.LINEAR_NEAREST_MIPNEAREST:
  72. magFilter = gl.LINEAR;
  73. if (generateMipMaps) {
  74. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  75. } else {
  76. minFilter = gl.NEAREST;
  77. }
  78. break;
  79. case Texture.LINEAR_NEAREST_MIPLINEAR:
  80. magFilter = gl.LINEAR;
  81. if (generateMipMaps) {
  82. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  83. } else {
  84. minFilter = gl.NEAREST;
  85. }
  86. break;
  87. case Texture.LINEAR_LINEAR:
  88. magFilter = gl.LINEAR;
  89. minFilter = gl.LINEAR;
  90. break;
  91. case Texture.LINEAR_NEAREST:
  92. magFilter = gl.LINEAR;
  93. minFilter = gl.NEAREST;
  94. break;
  95. }
  96. return {
  97. min: minFilter,
  98. mag: magFilter
  99. }
  100. }
  101. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  102. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: () => void = null) => {
  103. var img: HTMLImageElement;
  104. var onload = () => {
  105. loadedImages[index] = img;
  106. loadedImages._internalCount++;
  107. if (scene) {
  108. scene._removePendingData(img);
  109. }
  110. if (loadedImages._internalCount === 6) {
  111. onfinish(loadedImages);
  112. }
  113. };
  114. var onerror = () => {
  115. if (scene) {
  116. scene._removePendingData(img);
  117. }
  118. if (onErrorCallBack) {
  119. onErrorCallBack();
  120. }
  121. };
  122. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  123. if (scene) {
  124. scene._addPendingData(img);
  125. }
  126. }
  127. var cascadeLoad = (rootUrl: string, scene,
  128. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: () => void = null) => {
  129. var loadedImages: any = [];
  130. loadedImages._internalCount = 0;
  131. for (var index = 0; index < 6; index++) {
  132. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  133. }
  134. };
  135. class BufferPointer {
  136. public active: boolean;
  137. public index: number;
  138. public size: number;
  139. public type: number;
  140. public normalized: boolean;
  141. public stride: number;
  142. public offset: number;
  143. public buffer: WebGLBuffer;
  144. }
  145. export class InstancingAttributeInfo {
  146. /**
  147. * Index/offset of the attribute in the vertex shader
  148. */
  149. index: number;
  150. /**
  151. * size of the attribute, 1, 2, 3 or 4
  152. */
  153. attributeSize: number;
  154. /**
  155. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  156. * default is FLOAT
  157. */
  158. attribyteType: number;
  159. /**
  160. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  161. */
  162. normalized: boolean;
  163. /**
  164. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  165. */
  166. offset: number;
  167. /**
  168. * Name of the GLSL attribute, for debugging purpose only
  169. */
  170. attributeName: string;
  171. }
  172. /**
  173. * Define options used to create a render target texture
  174. */
  175. export class RenderTargetCreationOptions {
  176. generateMipMaps?: boolean;
  177. generateDepthBuffer?: boolean;
  178. generateStencilBuffer?: boolean;
  179. type?: number;
  180. samplingMode?: number;
  181. }
  182. /**
  183. * Regroup several parameters relative to the browser in use
  184. */
  185. export class EngineCapabilities {
  186. /** The maximum textures image */
  187. public maxTexturesImageUnits: number;
  188. public maxVertexTextureImageUnits: number;
  189. /** The maximum texture size */
  190. public maxTextureSize: number;
  191. public maxCubemapTextureSize: number;
  192. public maxRenderTextureSize: number;
  193. public maxVertexAttribs: number;
  194. public maxVaryingVectors: number;
  195. public maxVertexUniformVectors: number;
  196. public maxFragmentUniformVectors: number;
  197. public standardDerivatives: boolean;
  198. public s3tc: WEBGL_compressed_texture_s3tc;
  199. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  200. public etc1: any; //WEBGL_compressed_texture_etc1;
  201. public etc2: any; //WEBGL_compressed_texture_etc;
  202. public astc: any; //WEBGL_compressed_texture_astc;
  203. public textureFloat: boolean;
  204. public vertexArrayObject: boolean;
  205. public textureAnisotropicFilterExtension: EXT_texture_filter_anisotropic;
  206. public maxAnisotropy: number;
  207. public instancedArrays: boolean;
  208. public uintIndices: boolean;
  209. public highPrecisionShaderSupported: boolean;
  210. public fragmentDepthSupported: boolean;
  211. public textureFloatLinearFiltering: boolean;
  212. public textureFloatRender: boolean;
  213. public textureHalfFloat: boolean;
  214. public textureHalfFloatLinearFiltering: boolean;
  215. public textureHalfFloatRender: boolean;
  216. public textureLOD: boolean;
  217. public drawBuffersExtension: boolean;
  218. public depthTextureExtension: boolean;
  219. public colorBufferFloat: boolean;
  220. }
  221. export interface EngineOptions extends WebGLContextAttributes {
  222. limitDeviceRatio?: number;
  223. autoEnableWebVR?: boolean;
  224. disableWebGL2Support?: boolean;
  225. audioEngine?: boolean;
  226. deterministicLockstep?: boolean;
  227. lockstepMaxSteps?: number;
  228. doNotHandleContextLost?: boolean;
  229. }
  230. /**
  231. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  232. */
  233. export class Engine {
  234. public static Instances = new Array<Engine>();
  235. public static get LastCreatedEngine(): Engine {
  236. if (Engine.Instances.length === 0) {
  237. return null;
  238. }
  239. return Engine.Instances[Engine.Instances.length - 1];
  240. }
  241. public static get LastCreatedScene(): Scene {
  242. var lastCreatedEngine = Engine.LastCreatedEngine;
  243. if (!lastCreatedEngine) {
  244. return null;
  245. }
  246. if (lastCreatedEngine.scenes.length === 0) {
  247. return null;
  248. }
  249. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  250. }
  251. /**
  252. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  253. */
  254. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  255. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  256. var engine = Engine.Instances[engineIndex];
  257. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  258. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  259. }
  260. }
  261. }
  262. // Const statics
  263. private static _ALPHA_DISABLE = 0;
  264. private static _ALPHA_ADD = 1;
  265. private static _ALPHA_COMBINE = 2;
  266. private static _ALPHA_SUBTRACT = 3;
  267. private static _ALPHA_MULTIPLY = 4;
  268. private static _ALPHA_MAXIMIZED = 5;
  269. private static _ALPHA_ONEONE = 6;
  270. private static _ALPHA_PREMULTIPLIED = 7;
  271. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  272. private static _ALPHA_INTERPOLATE = 9;
  273. private static _ALPHA_SCREENMODE = 10;
  274. private static _DELAYLOADSTATE_NONE = 0;
  275. private static _DELAYLOADSTATE_LOADED = 1;
  276. private static _DELAYLOADSTATE_LOADING = 2;
  277. private static _DELAYLOADSTATE_NOTLOADED = 4;
  278. private static _TEXTUREFORMAT_ALPHA = 0;
  279. private static _TEXTUREFORMAT_LUMINANCE = 1;
  280. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  281. private static _TEXTUREFORMAT_RGB = 4;
  282. private static _TEXTUREFORMAT_RGBA = 5;
  283. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  284. private static _TEXTURETYPE_FLOAT = 1;
  285. private static _TEXTURETYPE_HALF_FLOAT = 2;
  286. // Depht or Stencil test Constants.
  287. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  288. private static _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.
  289. private static _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.
  290. private static _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.
  291. private static _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.
  292. private static _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.
  293. private static _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.
  294. private static _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.
  295. public static get NEVER(): number {
  296. return Engine._NEVER;
  297. }
  298. public static get ALWAYS(): number {
  299. return Engine._ALWAYS;
  300. }
  301. public static get LESS(): number {
  302. return Engine._LESS;
  303. }
  304. public static get EQUAL(): number {
  305. return Engine._EQUAL;
  306. }
  307. public static get LEQUAL(): number {
  308. return Engine._LEQUAL;
  309. }
  310. public static get GREATER(): number {
  311. return Engine._GREATER;
  312. }
  313. public static get GEQUAL(): number {
  314. return Engine._GEQUAL;
  315. }
  316. public static get NOTEQUAL(): number {
  317. return Engine._NOTEQUAL;
  318. }
  319. // Stencil Actions Constants.
  320. private static _KEEP = 0x1E00;
  321. private static _REPLACE = 0x1E01;
  322. private static _INCR = 0x1E02;
  323. private static _DECR = 0x1E03;
  324. private static _INVERT = 0x150A;
  325. private static _INCR_WRAP = 0x8507;
  326. private static _DECR_WRAP = 0x8508;
  327. public static get KEEP(): number {
  328. return Engine._KEEP;
  329. }
  330. public static get REPLACE(): number {
  331. return Engine._REPLACE;
  332. }
  333. public static get INCR(): number {
  334. return Engine._INCR;
  335. }
  336. public static get DECR(): number {
  337. return Engine._DECR;
  338. }
  339. public static get INVERT(): number {
  340. return Engine._INVERT;
  341. }
  342. public static get INCR_WRAP(): number {
  343. return Engine._INCR_WRAP;
  344. }
  345. public static get DECR_WRAP(): number {
  346. return Engine._DECR_WRAP;
  347. }
  348. public static get ALPHA_DISABLE(): number {
  349. return Engine._ALPHA_DISABLE;
  350. }
  351. public static get ALPHA_ONEONE(): number {
  352. return Engine._ALPHA_ONEONE;
  353. }
  354. public static get ALPHA_ADD(): number {
  355. return Engine._ALPHA_ADD;
  356. }
  357. public static get ALPHA_COMBINE(): number {
  358. return Engine._ALPHA_COMBINE;
  359. }
  360. public static get ALPHA_SUBTRACT(): number {
  361. return Engine._ALPHA_SUBTRACT;
  362. }
  363. public static get ALPHA_MULTIPLY(): number {
  364. return Engine._ALPHA_MULTIPLY;
  365. }
  366. public static get ALPHA_MAXIMIZED(): number {
  367. return Engine._ALPHA_MAXIMIZED;
  368. }
  369. public static get ALPHA_PREMULTIPLIED(): number {
  370. return Engine._ALPHA_PREMULTIPLIED;
  371. }
  372. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  373. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  374. }
  375. public static get ALPHA_INTERPOLATE(): number {
  376. return Engine._ALPHA_INTERPOLATE;
  377. }
  378. public static get ALPHA_SCREENMODE(): number {
  379. return Engine._ALPHA_SCREENMODE;
  380. }
  381. public static get DELAYLOADSTATE_NONE(): number {
  382. return Engine._DELAYLOADSTATE_NONE;
  383. }
  384. public static get DELAYLOADSTATE_LOADED(): number {
  385. return Engine._DELAYLOADSTATE_LOADED;
  386. }
  387. public static get DELAYLOADSTATE_LOADING(): number {
  388. return Engine._DELAYLOADSTATE_LOADING;
  389. }
  390. public static get DELAYLOADSTATE_NOTLOADED(): number {
  391. return Engine._DELAYLOADSTATE_NOTLOADED;
  392. }
  393. public static get TEXTUREFORMAT_ALPHA(): number {
  394. return Engine._TEXTUREFORMAT_ALPHA;
  395. }
  396. public static get TEXTUREFORMAT_LUMINANCE(): number {
  397. return Engine._TEXTUREFORMAT_LUMINANCE;
  398. }
  399. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  400. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  401. }
  402. public static get TEXTUREFORMAT_RGB(): number {
  403. return Engine._TEXTUREFORMAT_RGB;
  404. }
  405. public static get TEXTUREFORMAT_RGBA(): number {
  406. return Engine._TEXTUREFORMAT_RGBA;
  407. }
  408. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  409. return Engine._TEXTURETYPE_UNSIGNED_INT;
  410. }
  411. public static get TEXTURETYPE_FLOAT(): number {
  412. return Engine._TEXTURETYPE_FLOAT;
  413. }
  414. public static get TEXTURETYPE_HALF_FLOAT(): number {
  415. return Engine._TEXTURETYPE_HALF_FLOAT;
  416. }
  417. // Texture rescaling mode
  418. private static _SCALEMODE_FLOOR = 1;
  419. private static _SCALEMODE_NEAREST = 2;
  420. private static _SCALEMODE_CEILING = 3;
  421. public static get SCALEMODE_FLOOR(): number {
  422. return Engine._SCALEMODE_FLOOR;
  423. }
  424. public static get SCALEMODE_NEAREST(): number {
  425. return Engine._SCALEMODE_NEAREST;
  426. }
  427. public static get SCALEMODE_CEILING(): number {
  428. return Engine._SCALEMODE_CEILING;
  429. }
  430. public static get Version(): string {
  431. return "3.1-alpha";
  432. }
  433. // Updatable statics so stick with vars here
  434. public static CollisionsEpsilon = 0.001;
  435. public static CodeRepository = "src/";
  436. public static ShadersRepository = "src/Shaders/";
  437. // Public members
  438. public forcePOTTextures = false;
  439. public isFullscreen = false;
  440. public isPointerLock = false;
  441. public cullBackFaces = true;
  442. public renderEvenInBackground = true;
  443. public preventCacheWipeBetweenFrames = false;
  444. // To enable/disable IDB support and avoid XHR on .manifest
  445. public enableOfflineSupport = false;
  446. public scenes = new Array<Scene>();
  447. public postProcesses = new Array<PostProcess>();
  448. // Observables
  449. /**
  450. * Observable event triggered each time the rendering canvas is resized
  451. */
  452. public onResizeObservable = new Observable<Engine>();
  453. /**
  454. * Observable event triggered each time the canvas loses focus
  455. */
  456. public onCanvasBlurObservable = new Observable<Engine>();
  457. /**
  458. * Observable event triggered each time the canvas gains focus
  459. */
  460. public onCanvasFocusObservable = new Observable<Engine>();
  461. /**
  462. * Observable event triggered each time the canvas receives pointerout event
  463. */
  464. public onCanvasPointerOutObservable = new Observable<Engine>();
  465. //WebVR
  466. //The new WebVR uses promises.
  467. //this promise resolves with the current devices available.
  468. public vrDisplaysPromise;
  469. private _vrDisplays;
  470. private _vrDisplayEnabled;
  471. private _oldSize: BABYLON.Size;
  472. private _oldHardwareScaleFactor: number;
  473. // Uniform buffers list
  474. public disableUniformBuffers = false;
  475. public _uniformBuffers = new Array<UniformBuffer>();
  476. public get supportsUniformBuffers(): boolean {
  477. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  478. }
  479. // Private Members
  480. private _gl: WebGLRenderingContext;
  481. private _renderingCanvas: HTMLCanvasElement;
  482. private _windowIsBackground = false;
  483. private _webGLVersion = 1.0;
  484. public get needPOTTextures(): boolean {
  485. return this._webGLVersion < 2 || this.forcePOTTextures;
  486. }
  487. private _badOS = false;
  488. public get badOS(): boolean {
  489. return this._badOS;
  490. }
  491. private _badDesktopOS = false;
  492. public get badDesktopOS(): boolean {
  493. return this._badDesktopOS;
  494. }
  495. public static audioEngine: AudioEngine;
  496. // Focus
  497. private _onFocus: () => void;
  498. private _onBlur: () => void;
  499. private _onCanvasPointerOut: () => void;
  500. private _onCanvasBlur: () => void;
  501. private _onCanvasFocus: () => void;
  502. private _onFullscreenChange: () => void;
  503. private _onPointerLockChange: () => void;
  504. private _onVRDisplayPointerRestricted: () => void;
  505. private _onVRDisplayPointerUnrestricted: () => void;
  506. private _hardwareScalingLevel: number;
  507. private _caps: EngineCapabilities;
  508. private _pointerLockRequested: boolean;
  509. private _alphaTest: boolean;
  510. private _isStencilEnable: boolean;
  511. private _colorWrite = true;
  512. private _loadingScreen: ILoadingScreen;
  513. public _drawCalls = new PerfCounter();
  514. private _glVersion: string;
  515. private _glRenderer: string;
  516. private _glVendor: string;
  517. private _videoTextureSupported: boolean;
  518. private _renderingQueueLaunched = false;
  519. private _activeRenderLoops = [];
  520. // Deterministic lockstepMaxSteps
  521. private _deterministicLockstep: boolean = false;
  522. private _lockstepMaxSteps: number = 4;
  523. // Lost context
  524. public onContextLostObservable = new Observable<Engine>();
  525. public onContextRestoredObservable = new Observable<Engine>();
  526. private _onContextLost: (evt: Event) => void;
  527. private _onContextRestored: (evt: Event) => void;
  528. private _contextWasLost = false;
  529. private _doNotHandleContextLost = false;
  530. // FPS
  531. private _performanceMonitor = new PerformanceMonitor();
  532. private _fps = 60;
  533. private _deltaTime = 0;
  534. /**
  535. * Turn this value on if you want to pause FPS computation when in background
  536. */
  537. public disablePerformanceMonitorInBackground = false;
  538. public get performanceMonitor(): PerformanceMonitor {
  539. return this._performanceMonitor;
  540. }
  541. // States
  542. private _depthCullingState = new Internals._DepthCullingState();
  543. private _stencilState = new Internals._StencilState();
  544. private _alphaState = new Internals._AlphaState();
  545. private _alphaMode = Engine.ALPHA_DISABLE;
  546. // Cache
  547. private _internalTexturesCache = new Array<InternalTexture>();
  548. private _maxTextureChannels = 16;
  549. private _activeTexture: number;
  550. private _activeTexturesCache: { [key: string]: WebGLTexture } = {};
  551. private _currentEffect: Effect;
  552. private _currentProgram: WebGLProgram;
  553. private _compiledEffects = {};
  554. private _vertexAttribArraysEnabled: boolean[] = [];
  555. private _cachedViewport: Viewport;
  556. private _cachedVertexArrayObject: WebGLVertexArrayObject;
  557. private _cachedVertexBuffers: any;
  558. private _cachedIndexBuffer: WebGLBuffer;
  559. private _cachedEffectForVertexBuffers: Effect;
  560. private _currentRenderTarget: InternalTexture;
  561. private _uintIndicesCurrentlySet = false;
  562. private _currentBoundBuffer = new Array<WebGLBuffer>();
  563. private _currentFramebuffer: WebGLFramebuffer;
  564. private _currentBufferPointers = new Array<BufferPointer>();
  565. private _currentInstanceLocations = new Array<number>();
  566. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  567. private _textureUnits: Int32Array;
  568. private _workingCanvas: HTMLCanvasElement;
  569. private _workingContext: CanvasRenderingContext2D;
  570. private _rescalePostProcess: PassPostProcess;
  571. private _dummyFramebuffer: WebGLFramebuffer;
  572. private _externalData: StringDictionary<Object>;
  573. private _bindedRenderFunction: any;
  574. private _vaoRecordInProgress = false;
  575. private _mustWipeVertexAttributes = false;
  576. private _emptyTexture: InternalTexture;
  577. private _emptyCubeTexture: InternalTexture;
  578. private _frameHandler: number;
  579. // Hardware supported Compressed Textures
  580. private _texturesSupported = new Array<string>();
  581. private _textureFormatInUse: string;
  582. public get texturesSupported(): Array<string> {
  583. return this._texturesSupported;
  584. }
  585. public get textureFormatInUse(): string {
  586. return this._textureFormatInUse;
  587. }
  588. public get currentViewport(): Viewport {
  589. return this._cachedViewport;
  590. }
  591. // Empty texture
  592. public get emptyTexture(): InternalTexture {
  593. if (!this._emptyTexture) {
  594. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  595. }
  596. return this._emptyTexture;
  597. }
  598. public get emptyCubeTexture(): InternalTexture {
  599. if (!this._emptyCubeTexture) {
  600. var faceData = new Uint8Array(4);
  601. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  602. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  603. }
  604. return this._emptyCubeTexture;
  605. }
  606. /**
  607. * @constructor
  608. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  609. * @param {boolean} [antialias] - enable antialias
  610. * @param options - further options to be sent to the getContext function
  611. */
  612. constructor(canvasOrContext: HTMLCanvasElement | WebGLRenderingContext, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
  613. var canvas: HTMLCanvasElement;
  614. Engine.Instances.push(this);
  615. options = options || {};
  616. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  617. canvas = <HTMLCanvasElement>canvasOrContext;
  618. this._renderingCanvas = canvas;
  619. if (antialias != null) {
  620. options.antialias = antialias;
  621. }
  622. if (options.deterministicLockstep === undefined) {
  623. options.deterministicLockstep = false;
  624. }
  625. if (options.lockstepMaxSteps === undefined) {
  626. options.lockstepMaxSteps = 4;
  627. }
  628. if (options.preserveDrawingBuffer === undefined) {
  629. options.preserveDrawingBuffer = false;
  630. }
  631. if (options.audioEngine === undefined) {
  632. options.audioEngine = true;
  633. }
  634. if (options.stencil === undefined) {
  635. options.stencil = true;
  636. }
  637. this._deterministicLockstep = options.deterministicLockstep;
  638. this._lockstepMaxSteps = options.lockstepMaxSteps;
  639. this._doNotHandleContextLost = options.doNotHandleContextLost;
  640. // GL
  641. if (!options.disableWebGL2Support) {
  642. try {
  643. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  644. if (this._gl) {
  645. this._webGLVersion = 2.0;
  646. }
  647. } catch (e) {
  648. // Do nothing
  649. }
  650. }
  651. if (!this._gl) {
  652. if (!canvas) {
  653. throw new Error("The provided canvas is null or undefined.");
  654. }
  655. try {
  656. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  657. } catch (e) {
  658. throw new Error("WebGL not supported");
  659. }
  660. }
  661. if (!this._gl) {
  662. throw new Error("WebGL not supported");
  663. }
  664. this._onCanvasFocus = () => {
  665. this.onCanvasFocusObservable.notifyObservers(this);
  666. }
  667. this._onCanvasBlur = () => {
  668. this.onCanvasBlurObservable.notifyObservers(this);
  669. }
  670. canvas.addEventListener("focus", this._onCanvasFocus);
  671. canvas.addEventListener("blur", this._onCanvasBlur);
  672. this._onBlur = () => {
  673. if (this.disablePerformanceMonitorInBackground) {
  674. this._performanceMonitor.disable();
  675. }
  676. this._windowIsBackground = true;
  677. };
  678. this._onFocus = () => {
  679. if (this.disablePerformanceMonitorInBackground) {
  680. this._performanceMonitor.enable();
  681. }
  682. this._windowIsBackground = false;
  683. };
  684. this._onCanvasPointerOut = () => {
  685. this.onCanvasPointerOutObservable.notifyObservers(this);
  686. };
  687. window.addEventListener("blur", this._onBlur);
  688. window.addEventListener("focus", this._onFocus);
  689. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  690. // Context lost
  691. if (!this._doNotHandleContextLost) {
  692. this._onContextLost = (evt: Event) => {
  693. evt.preventDefault();
  694. this._contextWasLost = true;
  695. Tools.Warn("WebGL context lost.");
  696. this.onContextLostObservable.notifyObservers(this);
  697. };
  698. this._onContextRestored = (evt: Event) => {
  699. // Adding a timeout to avoid race condition at browser level
  700. setTimeout(()=> {
  701. // Rebuild gl context
  702. this._initGLContext();
  703. // Rebuild effects
  704. this._rebuildEffects();
  705. // Rebuild textures
  706. this._rebuildInternalTextures();
  707. // Rebuild buffers
  708. this._rebuildBuffers();
  709. // Cache
  710. this.wipeCaches(true);
  711. Tools.Warn("WebGL context successfully restored.");
  712. this.onContextRestoredObservable.notifyObservers(this);
  713. this._contextWasLost = false;
  714. }, 0);
  715. };
  716. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  717. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  718. }
  719. } else {
  720. this._gl = <WebGLRenderingContext>canvasOrContext;
  721. this._renderingCanvas = this._gl.canvas
  722. if (this._gl.renderbufferStorageMultisample) {
  723. this._webGLVersion = 2.0;
  724. }
  725. options.stencil = this._gl.getContextAttributes().stencil;
  726. }
  727. // Viewport
  728. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  729. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  730. this.resize();
  731. this._isStencilEnable = options.stencil;
  732. this._initGLContext();
  733. if (canvas) {
  734. // Fullscreen
  735. this._onFullscreenChange = () => {
  736. if (document.fullscreen !== undefined) {
  737. this.isFullscreen = document.fullscreen;
  738. } else if (document.mozFullScreen !== undefined) {
  739. this.isFullscreen = document.mozFullScreen;
  740. } else if (document.webkitIsFullScreen !== undefined) {
  741. this.isFullscreen = document.webkitIsFullScreen;
  742. } else if (document.msIsFullScreen !== undefined) {
  743. this.isFullscreen = document.msIsFullScreen;
  744. }
  745. // Pointer lock
  746. if (this.isFullscreen && this._pointerLockRequested) {
  747. canvas.requestPointerLock = canvas.requestPointerLock ||
  748. canvas.msRequestPointerLock ||
  749. canvas.mozRequestPointerLock ||
  750. canvas.webkitRequestPointerLock;
  751. if (canvas.requestPointerLock) {
  752. canvas.requestPointerLock();
  753. }
  754. }
  755. };
  756. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  757. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  758. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  759. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  760. // Pointer lock
  761. this._onPointerLockChange = () => {
  762. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  763. document.webkitPointerLockElement === canvas ||
  764. document.msPointerLockElement === canvas ||
  765. document.pointerLockElement === canvas
  766. );
  767. };
  768. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  769. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  770. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  771. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  772. this._onVRDisplayPointerRestricted = () => {
  773. canvas.requestPointerLock();
  774. }
  775. this._onVRDisplayPointerUnrestricted = () => {
  776. document.exitPointerLock();
  777. }
  778. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  779. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  780. }
  781. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  782. Engine.audioEngine = new AudioEngine();
  783. }
  784. // Prepare buffer pointers
  785. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  786. this._currentBufferPointers[i] = new BufferPointer();
  787. }
  788. // Load WebVR Devices
  789. if (options.autoEnableWebVR) {
  790. this.initWebVR();
  791. }
  792. // Detect if we are running on a faulty buggy OS.
  793. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  794. // Detect if we are running on a faulty buggy desktop OS.
  795. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  796. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  797. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  798. }
  799. private _rebuildInternalTextures(): void {
  800. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  801. for (var internalTexture of currentState) {
  802. internalTexture._rebuild();
  803. }
  804. }
  805. private _rebuildEffects(): void {
  806. for (var key in this._compiledEffects) {
  807. let effect = <Effect>this._compiledEffects[key];
  808. effect._prepareEffect();
  809. }
  810. Effect.ResetCache();
  811. }
  812. private _rebuildBuffers(): void {
  813. // Index / Vertex
  814. for (var scene of this.scenes) {
  815. scene.resetCachedMaterial();
  816. scene._rebuildGeometries();
  817. scene._rebuildTextures();
  818. }
  819. // Uniforms
  820. for (var uniformBuffer of this._uniformBuffers) {
  821. uniformBuffer._rebuild();
  822. }
  823. }
  824. private _initGLContext(): void {
  825. // Caps
  826. this._caps = new EngineCapabilities();
  827. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  828. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  829. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  830. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  831. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  832. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  833. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  834. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  835. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  836. // Infos
  837. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  838. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  839. if (rendererInfo != null) {
  840. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  841. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  842. }
  843. if (!this._glVendor) {
  844. this._glVendor = "Unknown vendor";
  845. }
  846. if (!this._glRenderer) {
  847. this._glRenderer = "Unknown renderer";
  848. }
  849. // Constants
  850. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  851. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  852. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  853. this._gl.DEPTH24_STENCIL8 = 35056;
  854. // Extensions
  855. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  856. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  857. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  858. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  859. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  860. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  861. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  862. 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');
  863. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  864. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  865. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  866. this._caps.highPrecisionShaderSupported = true;
  867. // Checks if some of the format renders first to allow the use of webgl inspector.
  868. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  869. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  870. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  871. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  872. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  873. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  874. if (this._webGLVersion > 1) {
  875. this._gl.HALF_FLOAT_OES = 0x140B;
  876. }
  877. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  878. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  879. // Draw buffers
  880. if (this._webGLVersion > 1) {
  881. this._caps.drawBuffersExtension = true;
  882. } else {
  883. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  884. if (drawBuffersExtension !== null) {
  885. this._caps.drawBuffersExtension = true;
  886. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  887. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  888. for (var i = 0; i < 16; i++) {
  889. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  890. }
  891. } else {
  892. this._caps.drawBuffersExtension = false;
  893. }
  894. }
  895. // Depth Texture
  896. if (this._webGLVersion > 1) {
  897. this._caps.depthTextureExtension = true;
  898. } else {
  899. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  900. if (depthTextureExtension != null) {
  901. this._caps.depthTextureExtension = true;
  902. }
  903. }
  904. // Vertex array object
  905. if (this._webGLVersion > 1) {
  906. this._caps.vertexArrayObject = true;
  907. } else {
  908. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  909. if (vertexArrayObjectExtension != null) {
  910. this._caps.vertexArrayObject = true;
  911. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  912. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  913. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  914. } else {
  915. this._caps.vertexArrayObject = false;
  916. }
  917. }
  918. // Instances count
  919. if (this._webGLVersion > 1) {
  920. this._caps.instancedArrays = true;
  921. } else {
  922. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  923. if (instanceExtension != null) {
  924. this._caps.instancedArrays = true;
  925. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  926. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  927. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  928. } else {
  929. this._caps.instancedArrays = false;
  930. }
  931. }
  932. // Intelligently add supported compressed formats in order to check for.
  933. // Check for ASTC support first as it is most powerful and to be very cross platform.
  934. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  935. // Likely no hardware which supports both PVR & DXT, so order matters little.
  936. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  937. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  938. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  939. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  940. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  941. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  942. if (this._gl.getShaderPrecisionFormat) {
  943. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  944. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  945. }
  946. // Depth buffer
  947. this.setDepthBuffer(true);
  948. this.setDepthFunctionToLessOrEqual();
  949. this.setDepthWrite(true);
  950. }
  951. public get webGLVersion(): number {
  952. return this._webGLVersion;
  953. }
  954. /**
  955. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  956. */
  957. public get isStencilEnable(): boolean {
  958. return this._isStencilEnable;
  959. }
  960. private _prepareWorkingCanvas(): void {
  961. if (this._workingCanvas) {
  962. return;
  963. }
  964. this._workingCanvas = document.createElement("canvas");
  965. this._workingContext = this._workingCanvas.getContext("2d");
  966. }
  967. public resetTextureCache() {
  968. for (var key in this._activeTexturesCache) {
  969. this._activeTexturesCache[key] = null;
  970. }
  971. }
  972. public isDeterministicLockStep(): boolean {
  973. return this._deterministicLockstep;
  974. }
  975. public getLockstepMaxSteps(): number {
  976. return this._lockstepMaxSteps;
  977. }
  978. public getGlInfo() {
  979. return {
  980. vendor: this._glVendor,
  981. renderer: this._glRenderer,
  982. version: this._glVersion
  983. }
  984. }
  985. public getAspectRatio(camera: Camera, useScreen = false): number {
  986. var viewport = camera.viewport;
  987. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  988. }
  989. public getRenderWidth(useScreen = false): number {
  990. if (!useScreen && this._currentRenderTarget) {
  991. return this._currentRenderTarget.width;
  992. }
  993. return this._gl.drawingBufferWidth;
  994. }
  995. public getRenderHeight(useScreen = false): number {
  996. if (!useScreen && this._currentRenderTarget) {
  997. return this._currentRenderTarget.height;
  998. }
  999. return this._gl.drawingBufferHeight;
  1000. }
  1001. public getRenderingCanvas(): HTMLCanvasElement {
  1002. return this._renderingCanvas;
  1003. }
  1004. public getRenderingCanvasClientRect(): ClientRect {
  1005. return this._renderingCanvas.getBoundingClientRect();
  1006. }
  1007. public setHardwareScalingLevel(level: number): void {
  1008. this._hardwareScalingLevel = level;
  1009. this.resize();
  1010. }
  1011. public getHardwareScalingLevel(): number {
  1012. return this._hardwareScalingLevel;
  1013. }
  1014. public getLoadedTexturesCache(): InternalTexture[] {
  1015. return this._internalTexturesCache;
  1016. }
  1017. public getCaps(): EngineCapabilities {
  1018. return this._caps;
  1019. }
  1020. /** The number of draw calls submitted last frame */
  1021. public get drawCalls(): number {
  1022. return this._drawCalls.current;
  1023. }
  1024. public get drawCallsPerfCounter(): PerfCounter {
  1025. return this._drawCalls;
  1026. }
  1027. public getDepthFunction(): number {
  1028. return this._depthCullingState.depthFunc;
  1029. }
  1030. public setDepthFunction(depthFunc: number) {
  1031. this._depthCullingState.depthFunc = depthFunc;
  1032. }
  1033. public setDepthFunctionToGreater(): void {
  1034. this._depthCullingState.depthFunc = this._gl.GREATER;
  1035. }
  1036. public setDepthFunctionToGreaterOrEqual(): void {
  1037. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1038. }
  1039. public setDepthFunctionToLess(): void {
  1040. this._depthCullingState.depthFunc = this._gl.LESS;
  1041. }
  1042. public setDepthFunctionToLessOrEqual(): void {
  1043. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1044. }
  1045. public getStencilBuffer(): boolean {
  1046. return this._stencilState.stencilTest;
  1047. }
  1048. public setStencilBuffer(enable: boolean): void {
  1049. this._stencilState.stencilTest = enable;
  1050. }
  1051. public getStencilMask(): number {
  1052. return this._stencilState.stencilMask;
  1053. }
  1054. public setStencilMask(mask: number): void {
  1055. this._stencilState.stencilMask = mask;
  1056. }
  1057. public getStencilFunction(): number {
  1058. return this._stencilState.stencilFunc;
  1059. }
  1060. public getStencilFunctionReference(): number {
  1061. return this._stencilState.stencilFuncRef;
  1062. }
  1063. public getStencilFunctionMask(): number {
  1064. return this._stencilState.stencilFuncMask;
  1065. }
  1066. public setStencilFunction(stencilFunc: number) {
  1067. this._stencilState.stencilFunc = stencilFunc;
  1068. }
  1069. public setStencilFunctionReference(reference: number) {
  1070. this._stencilState.stencilFuncRef = reference;
  1071. }
  1072. public setStencilFunctionMask(mask: number) {
  1073. this._stencilState.stencilFuncMask = mask;
  1074. }
  1075. public getStencilOperationFail(): number {
  1076. return this._stencilState.stencilOpStencilFail;
  1077. }
  1078. public getStencilOperationDepthFail(): number {
  1079. return this._stencilState.stencilOpDepthFail;
  1080. }
  1081. public getStencilOperationPass(): number {
  1082. return this._stencilState.stencilOpStencilDepthPass;
  1083. }
  1084. public setStencilOperationFail(operation: number): void {
  1085. this._stencilState.stencilOpStencilFail = operation;
  1086. }
  1087. public setStencilOperationDepthFail(operation: number): void {
  1088. this._stencilState.stencilOpDepthFail = operation;
  1089. }
  1090. public setStencilOperationPass(operation: number): void {
  1091. this._stencilState.stencilOpStencilDepthPass = operation;
  1092. }
  1093. public setDitheringState(value: boolean): void {
  1094. if (value) {
  1095. this._gl.enable(this._gl.DITHER);
  1096. } else {
  1097. this._gl.disable(this._gl.DITHER);
  1098. }
  1099. }
  1100. /**
  1101. * stop executing a render loop function and remove it from the execution array
  1102. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  1103. */
  1104. public stopRenderLoop(renderFunction?: () => void): void {
  1105. if (!renderFunction) {
  1106. this._activeRenderLoops = [];
  1107. return;
  1108. }
  1109. var index = this._activeRenderLoops.indexOf(renderFunction);
  1110. if (index >= 0) {
  1111. this._activeRenderLoops.splice(index, 1);
  1112. }
  1113. }
  1114. public _renderLoop(): void {
  1115. if (this._activeRenderLoops.length > 0) {
  1116. // Register new frame
  1117. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  1118. } else {
  1119. this._renderingQueueLaunched = false;
  1120. }
  1121. // Effective render
  1122. if (!this._contextWasLost) {
  1123. var shouldRender = true;
  1124. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1125. shouldRender = false;
  1126. }
  1127. if (shouldRender) {
  1128. // Start new frame
  1129. this.beginFrame();
  1130. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1131. var renderFunction = this._activeRenderLoops[index];
  1132. renderFunction();
  1133. }
  1134. // Present
  1135. this.endFrame();
  1136. }
  1137. }
  1138. }
  1139. /**
  1140. * Register and execute a render loop. The engine can have more than one render function.
  1141. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  1142. * @example
  1143. * engine.runRenderLoop(function () {
  1144. * scene.render()
  1145. * })
  1146. */
  1147. public runRenderLoop(renderFunction: () => void): void {
  1148. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1149. return;
  1150. }
  1151. this._activeRenderLoops.push(renderFunction);
  1152. if (!this._renderingQueueLaunched) {
  1153. this._renderingQueueLaunched = true;
  1154. this._bindedRenderFunction = this._renderLoop.bind(this);
  1155. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1156. }
  1157. }
  1158. /**
  1159. * Toggle full screen mode.
  1160. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  1161. * @param {any} options - an options object to be sent to the requestFullscreen function
  1162. */
  1163. public switchFullscreen(requestPointerLock: boolean): void {
  1164. if (this.isFullscreen) {
  1165. Tools.ExitFullscreen();
  1166. } else {
  1167. this._pointerLockRequested = requestPointerLock;
  1168. Tools.RequestFullscreen(this._renderingCanvas);
  1169. }
  1170. }
  1171. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1172. this.applyStates();
  1173. var mode = 0;
  1174. if (backBuffer && color) {
  1175. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1176. mode |= this._gl.COLOR_BUFFER_BIT;
  1177. }
  1178. if (depth) {
  1179. this._gl.clearDepth(1.0);
  1180. mode |= this._gl.DEPTH_BUFFER_BIT;
  1181. }
  1182. if (stencil) {
  1183. this._gl.clearStencil(0);
  1184. mode |= this._gl.STENCIL_BUFFER_BIT;
  1185. }
  1186. this._gl.clear(mode);
  1187. }
  1188. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1189. let gl = this._gl;
  1190. // Save state
  1191. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1192. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1193. // Change state
  1194. gl.enable(gl.SCISSOR_TEST);
  1195. gl.scissor(x, y, width, height);
  1196. // Clear
  1197. this.clear(clearColor, true, true, true);
  1198. // Restore state
  1199. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1200. if (curScissor === true) {
  1201. gl.enable(gl.SCISSOR_TEST);
  1202. } else {
  1203. gl.disable(gl.SCISSOR_TEST);
  1204. }
  1205. }
  1206. /**
  1207. * Set the WebGL's viewport
  1208. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  1209. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  1210. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  1211. */
  1212. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1213. var width = requiredWidth || this.getRenderWidth();
  1214. var height = requiredHeight || this.getRenderHeight();
  1215. var x = viewport.x || 0;
  1216. var y = viewport.y || 0;
  1217. this._cachedViewport = viewport;
  1218. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1219. }
  1220. /**
  1221. * Directly set the WebGL Viewport
  1222. * The x, y, width & height are directly passed to the WebGL call
  1223. * @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.
  1224. */
  1225. public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
  1226. let currentViewport = this._cachedViewport;
  1227. this._cachedViewport = null;
  1228. this._gl.viewport(x, y, width, height);
  1229. return currentViewport;
  1230. }
  1231. public beginFrame(): void {
  1232. this._measureFps();
  1233. }
  1234. public endFrame(): void {
  1235. //force a flush in case we are using a bad OS.
  1236. if (this._badOS) {
  1237. this.flushFramebuffer();
  1238. }
  1239. //submit frame to the vr device, if enabled
  1240. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  1241. this._vrDisplayEnabled.submitFrame()
  1242. }
  1243. }
  1244. /**
  1245. * resize the view according to the canvas' size.
  1246. * @example
  1247. * window.addEventListener("resize", function () {
  1248. * engine.resize();
  1249. * });
  1250. */
  1251. public resize(): void {
  1252. // We're not resizing the size of the canvas while in VR mode & presenting
  1253. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  1254. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  1255. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  1256. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1257. }
  1258. }
  1259. /**
  1260. * force a specific size of the canvas
  1261. * @param {number} width - the new canvas' width
  1262. * @param {number} height - the new canvas' height
  1263. */
  1264. public setSize(width: number, height: number): void {
  1265. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1266. return;
  1267. }
  1268. this._renderingCanvas.width = width;
  1269. this._renderingCanvas.height = height;
  1270. for (var index = 0; index < this.scenes.length; index++) {
  1271. var scene = this.scenes[index];
  1272. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1273. var cam = scene.cameras[camIndex];
  1274. cam._currentRenderId = 0;
  1275. }
  1276. }
  1277. if (this.onResizeObservable.hasObservers) {
  1278. this.onResizeObservable.notifyObservers(this);
  1279. }
  1280. }
  1281. //WebVR functions
  1282. public isVRDevicePresent(callback: (result: boolean) => void) {
  1283. this.getVRDevice(null, (device) => {
  1284. callback(device !== null);
  1285. });
  1286. }
  1287. public getVRDevice(name: string, callback: (device: any) => void) {
  1288. if (!this.vrDisplaysPromise) {
  1289. callback(null);
  1290. return;
  1291. }
  1292. this.vrDisplaysPromise.then((devices) => {
  1293. if (devices.length > 0) {
  1294. if (name) {
  1295. var found = devices.some(device => {
  1296. if (device.displayName === name) {
  1297. callback(device);
  1298. return true;
  1299. } else {
  1300. return false;
  1301. }
  1302. });
  1303. if (!found) {
  1304. Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  1305. callback(devices[0]);
  1306. }
  1307. } else {
  1308. //choose the first one
  1309. callback(devices[0]);
  1310. }
  1311. } else {
  1312. Tools.Error("No WebVR devices found!");
  1313. callback(null);
  1314. }
  1315. });
  1316. }
  1317. public initWebVR(): void {
  1318. if (!this.vrDisplaysPromise) {
  1319. this._getVRDisplays();
  1320. }
  1321. }
  1322. public enableVR(vrDevice) {
  1323. this._vrDisplayEnabled = vrDevice;
  1324. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  1325. }
  1326. public disableVR() {
  1327. if (this._vrDisplayEnabled) {
  1328. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  1329. }
  1330. }
  1331. private _onVRFullScreenTriggered = () => {
  1332. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  1333. //get the old size before we change
  1334. this._oldSize = new BABYLON.Size(this.getRenderWidth(), this.getRenderHeight());
  1335. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1336. //get the width and height, change the render size
  1337. var leftEye = this._vrDisplayEnabled.getEyeParameters('left');
  1338. var width, height;
  1339. this.setHardwareScalingLevel(1);
  1340. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1341. } else {
  1342. //When the specs are implemented, need to uncomment this.
  1343. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1344. this.setSize(this._oldSize.width, this._oldSize.height);
  1345. this._vrDisplayEnabled = undefined;
  1346. }
  1347. }
  1348. private _getVRDisplays() {
  1349. var getWebVRDevices = (devices: Array<any>) => {
  1350. this._vrDisplays = devices.filter(function (device) {
  1351. return device instanceof VRDisplay;
  1352. });
  1353. return this._vrDisplays;
  1354. }
  1355. if (navigator.getVRDisplays) {
  1356. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  1357. }
  1358. }
  1359. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1360. if (this._currentRenderTarget) {
  1361. this.unBindFramebuffer(this._currentRenderTarget);
  1362. }
  1363. this._currentRenderTarget = texture;
  1364. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1365. var gl = this._gl;
  1366. if (texture.isCube) {
  1367. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  1368. }
  1369. if (this._cachedViewport && !forceFullscreenViewport) {
  1370. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1371. } else {
  1372. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  1373. }
  1374. this.wipeCaches();
  1375. }
  1376. private bindUnboundFramebuffer(framebuffer: WebGLFramebuffer) {
  1377. if (this._currentFramebuffer !== framebuffer) {
  1378. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1379. this._currentFramebuffer = framebuffer;
  1380. }
  1381. }
  1382. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1383. this._currentRenderTarget = null;
  1384. // If MSAA, we need to bitblt back to main texture
  1385. var gl = this._gl;
  1386. if (texture._MSAAFramebuffer) {
  1387. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1388. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1389. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1390. 0, 0, texture.width, texture.height,
  1391. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1392. }
  1393. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1394. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1395. gl.generateMipmap(gl.TEXTURE_2D);
  1396. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1397. }
  1398. if (onBeforeUnbind) {
  1399. if (texture._MSAAFramebuffer) {
  1400. // Bind the correct framebuffer
  1401. this.bindUnboundFramebuffer(texture._framebuffer);
  1402. }
  1403. onBeforeUnbind();
  1404. }
  1405. this.bindUnboundFramebuffer(null);
  1406. }
  1407. public generateMipMapsForCubemap(texture: InternalTexture) {
  1408. if (texture.generateMipMaps) {
  1409. var gl = this._gl;
  1410. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1411. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1412. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1413. }
  1414. }
  1415. public flushFramebuffer(): void {
  1416. this._gl.flush();
  1417. }
  1418. public restoreDefaultFramebuffer(): void {
  1419. if (this._currentRenderTarget) {
  1420. this.unBindFramebuffer(this._currentRenderTarget);
  1421. } else {
  1422. this.bindUnboundFramebuffer(null);
  1423. }
  1424. if (this._cachedViewport) {
  1425. this.setViewport(this._cachedViewport);
  1426. }
  1427. this.wipeCaches();
  1428. }
  1429. // UBOs
  1430. public createUniformBuffer(elements: number[] | Float32Array): WebGLBuffer {
  1431. var ubo = this._gl.createBuffer();
  1432. this.bindUniformBuffer(ubo);
  1433. if (elements instanceof Float32Array) {
  1434. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  1435. } else {
  1436. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  1437. }
  1438. this.bindUniformBuffer(null);
  1439. ubo.references = 1;
  1440. return ubo;
  1441. }
  1442. public createDynamicUniformBuffer(elements: number[] | Float32Array): WebGLBuffer {
  1443. var ubo = this._gl.createBuffer();
  1444. this.bindUniformBuffer(ubo);
  1445. if (elements instanceof Float32Array) {
  1446. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  1447. } else {
  1448. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  1449. }
  1450. this.bindUniformBuffer(null);
  1451. ubo.references = 1;
  1452. return ubo;
  1453. }
  1454. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: number[] | Float32Array, offset?: number, count?: number): void {
  1455. this.bindUniformBuffer(uniformBuffer);
  1456. if (offset === undefined) {
  1457. offset = 0;
  1458. }
  1459. if (count === undefined) {
  1460. if (elements instanceof Float32Array) {
  1461. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  1462. } else {
  1463. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  1464. }
  1465. } else {
  1466. if (elements instanceof Float32Array) {
  1467. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  1468. } else {
  1469. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  1470. }
  1471. }
  1472. this.bindUniformBuffer(null);
  1473. }
  1474. // VBOs
  1475. private _resetVertexBufferBinding(): void {
  1476. this.bindArrayBuffer(null);
  1477. this._cachedVertexBuffers = null;
  1478. }
  1479. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1480. var vbo = this._gl.createBuffer();
  1481. this.bindArrayBuffer(vbo);
  1482. if (vertices instanceof Float32Array) {
  1483. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1484. } else {
  1485. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1486. }
  1487. this._resetVertexBufferBinding();
  1488. vbo.references = 1;
  1489. return vbo;
  1490. }
  1491. public createDynamicVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1492. var vbo = this._gl.createBuffer();
  1493. this.bindArrayBuffer(vbo);
  1494. if (vertices instanceof Float32Array) {
  1495. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1496. } else {
  1497. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1498. }
  1499. this._resetVertexBufferBinding();
  1500. vbo.references = 1;
  1501. return vbo;
  1502. }
  1503. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number, count?: number): void {
  1504. this.bindArrayBuffer(vertexBuffer);
  1505. if (offset === undefined) {
  1506. offset = 0;
  1507. }
  1508. if (count === undefined) {
  1509. if (vertices instanceof Float32Array) {
  1510. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1511. } else {
  1512. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1513. }
  1514. } else {
  1515. if (vertices instanceof Float32Array) {
  1516. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1517. } else {
  1518. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1519. }
  1520. }
  1521. this._resetVertexBufferBinding();
  1522. }
  1523. private _resetIndexBufferBinding(): void {
  1524. this.bindIndexBuffer(null);
  1525. this._cachedIndexBuffer = null;
  1526. }
  1527. public createIndexBuffer(indices: IndicesArray): WebGLBuffer {
  1528. var vbo = this._gl.createBuffer();
  1529. this.bindIndexBuffer(vbo);
  1530. // Check for 32 bits indices
  1531. var arrayBuffer;
  1532. var need32Bits = false;
  1533. if (indices instanceof Uint16Array) {
  1534. arrayBuffer = indices;
  1535. } else {
  1536. //check 32 bit support
  1537. if (this._caps.uintIndices) {
  1538. if (indices instanceof Uint32Array) {
  1539. arrayBuffer = indices;
  1540. need32Bits = true;
  1541. } else {
  1542. //number[] or Int32Array, check if 32 bit is necessary
  1543. for (var index = 0; index < indices.length; index++) {
  1544. if (indices[index] > 65535) {
  1545. need32Bits = true;
  1546. break;
  1547. }
  1548. }
  1549. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1550. }
  1551. } else {
  1552. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1553. arrayBuffer = new Uint16Array(indices);
  1554. }
  1555. }
  1556. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  1557. this._resetIndexBufferBinding();
  1558. vbo.references = 1;
  1559. vbo.is32Bits = need32Bits;
  1560. return vbo;
  1561. }
  1562. public bindArrayBuffer(buffer: WebGLBuffer): void {
  1563. if (!this._vaoRecordInProgress) {
  1564. this._unbindVertexArrayObject();
  1565. }
  1566. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1567. }
  1568. public bindUniformBuffer(buffer?: WebGLBuffer): void {
  1569. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  1570. }
  1571. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  1572. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  1573. }
  1574. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  1575. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  1576. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  1577. };
  1578. private bindIndexBuffer(buffer: WebGLBuffer): void {
  1579. if (!this._vaoRecordInProgress) {
  1580. this._unbindVertexArrayObject();
  1581. }
  1582. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1583. }
  1584. private bindBuffer(buffer: WebGLBuffer, target: number): void {
  1585. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1586. this._gl.bindBuffer(target, buffer);
  1587. this._currentBoundBuffer[target] = buffer;
  1588. }
  1589. }
  1590. public updateArrayBuffer(data: Float32Array): void {
  1591. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1592. }
  1593. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1594. var pointer = this._currentBufferPointers[indx];
  1595. var changed = false;
  1596. if (!pointer.active) {
  1597. changed = true;
  1598. pointer.active = true;
  1599. pointer.index = indx;
  1600. pointer.size = size;
  1601. pointer.type = type;
  1602. pointer.normalized = normalized;
  1603. pointer.stride = stride;
  1604. pointer.offset = offset;
  1605. pointer.buffer = buffer;
  1606. } else {
  1607. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1608. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1609. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1610. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1611. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1612. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1613. }
  1614. if (changed || this._vaoRecordInProgress) {
  1615. this.bindArrayBuffer(buffer);
  1616. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1617. }
  1618. }
  1619. private _bindIndexBufferWithCache(indexBuffer: WebGLBuffer): void {
  1620. if (indexBuffer == null) {
  1621. return;
  1622. }
  1623. if (this._cachedIndexBuffer !== indexBuffer) {
  1624. this._cachedIndexBuffer = indexBuffer;
  1625. this.bindIndexBuffer(indexBuffer);
  1626. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1627. }
  1628. }
  1629. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: VertexBuffer; }, effect: Effect) {
  1630. var attributes = effect.getAttributesNames();
  1631. if (!this._vaoRecordInProgress) {
  1632. this._unbindVertexArrayObject();
  1633. }
  1634. this.unbindAllAttributes();
  1635. for (var index = 0; index < attributes.length; index++) {
  1636. var order = effect.getAttributeLocation(index);
  1637. if (order >= 0) {
  1638. var vertexBuffer = vertexBuffers[attributes[index]];
  1639. if (!vertexBuffer) {
  1640. continue;
  1641. }
  1642. this._gl.enableVertexAttribArray(order);
  1643. if (!this._vaoRecordInProgress) {
  1644. this._vertexAttribArraysEnabled[order] = true;
  1645. }
  1646. var buffer = vertexBuffer.getBuffer();
  1647. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1648. if (vertexBuffer.getIsInstanced()) {
  1649. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1650. if (!this._vaoRecordInProgress) {
  1651. this._currentInstanceLocations.push(order);
  1652. this._currentInstanceBuffers.push(buffer);
  1653. }
  1654. }
  1655. }
  1656. }
  1657. }
  1658. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): WebGLVertexArrayObject {
  1659. var vao = this._gl.createVertexArray();
  1660. this._vaoRecordInProgress = true;
  1661. this._gl.bindVertexArray(vao);
  1662. this._mustWipeVertexAttributes = true;
  1663. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1664. this.bindIndexBuffer(indexBuffer);
  1665. this._vaoRecordInProgress = false;
  1666. this._gl.bindVertexArray(null);
  1667. return vao;
  1668. }
  1669. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: WebGLBuffer): void {
  1670. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1671. this._cachedVertexArrayObject = vertexArrayObject;
  1672. this._gl.bindVertexArray(vertexArrayObject);
  1673. this._cachedVertexBuffers = null;
  1674. this._cachedIndexBuffer = null;
  1675. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1676. this._mustWipeVertexAttributes = true;
  1677. }
  1678. }
  1679. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1680. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1681. this._cachedVertexBuffers = vertexBuffer;
  1682. this._cachedEffectForVertexBuffers = effect;
  1683. let attributesCount = effect.getAttributesCount();
  1684. this._unbindVertexArrayObject();
  1685. this.unbindAllAttributes();
  1686. var offset = 0;
  1687. for (var index = 0; index < attributesCount; index++) {
  1688. if (index < vertexDeclaration.length) {
  1689. var order = effect.getAttributeLocation(index);
  1690. if (order >= 0) {
  1691. this._gl.enableVertexAttribArray(order);
  1692. this._vertexAttribArraysEnabled[order] = true;
  1693. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1694. }
  1695. offset += vertexDeclaration[index] * 4;
  1696. }
  1697. }
  1698. }
  1699. this._bindIndexBufferWithCache(indexBuffer);
  1700. }
  1701. private _unbindVertexArrayObject(): void {
  1702. if (!this._cachedVertexArrayObject) {
  1703. return;
  1704. }
  1705. this._cachedVertexArrayObject = null;
  1706. this._gl.bindVertexArray(null);
  1707. }
  1708. public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): void {
  1709. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1710. this._cachedVertexBuffers = vertexBuffers;
  1711. this._cachedEffectForVertexBuffers = effect;
  1712. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1713. }
  1714. this._bindIndexBufferWithCache(indexBuffer);
  1715. }
  1716. public unbindInstanceAttributes() {
  1717. var boundBuffer;
  1718. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1719. var instancesBuffer = this._currentInstanceBuffers[i];
  1720. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1721. boundBuffer = instancesBuffer;
  1722. this.bindArrayBuffer(instancesBuffer);
  1723. }
  1724. var offsetLocation = this._currentInstanceLocations[i];
  1725. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1726. }
  1727. this._currentInstanceBuffers.length = 0;
  1728. this._currentInstanceLocations.length = 0;
  1729. }
  1730. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1731. this._gl.deleteVertexArray(vao);
  1732. }
  1733. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1734. buffer.references--;
  1735. if (buffer.references === 0) {
  1736. this._gl.deleteBuffer(buffer);
  1737. return true;
  1738. }
  1739. return false;
  1740. }
  1741. public createInstancesBuffer(capacity: number): WebGLBuffer {
  1742. var buffer = this._gl.createBuffer();
  1743. buffer.capacity = capacity;
  1744. this.bindArrayBuffer(buffer);
  1745. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1746. return buffer;
  1747. }
  1748. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  1749. this._gl.deleteBuffer(buffer);
  1750. }
  1751. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1752. this.bindArrayBuffer(instancesBuffer);
  1753. if (data) {
  1754. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1755. }
  1756. if ((<any>offsetLocations[0]).index !== undefined) {
  1757. let stride = 0;
  1758. for (let i = 0; i < offsetLocations.length; i++) {
  1759. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1760. stride += ai.attributeSize * 4;
  1761. }
  1762. for (let i = 0; i < offsetLocations.length; i++) {
  1763. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1764. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1765. this._gl.enableVertexAttribArray(ai.index);
  1766. this._vertexAttribArraysEnabled[ai.index] = true;
  1767. }
  1768. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1769. this._gl.vertexAttribDivisor(ai.index, 1);
  1770. this._currentInstanceLocations.push(ai.index);
  1771. this._currentInstanceBuffers.push(instancesBuffer);
  1772. }
  1773. } else {
  1774. for (let index = 0; index < 4; index++) {
  1775. let offsetLocation = <number>offsetLocations[index];
  1776. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1777. this._gl.enableVertexAttribArray(offsetLocation);
  1778. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1779. }
  1780. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1781. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1782. this._currentInstanceLocations.push(offsetLocation);
  1783. this._currentInstanceBuffers.push(instancesBuffer);
  1784. }
  1785. }
  1786. }
  1787. public applyStates() {
  1788. this._depthCullingState.apply(this._gl);
  1789. this._stencilState.apply(this._gl);
  1790. this._alphaState.apply(this._gl);
  1791. }
  1792. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1793. // Apply states
  1794. this.applyStates();
  1795. this._drawCalls.addCount(1, false);
  1796. // Render
  1797. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1798. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1799. if (instancesCount) {
  1800. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1801. return;
  1802. }
  1803. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1804. }
  1805. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1806. // Apply states
  1807. this.applyStates();
  1808. this._drawCalls.addCount(1, false);
  1809. if (instancesCount) {
  1810. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1811. return;
  1812. }
  1813. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1814. }
  1815. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1816. // Apply states
  1817. this.applyStates();
  1818. this._drawCalls.addCount(1, false);
  1819. if (instancesCount) {
  1820. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1821. return;
  1822. }
  1823. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1824. }
  1825. // Shaders
  1826. public _releaseEffect(effect: Effect): void {
  1827. if (this._compiledEffects[effect._key]) {
  1828. delete this._compiledEffects[effect._key];
  1829. if (effect.getProgram()) {
  1830. this._gl.deleteProgram(effect.getProgram());
  1831. }
  1832. }
  1833. }
  1834. /**
  1835. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  1836. * @param samplers An array of string used to represent textures
  1837. */
  1838. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  1839. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  1840. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1841. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1842. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  1843. if (this._compiledEffects[name]) {
  1844. var compiledEffect = <Effect>this._compiledEffects[name];
  1845. if (onCompiled && compiledEffect.isReady()) {
  1846. onCompiled(compiledEffect);
  1847. }
  1848. return compiledEffect;
  1849. }
  1850. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1851. effect._key = name;
  1852. this._compiledEffects[name] = effect;
  1853. return effect;
  1854. }
  1855. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  1856. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  1857. return this.createEffect(
  1858. {
  1859. vertex: "particles",
  1860. fragmentElement: fragmentName
  1861. },
  1862. ["position", "color", "options"],
  1863. ["view", "projection"].concat(uniformsNames),
  1864. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1865. }
  1866. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string, context?: WebGLRenderingContext): WebGLProgram {
  1867. context = context || this._gl;
  1868. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  1869. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  1870. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  1871. var shaderProgram = context.createProgram();
  1872. context.attachShader(shaderProgram, vertexShader);
  1873. context.attachShader(shaderProgram, fragmentShader);
  1874. context.linkProgram(shaderProgram);
  1875. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1876. if (!linked) {
  1877. context.validateProgram(shaderProgram);
  1878. var error = context.getProgramInfoLog(shaderProgram);
  1879. if (error) {
  1880. throw new Error(error);
  1881. }
  1882. }
  1883. context.deleteShader(vertexShader);
  1884. context.deleteShader(fragmentShader);
  1885. return shaderProgram;
  1886. }
  1887. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  1888. var results = [];
  1889. for (var index = 0; index < uniformsNames.length; index++) {
  1890. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1891. }
  1892. return results;
  1893. }
  1894. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  1895. var results = [];
  1896. for (var index = 0; index < attributesNames.length; index++) {
  1897. try {
  1898. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1899. } catch (e) {
  1900. results.push(-1);
  1901. }
  1902. }
  1903. return results;
  1904. }
  1905. public enableEffect(effect: Effect): void {
  1906. // Use program
  1907. this.setProgram(effect.getProgram());
  1908. this._currentEffect = effect;
  1909. if (effect.onBind) {
  1910. effect.onBind(effect);
  1911. }
  1912. effect.onBindObservable.notifyObservers(effect);
  1913. }
  1914. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  1915. if (!uniform)
  1916. return;
  1917. this._gl.uniform1iv(uniform, array);
  1918. }
  1919. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  1920. if (!uniform || array.length % 2 !== 0)
  1921. return;
  1922. this._gl.uniform2iv(uniform, array);
  1923. }
  1924. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  1925. if (!uniform || array.length % 3 !== 0)
  1926. return;
  1927. this._gl.uniform3iv(uniform, array);
  1928. }
  1929. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  1930. if (!uniform || array.length % 4 !== 0)
  1931. return;
  1932. this._gl.uniform4iv(uniform, array);
  1933. }
  1934. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  1935. if (!uniform)
  1936. return;
  1937. this._gl.uniform1fv(uniform, array);
  1938. }
  1939. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  1940. if (!uniform || array.length % 2 !== 0)
  1941. return;
  1942. this._gl.uniform2fv(uniform, array);
  1943. }
  1944. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  1945. if (!uniform || array.length % 3 !== 0)
  1946. return;
  1947. this._gl.uniform3fv(uniform, array);
  1948. }
  1949. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  1950. if (!uniform || array.length % 4 !== 0)
  1951. return;
  1952. this._gl.uniform4fv(uniform, array);
  1953. }
  1954. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  1955. if (!uniform)
  1956. return;
  1957. this._gl.uniform1fv(uniform, <any>array);
  1958. }
  1959. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  1960. if (!uniform || array.length % 2 !== 0)
  1961. return;
  1962. this._gl.uniform2fv(uniform, <any>array);
  1963. }
  1964. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1965. if (!uniform || array.length % 3 !== 0)
  1966. return;
  1967. this._gl.uniform3fv(uniform, <any>array);
  1968. }
  1969. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1970. if (!uniform || array.length % 4 !== 0)
  1971. return;
  1972. this._gl.uniform4fv(uniform, <any>array);
  1973. }
  1974. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1975. if (!uniform)
  1976. return;
  1977. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1978. }
  1979. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1980. if (!uniform)
  1981. return;
  1982. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1983. }
  1984. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1985. if (!uniform)
  1986. return;
  1987. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1988. }
  1989. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1990. if (!uniform)
  1991. return;
  1992. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1993. }
  1994. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1995. if (!uniform)
  1996. return;
  1997. this._gl.uniform1f(uniform, value);
  1998. }
  1999. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  2000. if (!uniform)
  2001. return;
  2002. this._gl.uniform2f(uniform, x, y);
  2003. }
  2004. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  2005. if (!uniform)
  2006. return;
  2007. this._gl.uniform3f(uniform, x, y, z);
  2008. }
  2009. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  2010. if (!uniform)
  2011. return;
  2012. this._gl.uniform1i(uniform, bool);
  2013. }
  2014. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  2015. if (!uniform)
  2016. return;
  2017. this._gl.uniform4f(uniform, x, y, z, w);
  2018. }
  2019. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  2020. if (!uniform)
  2021. return;
  2022. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  2023. }
  2024. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  2025. if (!uniform)
  2026. return;
  2027. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  2028. }
  2029. // States
  2030. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  2031. // Culling
  2032. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  2033. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  2034. var cullFace = this.cullBackFaces ? showSide : hideSide;
  2035. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  2036. if (culling) {
  2037. this._depthCullingState.cullFace = cullFace;
  2038. this._depthCullingState.cull = true;
  2039. } else {
  2040. this._depthCullingState.cull = false;
  2041. }
  2042. }
  2043. // Z offset
  2044. this.setZOffset(zOffset);
  2045. }
  2046. public setZOffset(value: number): void {
  2047. this._depthCullingState.zOffset = value;
  2048. }
  2049. public getZOffset(): number {
  2050. return this._depthCullingState.zOffset;
  2051. }
  2052. public setDepthBuffer(enable: boolean): void {
  2053. this._depthCullingState.depthTest = enable;
  2054. }
  2055. public getDepthWrite(): boolean {
  2056. return this._depthCullingState.depthMask;
  2057. }
  2058. public setDepthWrite(enable: boolean): void {
  2059. this._depthCullingState.depthMask = enable;
  2060. }
  2061. public setColorWrite(enable: boolean): void {
  2062. this._gl.colorMask(enable, enable, enable, enable);
  2063. this._colorWrite = enable;
  2064. }
  2065. public getColorWrite(): boolean {
  2066. return this._colorWrite;
  2067. }
  2068. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  2069. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  2070. }
  2071. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  2072. if (this._alphaMode === mode) {
  2073. return;
  2074. }
  2075. switch (mode) {
  2076. case Engine.ALPHA_DISABLE:
  2077. this._alphaState.alphaBlend = false;
  2078. break;
  2079. case Engine.ALPHA_PREMULTIPLIED:
  2080. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2081. this._alphaState.alphaBlend = true;
  2082. break;
  2083. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  2084. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2085. this._alphaState.alphaBlend = true;
  2086. break;
  2087. case Engine.ALPHA_COMBINE:
  2088. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  2089. this._alphaState.alphaBlend = true;
  2090. break;
  2091. case Engine.ALPHA_ONEONE:
  2092. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2093. this._alphaState.alphaBlend = true;
  2094. break;
  2095. case Engine.ALPHA_ADD:
  2096. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  2097. this._alphaState.alphaBlend = true;
  2098. break;
  2099. case Engine.ALPHA_SUBTRACT:
  2100. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2101. this._alphaState.alphaBlend = true;
  2102. break;
  2103. case Engine.ALPHA_MULTIPLY:
  2104. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  2105. this._alphaState.alphaBlend = true;
  2106. break;
  2107. case Engine.ALPHA_MAXIMIZED:
  2108. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  2109. this._alphaState.alphaBlend = true;
  2110. break;
  2111. case Engine.ALPHA_INTERPOLATE:
  2112. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  2113. this._alphaState.alphaBlend = true;
  2114. break;
  2115. case Engine.ALPHA_SCREENMODE:
  2116. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  2117. this._alphaState.alphaBlend = true;
  2118. break;
  2119. }
  2120. if (!noDepthWriteChange) {
  2121. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  2122. }
  2123. this._alphaMode = mode;
  2124. }
  2125. public getAlphaMode(): number {
  2126. return this._alphaMode;
  2127. }
  2128. public setAlphaTesting(enable: boolean): void {
  2129. this._alphaTest = enable;
  2130. }
  2131. public getAlphaTesting(): boolean {
  2132. return !!this._alphaTest;
  2133. }
  2134. // Textures
  2135. public wipeCaches(bruteForce?: boolean): void {
  2136. if (this.preventCacheWipeBetweenFrames) {
  2137. return;
  2138. }
  2139. this.resetTextureCache();
  2140. this._currentEffect = null;
  2141. // 6/8/2017: deltakosh: Should not be required anymore.
  2142. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  2143. if (bruteForce) {
  2144. this._currentProgram = null;
  2145. this._stencilState.reset();
  2146. this._depthCullingState.reset();
  2147. this.setDepthFunctionToLessOrEqual();
  2148. this._alphaState.reset();
  2149. }
  2150. this._cachedVertexBuffers = null;
  2151. this._cachedIndexBuffer = null;
  2152. this._cachedEffectForVertexBuffers = null;
  2153. this._unbindVertexArrayObject();
  2154. this.bindIndexBuffer(null);
  2155. this.bindArrayBuffer(null);
  2156. }
  2157. /**
  2158. * Set the compressed texture format to use, based on the formats you have, and the formats
  2159. * supported by the hardware / browser.
  2160. *
  2161. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  2162. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  2163. * to API arguments needed to compressed textures. This puts the burden on the container
  2164. * generator to house the arcane code for determining these for current & future formats.
  2165. *
  2166. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  2167. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  2168. *
  2169. * Note: The result of this call is not taken into account when a texture is base64.
  2170. *
  2171. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  2172. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  2173. *
  2174. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  2175. * @returns The extension selected.
  2176. */
  2177. public setTextureFormatToUse(formatsAvailable: Array<string>): string {
  2178. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  2179. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  2180. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  2181. return this._textureFormatInUse = this._texturesSupported[i];
  2182. }
  2183. }
  2184. }
  2185. // actively set format to nothing, to allow this to be called more than once
  2186. // and possibly fail the 2nd time
  2187. return this._textureFormatInUse = null;
  2188. }
  2189. public _createTexture(): WebGLTexture {
  2190. return this._gl.createTexture();
  2191. }
  2192. /**
  2193. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  2194. * @param {string} urlArg- This contains one of the following:
  2195. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  2196. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2197. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2198. *
  2199. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  2200. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  2201. * @param {Scene} scene- Needed for loading to the correct scene.
  2202. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  2203. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  2204. * @param {callback} onError- Optional callback to be called upon failure.
  2205. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  2206. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  2207. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  2208. *
  2209. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  2210. */
  2211. public createTexture(urlArg: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: ArrayBuffer | HTMLImageElement = null, fallBack?: InternalTexture, format?: number): InternalTexture {
  2212. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2213. var fromData = url.substr(0, 5) === "data:";
  2214. var fromBlob = url.substr(0, 5) === "blob:";
  2215. var isBase64 = fromData && url.indexOf("base64") !== -1;
  2216. let texture = fallBack ? fallBack : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  2217. // establish the file extension, if possible
  2218. var lastDot = url.lastIndexOf('.');
  2219. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  2220. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  2221. var isTGA = (extension === ".tga");
  2222. // determine if a ktx file should be substituted
  2223. var isKTX = false;
  2224. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  2225. url = url.substring(0, lastDot) + this._textureFormatInUse;
  2226. isKTX = true;
  2227. }
  2228. if (scene) {
  2229. scene._addPendingData(texture);
  2230. }
  2231. texture.url = url;
  2232. texture.generateMipMaps = !noMipmap;
  2233. texture.samplingMode = samplingMode;
  2234. texture.invertY = invertY;
  2235. if (!this._doNotHandleContextLost) {
  2236. // Keep a link to the buffer only if we plan to handle context lost
  2237. texture._buffer = buffer;
  2238. }
  2239. if (onLoad) {
  2240. texture.onLoadedObservable.add(onLoad);
  2241. }
  2242. if (!fallBack) this._internalTexturesCache.push(texture);
  2243. var onerror = () => {
  2244. if (scene) {
  2245. scene._removePendingData(texture);
  2246. }
  2247. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  2248. if (isKTX) {
  2249. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2250. } else if (onError) {
  2251. onError();
  2252. }
  2253. };
  2254. var callback: (arrayBuffer: any) => void;
  2255. // processing for non-image formats
  2256. if (isKTX || isTGA || isDDS) {
  2257. if (isKTX) {
  2258. callback = (data) => {
  2259. var ktx = new Internals.KhronosTextureContainer(data, 1);
  2260. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  2261. ktx.uploadLevels(this._gl, !noMipmap);
  2262. return false;
  2263. }, samplingMode);
  2264. };
  2265. } else if (isTGA) {
  2266. callback = (arrayBuffer) => {
  2267. var data = new Uint8Array(arrayBuffer);
  2268. var header = Internals.TGATools.GetTGAHeader(data);
  2269. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  2270. Internals.TGATools.UploadContent(this._gl, data);
  2271. return false;
  2272. }, samplingMode);
  2273. };
  2274. } else if (isDDS) {
  2275. callback = (data) => {
  2276. var info = Internals.DDSTools.GetDDSInfo(data);
  2277. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  2278. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  2279. Internals.DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 1);
  2280. return false;
  2281. }, samplingMode);
  2282. };
  2283. }
  2284. if (!buffer) {
  2285. Tools.LoadFile(url, data => {
  2286. callback(data);
  2287. }, null, scene ? scene.database : null, true, onerror);
  2288. } else {
  2289. callback(buffer);
  2290. }
  2291. // image format processing
  2292. } else {
  2293. var onload = (img) => {
  2294. if (fromBlob && !this._doNotHandleContextLost) {
  2295. // We need to store the image if we need to rebuild the texture
  2296. // in case of a webgl context lost
  2297. texture._buffer = img;
  2298. }
  2299. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2300. let gl = this._gl;
  2301. var isPot = (img.width === potWidth && img.height === potHeight);
  2302. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2303. if (isPot) {
  2304. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2305. return false;
  2306. }
  2307. // Using shaders to rescale because canvas.drawImage is lossy
  2308. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2309. this._bindTextureDirectly(gl.TEXTURE_2D, source);
  2310. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2311. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2312. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2313. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2314. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2315. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2316. this._releaseTexture(source);
  2317. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2318. continuationCallback();
  2319. });
  2320. return true;
  2321. }, samplingMode);
  2322. };
  2323. if (!fromData || isBase64)
  2324. if (buffer instanceof HTMLImageElement) {
  2325. onload(buffer);
  2326. } else {
  2327. Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  2328. }
  2329. else if (buffer instanceof Array || typeof buffer === "string")
  2330. Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  2331. else
  2332. onload(buffer);
  2333. }
  2334. return texture;
  2335. }
  2336. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Scene, internalFormat: number, onComplete: () => void): void {
  2337. let rtt = this.createRenderTargetTexture({
  2338. width: destination.width,
  2339. height: destination.height,
  2340. }, {
  2341. generateMipMaps: false,
  2342. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  2343. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  2344. generateDepthBuffer: false,
  2345. generateStencilBuffer: false
  2346. }
  2347. );
  2348. if (!this._rescalePostProcess) {
  2349. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  2350. }
  2351. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  2352. this._rescalePostProcess.onApply = function (effect) {
  2353. effect._bindTexture("textureSampler", source);
  2354. }
  2355. let hostingScene = scene;
  2356. if (!hostingScene) {
  2357. hostingScene = this.scenes[this.scenes.length - 1];
  2358. }
  2359. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt);
  2360. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination);
  2361. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  2362. this.unBindFramebuffer(rtt);
  2363. this._releaseTexture(rtt);
  2364. if (onComplete) {
  2365. onComplete();
  2366. }
  2367. });
  2368. }
  2369. private _getInternalFormat(format: number): number {
  2370. var internalFormat = this._gl.RGBA;
  2371. switch (format) {
  2372. case Engine.TEXTUREFORMAT_ALPHA:
  2373. internalFormat = this._gl.ALPHA;
  2374. break;
  2375. case Engine.TEXTUREFORMAT_LUMINANCE:
  2376. internalFormat = this._gl.LUMINANCE;
  2377. break;
  2378. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  2379. internalFormat = this._gl.LUMINANCE_ALPHA;
  2380. break;
  2381. case Engine.TEXTUREFORMAT_RGB:
  2382. internalFormat = this._gl.RGB;
  2383. break;
  2384. case Engine.TEXTUREFORMAT_RGBA:
  2385. internalFormat = this._gl.RGBA;
  2386. break;
  2387. }
  2388. return internalFormat;
  2389. }
  2390. public updateRawTexture(texture: InternalTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  2391. var internalFormat = this._getInternalFormat(format);
  2392. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2393. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2394. if (!this._doNotHandleContextLost) {
  2395. texture._bufferView = data;
  2396. texture.format = format;
  2397. texture.invertY = invertY;
  2398. texture._compression = compression;
  2399. }
  2400. if (texture.width % 4 !== 0) {
  2401. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  2402. }
  2403. if (compression) {
  2404. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  2405. } else {
  2406. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  2407. }
  2408. if (texture.generateMipMaps) {
  2409. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2410. }
  2411. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2412. this.resetTextureCache();
  2413. texture.isReady = true;
  2414. }
  2415. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): InternalTexture {
  2416. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  2417. texture.baseWidth = width;
  2418. texture.baseHeight = height;
  2419. texture.width = width;
  2420. texture.height = height;
  2421. texture.format = format;
  2422. texture.generateMipMaps = generateMipMaps;
  2423. texture.samplingMode = samplingMode;
  2424. texture.invertY = invertY;
  2425. texture._compression = compression;
  2426. if (!this._doNotHandleContextLost) {
  2427. texture._bufferView = data;
  2428. }
  2429. this.updateRawTexture(texture, data, format, invertY, compression);
  2430. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2431. // Filters
  2432. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  2433. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2434. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2435. if (generateMipMaps) {
  2436. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2437. }
  2438. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2439. this._internalTexturesCache.push(texture);
  2440. return texture;
  2441. }
  2442. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  2443. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  2444. texture.baseWidth = width;
  2445. texture.baseHeight = height;
  2446. if (generateMipMaps) {
  2447. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  2448. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  2449. }
  2450. this.resetTextureCache();
  2451. texture.width = width;
  2452. texture.height = height;
  2453. texture.isReady = false;
  2454. texture.generateMipMaps = generateMipMaps;
  2455. texture.samplingMode = samplingMode;
  2456. this.updateTextureSamplingMode(samplingMode, texture);
  2457. this._internalTexturesCache.push(texture);
  2458. return texture;
  2459. }
  2460. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  2461. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  2462. if (texture.isCube) {
  2463. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  2464. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2465. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2466. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2467. } else {
  2468. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2469. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2470. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2471. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2472. }
  2473. texture.samplingMode = samplingMode;
  2474. }
  2475. public updateDynamicTexture(texture: InternalTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  2476. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2477. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  2478. if (premulAlpha) {
  2479. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  2480. }
  2481. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2482. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  2483. if (texture.generateMipMaps) {
  2484. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2485. }
  2486. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2487. if (premulAlpha) {
  2488. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2489. }
  2490. this.resetTextureCache();
  2491. texture.isReady = true;
  2492. }
  2493. public updateVideoTexture(texture: InternalTexture, video: HTMLVideoElement, invertY: boolean): void {
  2494. if (texture._isDisabled) {
  2495. return;
  2496. }
  2497. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2498. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  2499. try {
  2500. // Testing video texture support
  2501. if (this._videoTextureSupported === undefined) {
  2502. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2503. if (this._gl.getError() !== 0) {
  2504. this._videoTextureSupported = false;
  2505. } else {
  2506. this._videoTextureSupported = true;
  2507. }
  2508. }
  2509. // Copy video through the current working canvas if video texture is not supported
  2510. if (!this._videoTextureSupported) {
  2511. if (!texture._workingCanvas) {
  2512. texture._workingCanvas = document.createElement("canvas");
  2513. texture._workingContext = texture._workingCanvas.getContext("2d");
  2514. texture._workingCanvas.width = texture.width;
  2515. texture._workingCanvas.height = texture.height;
  2516. }
  2517. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  2518. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  2519. } else {
  2520. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2521. }
  2522. if (texture.generateMipMaps) {
  2523. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2524. }
  2525. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2526. this.resetTextureCache();
  2527. texture.isReady = true;
  2528. } catch (ex) {
  2529. // Something unexpected
  2530. // Let's disable the texture
  2531. texture._isDisabled = true;
  2532. }
  2533. }
  2534. public createRenderTargetTexture(size: any, options: boolean | RenderTargetCreationOptions): InternalTexture {
  2535. let fullOptions = new RenderTargetCreationOptions();
  2536. if (options !== undefined && typeof options === "object") {
  2537. fullOptions.generateMipMaps = options.generateMipMaps;
  2538. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2539. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  2540. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  2541. fullOptions.samplingMode = options.samplingMode === undefined ? Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  2542. } else {
  2543. fullOptions.generateMipMaps = <boolean>options;
  2544. fullOptions.generateDepthBuffer = true;
  2545. fullOptions.generateStencilBuffer = false;
  2546. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2547. fullOptions.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2548. }
  2549. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2550. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2551. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2552. }
  2553. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2554. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2555. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2556. }
  2557. var gl = this._gl;
  2558. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  2559. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2560. var width = size.width || size;
  2561. var height = size.height || size;
  2562. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  2563. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2564. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2565. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2566. }
  2567. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2568. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2569. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2570. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2571. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  2572. // Create the framebuffer
  2573. var framebuffer = gl.createFramebuffer();
  2574. this.bindUnboundFramebuffer(framebuffer);
  2575. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  2576. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  2577. if (fullOptions.generateMipMaps) {
  2578. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2579. }
  2580. // Unbind
  2581. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2582. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2583. this.bindUnboundFramebuffer(null);
  2584. texture._framebuffer = framebuffer;
  2585. texture.baseWidth = width;
  2586. texture.baseHeight = height;
  2587. texture.width = width;
  2588. texture.height = height;
  2589. texture.isReady = true;
  2590. texture.samples = 1;
  2591. texture.generateMipMaps = fullOptions.generateMipMaps;
  2592. texture.samplingMode = fullOptions.samplingMode;
  2593. texture.type = fullOptions.type;
  2594. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  2595. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  2596. this.resetTextureCache();
  2597. this._internalTexturesCache.push(texture);
  2598. return texture;
  2599. }
  2600. public createMultipleRenderTarget(size: any, options): InternalTexture[] {
  2601. var generateMipMaps = false;
  2602. var generateDepthBuffer = true;
  2603. var generateStencilBuffer = false;
  2604. var generateDepthTexture = false;
  2605. var textureCount = 1;
  2606. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  2607. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2608. var types = [], samplingModes = [];
  2609. if (options !== undefined) {
  2610. generateMipMaps = options.generateMipMaps;
  2611. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2612. generateStencilBuffer = options.generateStencilBuffer;
  2613. generateDepthTexture = options.generateDepthTexture;
  2614. textureCount = options.textureCount || 1;
  2615. if (options.types) {
  2616. types = options.types;
  2617. }
  2618. if (options.samplingModes) {
  2619. samplingModes = options.samplingModes;
  2620. }
  2621. }
  2622. var gl = this._gl;
  2623. // Create the framebuffer
  2624. var framebuffer = gl.createFramebuffer();
  2625. this.bindUnboundFramebuffer(framebuffer);
  2626. var width = size.width || size;
  2627. var height = size.height || size;
  2628. var textures = [];
  2629. var attachments = []
  2630. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  2631. for (var i = 0; i < textureCount; i++) {
  2632. var samplingMode = samplingModes[i] || defaultSamplingMode;
  2633. var type = types[i] || defaultType;
  2634. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2635. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2636. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2637. }
  2638. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2639. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2640. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2641. }
  2642. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2643. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2644. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2645. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2646. }
  2647. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  2648. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2649. textures.push(texture);
  2650. attachments.push(attachment);
  2651. gl.activeTexture(gl["TEXTURE" + i]);
  2652. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  2653. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2656. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2657. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2658. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  2659. if (generateMipMaps) {
  2660. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2661. }
  2662. // Unbind
  2663. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2664. texture._framebuffer = framebuffer;
  2665. texture._depthStencilBuffer = depthStencilBuffer;
  2666. texture.baseWidth = width;
  2667. texture.baseHeight = height;
  2668. texture.width = width;
  2669. texture.height = height;
  2670. texture.isReady = true;
  2671. texture.samples = 1;
  2672. texture.generateMipMaps = generateMipMaps;
  2673. texture.samplingMode = samplingMode;
  2674. texture.type = type;
  2675. texture._generateDepthBuffer = generateDepthBuffer;
  2676. texture._generateStencilBuffer = generateStencilBuffer;
  2677. this._internalTexturesCache.push(texture);
  2678. }
  2679. if (generateDepthTexture && this._caps.depthTextureExtension) {
  2680. // Depth texture
  2681. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  2682. gl.activeTexture(gl.TEXTURE0);
  2683. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  2684. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2685. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2686. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2687. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2688. gl.texImage2D(
  2689. gl.TEXTURE_2D,
  2690. 0,
  2691. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  2692. width,
  2693. height,
  2694. 0,
  2695. gl.DEPTH_COMPONENT,
  2696. gl.UNSIGNED_SHORT,
  2697. null
  2698. );
  2699. gl.framebufferTexture2D(
  2700. gl.FRAMEBUFFER,
  2701. gl.DEPTH_ATTACHMENT,
  2702. gl.TEXTURE_2D,
  2703. depthTexture._webGLTexture,
  2704. 0
  2705. );
  2706. depthTexture._framebuffer = framebuffer;
  2707. depthTexture.baseWidth = width;
  2708. depthTexture.baseHeight = height;
  2709. depthTexture.width = width;
  2710. depthTexture.height = height;
  2711. depthTexture.isReady = true;
  2712. depthTexture.samples = 1;
  2713. depthTexture.generateMipMaps = generateMipMaps;
  2714. depthTexture.samplingMode = gl.NEAREST;
  2715. depthTexture._generateDepthBuffer = generateDepthBuffer;
  2716. depthTexture._generateStencilBuffer = generateStencilBuffer;
  2717. textures.push(depthTexture)
  2718. this._internalTexturesCache.push(depthTexture);
  2719. }
  2720. gl.drawBuffers(attachments);
  2721. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2722. this.bindUnboundFramebuffer(null);
  2723. this.resetTextureCache();
  2724. return textures;
  2725. }
  2726. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): WebGLRenderbuffer {
  2727. var depthStencilBuffer: WebGLRenderbuffer = null;
  2728. var gl = this._gl;
  2729. // Create the depth/stencil buffer
  2730. if (generateStencilBuffer) {
  2731. depthStencilBuffer = gl.createRenderbuffer();
  2732. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2733. if (samples > 1) {
  2734. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  2735. } else {
  2736. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  2737. }
  2738. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2739. }
  2740. else if (generateDepthBuffer) {
  2741. depthStencilBuffer = gl.createRenderbuffer();
  2742. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2743. if (samples > 1) {
  2744. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  2745. } else {
  2746. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  2747. }
  2748. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2749. }
  2750. return depthStencilBuffer;
  2751. }
  2752. public updateRenderTargetTextureSampleCount(texture: InternalTexture, samples: number): number {
  2753. if (this.webGLVersion < 2) {
  2754. return 1;
  2755. }
  2756. if (texture.samples === samples) {
  2757. return samples;
  2758. }
  2759. var gl = this._gl;
  2760. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  2761. // Dispose previous render buffers
  2762. if (texture._depthStencilBuffer) {
  2763. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2764. }
  2765. if (texture._MSAAFramebuffer) {
  2766. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2767. }
  2768. if (texture._MSAARenderBuffer) {
  2769. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2770. }
  2771. if (samples > 1) {
  2772. texture._MSAAFramebuffer = gl.createFramebuffer();
  2773. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  2774. var colorRenderbuffer = gl.createRenderbuffer();
  2775. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  2776. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  2777. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  2778. texture._MSAARenderBuffer = colorRenderbuffer;
  2779. } else {
  2780. this.bindUnboundFramebuffer(texture._framebuffer);
  2781. }
  2782. texture.samples = samples;
  2783. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  2784. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2785. this.bindUnboundFramebuffer(null);
  2786. return samples;
  2787. }
  2788. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  2789. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  2790. }
  2791. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  2792. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  2793. }
  2794. public createRenderTargetCubeTexture(size: number, options?: RenderTargetCreationOptions): InternalTexture {
  2795. var gl = this._gl;
  2796. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  2797. var generateMipMaps = true;
  2798. var generateDepthBuffer = true;
  2799. var generateStencilBuffer = false;
  2800. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2801. if (options !== undefined) {
  2802. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  2803. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2804. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2805. if (options.samplingMode !== undefined) {
  2806. samplingMode = options.samplingMode;
  2807. }
  2808. }
  2809. texture.isCube = true;
  2810. texture.generateMipMaps = generateMipMaps;
  2811. texture.samples = 1;
  2812. texture.samplingMode = samplingMode;
  2813. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2814. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2815. for (var face = 0; face < 6; face++) {
  2816. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  2817. }
  2818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  2819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  2820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2822. // Create the framebuffer
  2823. var framebuffer = gl.createFramebuffer();
  2824. this.bindUnboundFramebuffer(framebuffer);
  2825. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  2826. // Mipmaps
  2827. if (texture.generateMipMaps) {
  2828. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2829. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2830. }
  2831. // Unbind
  2832. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2833. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2834. this.bindUnboundFramebuffer(null);
  2835. texture._framebuffer = framebuffer;
  2836. texture.width = size;
  2837. texture.height = size;
  2838. texture.isReady = true;
  2839. this.resetTextureCache();
  2840. this._internalTexturesCache.push(texture);
  2841. return texture;
  2842. }
  2843. public createPrefilteredCubeTexture(rootUrl: string, scene: Scene, scale: number, offset: number, onLoad: (internalTexture: InternalTexture) => void, onError: () => void = null, format?: number, forcedExtension = null): InternalTexture {
  2844. var callback = (loadData) => {
  2845. if (!loadData) {
  2846. if (onLoad) {
  2847. onLoad(null);
  2848. }
  2849. return;
  2850. }
  2851. let texture = loadData.texture as InternalTexture;
  2852. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  2853. texture._lodGenerationScale = scale;
  2854. texture._lodGenerationOffset = offset;
  2855. if (this._caps.textureLOD) {
  2856. // Do not add extra process if texture lod is supported.
  2857. if (onLoad) {
  2858. onLoad(texture);
  2859. }
  2860. return;
  2861. }
  2862. const mipSlices = 3;
  2863. var gl = this._gl;
  2864. const width = loadData.width;
  2865. if (!width) {
  2866. return;
  2867. }
  2868. const textures: BaseTexture[] = [];
  2869. for (let i = 0; i < mipSlices; i++) {
  2870. //compute LOD from even spacing in smoothness (matching shader calculation)
  2871. let smoothness = i / (mipSlices - 1);
  2872. let roughness = 1 - smoothness;
  2873. let minLODIndex = offset; // roughness = 0
  2874. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  2875. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  2876. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  2877. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  2878. glTextureFromLod.isCube = true;
  2879. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  2880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2882. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2883. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2884. if (loadData.isDDS) {
  2885. var info: Internals.DDSInfo = loadData.info;
  2886. var data: any = loadData.data;
  2887. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  2888. Internals.DDSTools.UploadDDSLevels(this, this._gl, data, info, true, 6, mipmapIndex);
  2889. }
  2890. else {
  2891. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  2892. }
  2893. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2894. // Wrap in a base texture for easy binding.
  2895. const lodTexture = new BaseTexture(scene);
  2896. lodTexture.isCube = true;
  2897. lodTexture._texture = glTextureFromLod;
  2898. glTextureFromLod.isReady = true;
  2899. textures.push(lodTexture);
  2900. }
  2901. texture._lodTextureHigh = textures[2];
  2902. texture._lodTextureMid = textures[1];
  2903. texture._lodTextureLow = textures[0];
  2904. if (onLoad) {
  2905. onLoad(texture);
  2906. }
  2907. };
  2908. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  2909. }
  2910. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean, onLoad: (data?: any) => void = null, onError: () => void = null, format?: number, forcedExtension = null): InternalTexture {
  2911. var gl = this._gl;
  2912. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  2913. texture.isCube = true;
  2914. texture.url = rootUrl;
  2915. texture.generateMipMaps = !noMipmap;
  2916. if (!this._doNotHandleContextLost) {
  2917. texture._extension = forcedExtension;
  2918. texture._files = files;
  2919. }
  2920. var isKTX = false;
  2921. var isDDS = false;
  2922. var lastDot = rootUrl.lastIndexOf('.');
  2923. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  2924. if (this._textureFormatInUse) {
  2925. extension = this._textureFormatInUse;
  2926. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  2927. isKTX = true;
  2928. } else {
  2929. isDDS = (extension === ".dds");
  2930. }
  2931. if (isKTX) {
  2932. Tools.LoadFile(rootUrl, data => {
  2933. var ktx = new Internals.KhronosTextureContainer(data, 6);
  2934. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  2935. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2936. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2937. ktx.uploadLevels(this._gl, !noMipmap);
  2938. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2939. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2940. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2941. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2942. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2943. this.resetTextureCache();
  2944. texture.width = ktx.pixelWidth;
  2945. texture.height = ktx.pixelHeight;
  2946. texture.isReady = true;
  2947. }, null, null, true, onError);
  2948. } else if (isDDS) {
  2949. Tools.LoadFile(rootUrl, data => {
  2950. var info = Internals.DDSTools.GetDDSInfo(data);
  2951. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  2952. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2953. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  2954. Internals.DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6);
  2955. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  2956. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2957. }
  2958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2960. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2961. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2962. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2963. this.resetTextureCache();
  2964. texture.width = info.width;
  2965. texture.height = info.height;
  2966. texture.isReady = true;
  2967. texture.type = info.textureType;
  2968. if (onLoad) {
  2969. onLoad({ isDDS: true, width: info.width, info, data, texture });
  2970. }
  2971. }, null, null, true, onError);
  2972. } else {
  2973. cascadeLoad(rootUrl, scene, imgs => {
  2974. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  2975. var height = width;
  2976. this._prepareWorkingCanvas();
  2977. this._workingCanvas.width = width;
  2978. this._workingCanvas.height = height;
  2979. var faces = [
  2980. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2981. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2982. ];
  2983. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2984. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2985. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2986. for (var index = 0; index < faces.length; index++) {
  2987. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  2988. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2989. }
  2990. if (!noMipmap) {
  2991. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2992. }
  2993. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2994. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2995. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2997. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2998. this.resetTextureCache();
  2999. texture.width = width;
  3000. texture.height = height;
  3001. texture.isReady = true;
  3002. texture.format = format;
  3003. texture.onLoadedObservable.notifyObservers(texture);
  3004. texture.onLoadedObservable.clear();
  3005. if (onLoad) {
  3006. onLoad();
  3007. }
  3008. }, files, onError);
  3009. }
  3010. this._internalTexturesCache.push(texture);
  3011. return texture;
  3012. }
  3013. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: string = null, level = 0): void {
  3014. texture._bufferViewArray = data;
  3015. texture.format = format;
  3016. texture.type = type;
  3017. texture.invertY = invertY;
  3018. texture._compression = compression;
  3019. var gl = this._gl;
  3020. var textureType = this._getWebGLTextureType(type);
  3021. var internalFormat = this._getInternalFormat(format);
  3022. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3023. var needConversion = false;
  3024. if (internalFormat === gl.RGB) {
  3025. internalFormat = gl.RGBA;
  3026. needConversion = true;
  3027. }
  3028. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  3029. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3030. if (texture.width % 4 !== 0) {
  3031. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  3032. }
  3033. // Data are known to be in +X +Y +Z -X -Y -Z
  3034. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  3035. let faceData = data[faceIndex];
  3036. if (compression) {
  3037. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  3038. } else {
  3039. if (needConversion) {
  3040. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  3041. }
  3042. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  3043. }
  3044. }
  3045. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3046. if (isPot && texture.generateMipMaps && level === 0) {
  3047. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3048. }
  3049. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3050. this.resetTextureCache();
  3051. texture.isReady = true;
  3052. }
  3053. public createRawCubeTexture(data: ArrayBufferView[], size: number, format: number, type: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): InternalTexture {
  3054. var gl = this._gl;
  3055. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  3056. texture.isCube = true;
  3057. texture.generateMipMaps = generateMipMaps;
  3058. texture.format = format;
  3059. texture.type = type;
  3060. if (!this._doNotHandleContextLost) {
  3061. texture._bufferViewArray = data;
  3062. }
  3063. var textureType = this._getWebGLTextureType(type);
  3064. var internalFormat = this._getInternalFormat(format);
  3065. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3066. var needConversion = false;
  3067. if (internalFormat === gl.RGB) {
  3068. internalFormat = gl.RGBA;
  3069. needConversion = true;
  3070. }
  3071. var width = size;
  3072. var height = width;
  3073. texture.width = width;
  3074. texture.height = height;
  3075. // Double check on POT to generate Mips.
  3076. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  3077. if (!isPot) {
  3078. generateMipMaps = false;
  3079. }
  3080. // Upload data if needed. The texture won't be ready until then.
  3081. if (data) {
  3082. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  3083. }
  3084. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  3085. // Filters
  3086. if (data && generateMipMaps) {
  3087. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  3088. }
  3089. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  3090. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3091. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3092. }
  3093. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  3094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3096. }
  3097. else {
  3098. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  3099. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  3100. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  3101. }
  3102. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3103. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3104. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3105. return texture;
  3106. }
  3107. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  3108. callback: (ArrayBuffer: ArrayBuffer) => ArrayBufferView[],
  3109. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][]),
  3110. onLoad: () => void = null,
  3111. onError: () => void = null,
  3112. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  3113. invertY = false): InternalTexture {
  3114. var gl = this._gl;
  3115. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  3116. scene._addPendingData(texture);
  3117. texture.url = url;
  3118. this._internalTexturesCache.push(texture);
  3119. var onerror = () => {
  3120. scene._removePendingData(texture);
  3121. if (onError) {
  3122. onError();
  3123. }
  3124. };
  3125. var internalCallback = (data) => {
  3126. var width = texture.width;
  3127. var height = texture.height;
  3128. var faceDataArrays = callback(data);
  3129. if (mipmmapGenerator) {
  3130. var textureType = this._getWebGLTextureType(type);
  3131. var internalFormat = this._getInternalFormat(format);
  3132. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  3133. var needConversion = false;
  3134. if (internalFormat === gl.RGB) {
  3135. internalFormat = gl.RGBA;
  3136. needConversion = true;
  3137. }
  3138. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  3139. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  3140. var mipData = mipmmapGenerator(faceDataArrays);
  3141. for (var level = 0; level < mipData.length; level++) {
  3142. var mipSize = width >> level;
  3143. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  3144. let mipFaceData = mipData[level][faceIndex];
  3145. if (needConversion) {
  3146. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  3147. }
  3148. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  3149. }
  3150. }
  3151. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  3152. }
  3153. else {
  3154. texture.generateMipMaps = !noMipmap;
  3155. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  3156. }
  3157. texture.isReady = true;
  3158. this.resetTextureCache();
  3159. scene._removePendingData(texture);
  3160. if (onLoad) {
  3161. onLoad();
  3162. }
  3163. };
  3164. Tools.LoadFile(url, data => {
  3165. internalCallback(data);
  3166. }, onerror, scene.database, true);
  3167. return texture;
  3168. };
  3169. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Scene, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  3170. var gl = this._gl;
  3171. if (!gl) {
  3172. return;
  3173. }
  3174. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3177. if (!noMipmap && !isCompressed) {
  3178. gl.generateMipmap(gl.TEXTURE_2D);
  3179. }
  3180. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3181. this.resetTextureCache();
  3182. if (scene) {
  3183. scene._removePendingData(texture);
  3184. }
  3185. texture.onLoadedObservable.notifyObservers(texture);
  3186. texture.onLoadedObservable.clear();
  3187. }
  3188. private _prepareWebGLTexture(texture: InternalTexture, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  3189. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  3190. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  3191. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  3192. var gl = this._gl;
  3193. if (!gl) {
  3194. return;
  3195. }
  3196. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  3197. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3198. texture.baseWidth = width;
  3199. texture.baseHeight = height;
  3200. texture.width = potWidth;
  3201. texture.height = potHeight;
  3202. texture.isReady = true;
  3203. if (processFunction(potWidth, potHeight, () => {
  3204. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3205. })) {
  3206. // Returning as texture needs extra async steps
  3207. return;
  3208. }
  3209. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3210. }
  3211. private _convertRGBtoRGBATextureData(rgbData: ArrayBufferView, width: number, height: number, textureType: number): ArrayBufferView {
  3212. // Create new RGBA data container.
  3213. var rgbaData: ArrayBufferView;
  3214. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  3215. rgbaData = new Float32Array(width * height * 4);
  3216. }
  3217. else {
  3218. rgbaData = new Uint32Array(width * height * 4);
  3219. }
  3220. // Convert each pixel.
  3221. for (let x = 0; x < width; x++) {
  3222. for (let y = 0; y < height; y++) {
  3223. let index = (y * width + x) * 3;
  3224. let newIndex = (y * width + x) * 4;
  3225. // Map Old Value to new value.
  3226. rgbaData[newIndex + 0] = rgbData[index + 0];
  3227. rgbaData[newIndex + 1] = rgbData[index + 1];
  3228. rgbaData[newIndex + 2] = rgbData[index + 2];
  3229. // Add fully opaque alpha channel.
  3230. rgbaData[newIndex + 3] = 1;
  3231. }
  3232. }
  3233. return rgbaData;
  3234. }
  3235. public _releaseFramebufferObjects(texture: InternalTexture): void {
  3236. var gl = this._gl;
  3237. if (texture._framebuffer) {
  3238. gl.deleteFramebuffer(texture._framebuffer);
  3239. texture._framebuffer = null;
  3240. }
  3241. if (texture._depthStencilBuffer) {
  3242. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3243. texture._depthStencilBuffer = null;
  3244. }
  3245. if (texture._MSAAFramebuffer) {
  3246. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3247. texture._MSAAFramebuffer = null;
  3248. }
  3249. if (texture._MSAARenderBuffer) {
  3250. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3251. texture._MSAARenderBuffer = null;
  3252. }
  3253. }
  3254. public _releaseTexture(texture: InternalTexture): void {
  3255. var gl = this._gl;
  3256. this._releaseFramebufferObjects(texture);
  3257. gl.deleteTexture(texture._webGLTexture);
  3258. // Unbind channels
  3259. this.unbindAllTextures();
  3260. var index = this._internalTexturesCache.indexOf(texture);
  3261. if (index !== -1) {
  3262. this._internalTexturesCache.splice(index, 1);
  3263. }
  3264. // Integrated fixed lod samplers.
  3265. if (texture._lodTextureHigh) {
  3266. texture._lodTextureHigh.dispose();
  3267. }
  3268. if (texture._lodTextureMid) {
  3269. texture._lodTextureMid.dispose();
  3270. }
  3271. if (texture._lodTextureLow) {
  3272. texture._lodTextureLow.dispose();
  3273. }
  3274. }
  3275. private setProgram(program: WebGLProgram): void {
  3276. if (this._currentProgram !== program) {
  3277. this._gl.useProgram(program);
  3278. this._currentProgram = program;
  3279. }
  3280. }
  3281. public bindSamplers(effect: Effect): void {
  3282. this.setProgram(effect.getProgram());
  3283. var samplers = effect.getSamplers();
  3284. for (var index = 0; index < samplers.length; index++) {
  3285. var uniform = effect.getUniform(samplers[index]);
  3286. this._gl.uniform1i(uniform, index);
  3287. }
  3288. this._currentEffect = null;
  3289. }
  3290. private activateTexture(texture: number): void {
  3291. if (this._activeTexture !== texture) {
  3292. this._gl.activeTexture(texture);
  3293. this._activeTexture = texture;
  3294. }
  3295. }
  3296. public _bindTextureDirectly(target: number, texture: InternalTexture): void {
  3297. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  3298. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  3299. this._activeTexturesCache[this._activeTexture] = texture;
  3300. }
  3301. }
  3302. public _bindTexture(channel: number, texture: InternalTexture): void {
  3303. if (channel < 0) {
  3304. return;
  3305. }
  3306. this.activateTexture(this._gl.TEXTURE0 + channel);
  3307. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  3308. }
  3309. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  3310. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3311. }
  3312. public unbindAllTextures(): void {
  3313. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3314. this.activateTexture(this._gl["TEXTURE" + channel]);
  3315. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3316. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3317. }
  3318. }
  3319. public setTexture(channel: number, uniform: WebGLUniformLocation, texture: BaseTexture): void {
  3320. if (channel < 0) {
  3321. return;
  3322. }
  3323. this._gl.uniform1i(uniform, channel);
  3324. this._setTexture(channel, texture);
  3325. }
  3326. private _setTexture(channel: number, texture: BaseTexture): void {
  3327. // Not ready?
  3328. if (!texture) {
  3329. if (this._activeTexturesCache[channel] != null) {
  3330. this.activateTexture(this._gl["TEXTURE" + channel]);
  3331. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3332. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3333. }
  3334. return;
  3335. }
  3336. // Video
  3337. var alreadyActivated = false;
  3338. if ((<VideoTexture>texture).video) {
  3339. this.activateTexture(this._gl["TEXTURE" + channel]);
  3340. alreadyActivated = true;
  3341. (<VideoTexture>texture).update();
  3342. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  3343. texture.delayLoad();
  3344. return;
  3345. }
  3346. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  3347. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  3348. if (this._activeTexturesCache[channel] === internalTexture) {
  3349. return;
  3350. }
  3351. if (!alreadyActivated) {
  3352. this.activateTexture(this._gl["TEXTURE" + channel]);
  3353. }
  3354. if (internalTexture.isCube) {
  3355. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3356. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3357. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3358. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  3359. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3360. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3361. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3362. }
  3363. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3364. } else {
  3365. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  3366. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3367. internalTexture._cachedWrapU = texture.wrapU;
  3368. switch (texture.wrapU) {
  3369. case Texture.WRAP_ADDRESSMODE:
  3370. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3371. break;
  3372. case Texture.CLAMP_ADDRESSMODE:
  3373. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3374. break;
  3375. case Texture.MIRROR_ADDRESSMODE:
  3376. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3377. break;
  3378. }
  3379. }
  3380. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3381. internalTexture._cachedWrapV = texture.wrapV;
  3382. switch (texture.wrapV) {
  3383. case Texture.WRAP_ADDRESSMODE:
  3384. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3385. break;
  3386. case Texture.CLAMP_ADDRESSMODE:
  3387. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3388. break;
  3389. case Texture.MIRROR_ADDRESSMODE:
  3390. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3391. break;
  3392. }
  3393. }
  3394. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3395. }
  3396. }
  3397. public setTextureArray(channel: number, uniform: WebGLUniformLocation, textures: BaseTexture[]): void {
  3398. if (channel < 0) {
  3399. return;
  3400. }
  3401. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  3402. this._textureUnits = new Int32Array(textures.length);
  3403. }
  3404. for (let i = 0; i < textures.length; i++) {
  3405. this._textureUnits[i] = channel + i;
  3406. }
  3407. this._gl.uniform1iv(uniform, this._textureUnits);
  3408. for (var index = 0; index < textures.length; index++) {
  3409. this._setTexture(channel + index, textures[index]);
  3410. }
  3411. }
  3412. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  3413. var internalTexture = texture.getInternalTexture();
  3414. if (!internalTexture) {
  3415. return;
  3416. }
  3417. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3418. var value = texture.anisotropicFilteringLevel;
  3419. if (internalTexture.samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  3420. value = 1;
  3421. }
  3422. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  3423. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  3424. internalTexture._cachedAnisotropicFilteringLevel = value;
  3425. }
  3426. }
  3427. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  3428. var data = new Uint8Array(height * width * 4);
  3429. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3430. return data;
  3431. }
  3432. /**
  3433. * Add an externaly attached data from its key.
  3434. * This method call will fail and return false, if such key already exists.
  3435. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3436. * @param key the unique key that identifies the data
  3437. * @param data the data object to associate to the key for this Engine instance
  3438. * @return true if no such key were already present and the data was added successfully, false otherwise
  3439. */
  3440. public addExternalData<T>(key: string, data: T): boolean {
  3441. if (!this._externalData) {
  3442. this._externalData = new StringDictionary<Object>();
  3443. }
  3444. return this._externalData.add(key, data);
  3445. }
  3446. /**
  3447. * Get an externaly attached data from its key
  3448. * @param key the unique key that identifies the data
  3449. * @return the associated data, if present (can be null), or undefined if not present
  3450. */
  3451. public getExternalData<T>(key: string): T {
  3452. if (!this._externalData) {
  3453. this._externalData = new StringDictionary<Object>();
  3454. }
  3455. return <T>this._externalData.get(key);
  3456. }
  3457. /**
  3458. * Get an externaly attached data from its key, create it using a factory if it's not already present
  3459. * @param key the unique key that identifies the data
  3460. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3461. * @return the associated data, can be null if the factory returned null.
  3462. */
  3463. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  3464. if (!this._externalData) {
  3465. this._externalData = new StringDictionary<Object>();
  3466. }
  3467. return <T>this._externalData.getOrAddWithFactory(key, factory);
  3468. }
  3469. /**
  3470. * Remove an externaly attached data from the Engine instance
  3471. * @param key the unique key that identifies the data
  3472. * @return true if the data was successfully removed, false if it doesn't exist
  3473. */
  3474. public removeExternalData(key): boolean {
  3475. if (!this._externalData) {
  3476. this._externalData = new StringDictionary<Object>();
  3477. }
  3478. return this._externalData.remove(key);
  3479. }
  3480. public unbindAllAttributes() {
  3481. if (this._mustWipeVertexAttributes) {
  3482. this._mustWipeVertexAttributes = false;
  3483. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  3484. this._gl.disableVertexAttribArray(i);
  3485. this._vertexAttribArraysEnabled[i] = false;
  3486. this._currentBufferPointers[i].active = false;
  3487. }
  3488. return;
  3489. }
  3490. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  3491. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  3492. continue;
  3493. }
  3494. this._gl.disableVertexAttribArray(i);
  3495. this._vertexAttribArraysEnabled[i] = false;
  3496. this._currentBufferPointers[i].active = false;
  3497. }
  3498. }
  3499. public releaseEffects() {
  3500. for (var name in this._compiledEffects) {
  3501. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3502. }
  3503. this._compiledEffects = {};
  3504. }
  3505. // Dispose
  3506. public dispose(): void {
  3507. this.hideLoadingUI();
  3508. this.stopRenderLoop();
  3509. // Release postProcesses
  3510. while (this.postProcesses.length) {
  3511. this.postProcesses[0].dispose();
  3512. }
  3513. // Empty texture
  3514. if (this._emptyTexture) {
  3515. this._releaseTexture(this._emptyTexture);
  3516. this._emptyTexture = null;
  3517. }
  3518. if (this._emptyCubeTexture) {
  3519. this._releaseTexture(this._emptyCubeTexture);
  3520. this._emptyCubeTexture = null;
  3521. }
  3522. // Rescale PP
  3523. if (this._rescalePostProcess) {
  3524. this._rescalePostProcess.dispose();
  3525. }
  3526. // Release scenes
  3527. while (this.scenes.length) {
  3528. this.scenes[0].dispose();
  3529. }
  3530. // Release audio engine
  3531. if (Engine.audioEngine) {
  3532. Engine.audioEngine.dispose();
  3533. }
  3534. // Release effects
  3535. this.releaseEffects();
  3536. // Unbind
  3537. this.unbindAllAttributes();
  3538. if (this._dummyFramebuffer) {
  3539. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  3540. }
  3541. this._gl = null;
  3542. //WebVR
  3543. this.disableVR();
  3544. // Events
  3545. window.removeEventListener("blur", this._onBlur);
  3546. window.removeEventListener("focus", this._onFocus);
  3547. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  3548. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  3549. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  3550. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  3551. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  3552. if (!this._doNotHandleContextLost) {
  3553. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  3554. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  3555. }
  3556. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3557. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3558. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3559. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3560. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3561. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3562. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3563. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3564. // Remove from Instances
  3565. var index = Engine.Instances.indexOf(this);
  3566. if (index >= 0) {
  3567. Engine.Instances.splice(index, 1);
  3568. }
  3569. this._workingCanvas = null;
  3570. this._workingContext = null;
  3571. this._currentBufferPointers = null;
  3572. this._renderingCanvas = null;
  3573. this._currentProgram = null;
  3574. this.onResizeObservable.clear();
  3575. this.onCanvasBlurObservable.clear();
  3576. this.onCanvasFocusObservable.clear();
  3577. this.onCanvasPointerOutObservable.clear();
  3578. BABYLON.Effect.ResetCache();
  3579. }
  3580. // Loading screen
  3581. public displayLoadingUI(): void {
  3582. const loadingScreen = this.loadingScreen;
  3583. if (loadingScreen) {
  3584. loadingScreen.displayLoadingUI();
  3585. }
  3586. }
  3587. public hideLoadingUI(): void {
  3588. const loadingScreen = this.loadingScreen;
  3589. if (loadingScreen) {
  3590. loadingScreen.hideLoadingUI();
  3591. }
  3592. }
  3593. public get loadingScreen(): ILoadingScreen {
  3594. if (!this._loadingScreen && DefaultLoadingScreen)
  3595. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  3596. return this._loadingScreen;
  3597. }
  3598. public set loadingScreen(loadingScreen: ILoadingScreen) {
  3599. this._loadingScreen = loadingScreen;
  3600. }
  3601. public set loadingUIText(text: string) {
  3602. this.loadingScreen.loadingUIText = text;
  3603. }
  3604. public set loadingUIBackgroundColor(color: string) {
  3605. this.loadingScreen.loadingUIBackgroundColor = color;
  3606. }
  3607. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3608. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  3609. }
  3610. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3611. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  3612. }
  3613. public getVertexShaderSource(program: WebGLProgram): string {
  3614. var shaders = this._gl.getAttachedShaders(program);
  3615. return this._gl.getShaderSource(shaders[0]);
  3616. }
  3617. public getFragmentShaderSource(program: WebGLProgram): string {
  3618. var shaders = this._gl.getAttachedShaders(program);
  3619. return this._gl.getShaderSource(shaders[1]);
  3620. }
  3621. public getError(): number {
  3622. return this._gl.getError();
  3623. }
  3624. // FPS
  3625. public getFps(): number {
  3626. return this._fps;
  3627. }
  3628. public getDeltaTime(): number {
  3629. return this._deltaTime;
  3630. }
  3631. private _measureFps(): void {
  3632. this._performanceMonitor.sampleFrame();
  3633. this._fps = this._performanceMonitor.averageFPS;
  3634. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  3635. }
  3636. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  3637. let gl = this._gl;
  3638. if (!this._dummyFramebuffer) {
  3639. this._dummyFramebuffer = gl.createFramebuffer();
  3640. }
  3641. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  3642. if (faceIndex > -1) {
  3643. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  3644. } else {
  3645. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  3646. }
  3647. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  3648. let buffer: ArrayBufferView;
  3649. switch (readType) {
  3650. case gl.UNSIGNED_BYTE:
  3651. buffer = new Uint8Array(4 * width * height);
  3652. readType = gl.UNSIGNED_BYTE;
  3653. break;
  3654. default:
  3655. buffer = new Float32Array(4 * width * height);
  3656. readType = gl.FLOAT;
  3657. break;
  3658. }
  3659. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  3660. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  3661. return buffer;
  3662. }
  3663. private _canRenderToFloatFramebuffer(): boolean {
  3664. if (this._webGLVersion > 1) {
  3665. return this._caps.colorBufferFloat;
  3666. }
  3667. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  3668. }
  3669. private _canRenderToHalfFloatFramebuffer(): boolean {
  3670. if (this._webGLVersion > 1) {
  3671. return this._caps.colorBufferFloat;
  3672. }
  3673. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  3674. }
  3675. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  3676. private _canRenderToFramebuffer(type: number): boolean {
  3677. let gl = this._gl;
  3678. //clear existing errors
  3679. while (gl.getError() !== gl.NO_ERROR) { }
  3680. let successful = true;
  3681. let texture = gl.createTexture();
  3682. gl.bindTexture(gl.TEXTURE_2D, texture);
  3683. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3684. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3685. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3686. let fb = gl.createFramebuffer();
  3687. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  3688. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3689. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  3690. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  3691. successful = successful && (gl.getError() === gl.NO_ERROR);
  3692. //try render by clearing frame buffer's color buffer
  3693. if (successful) {
  3694. gl.clear(gl.COLOR_BUFFER_BIT);
  3695. successful = successful && (gl.getError() === gl.NO_ERROR);
  3696. }
  3697. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  3698. if (successful) {
  3699. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  3700. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3701. let readFormat = gl.RGBA;
  3702. let readType = gl.UNSIGNED_BYTE;
  3703. let buffer = new Uint8Array(4);
  3704. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  3705. successful = successful && (gl.getError() === gl.NO_ERROR);
  3706. }
  3707. //clean up
  3708. gl.deleteTexture(texture);
  3709. gl.deleteFramebuffer(fb);
  3710. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3711. //clear accumulated errors
  3712. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  3713. return successful;
  3714. }
  3715. public _getWebGLTextureType(type: number): number {
  3716. if (type === Engine.TEXTURETYPE_FLOAT) {
  3717. return this._gl.FLOAT;
  3718. }
  3719. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  3720. // Add Half Float Constant.
  3721. return this._gl.HALF_FLOAT_OES;
  3722. }
  3723. return this._gl.UNSIGNED_BYTE;
  3724. };
  3725. public _getRGBABufferInternalSizedFormat(type: number): number {
  3726. if (this._webGLVersion === 1) {
  3727. return this._gl.RGBA;
  3728. }
  3729. if (type === Engine.TEXTURETYPE_FLOAT) {
  3730. return this._gl.RGBA32F;
  3731. }
  3732. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  3733. return this._gl.RGBA16F;
  3734. }
  3735. return this._gl.RGBA;
  3736. };
  3737. public createQuery(): WebGLQuery {
  3738. return this._gl.createQuery();
  3739. }
  3740. public deleteQuery(query: WebGLQuery): Engine {
  3741. this._gl.deleteQuery(query);
  3742. return this;
  3743. }
  3744. public isQueryResultAvailable(query: WebGLQuery): boolean {
  3745. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE) as boolean;
  3746. }
  3747. public getQueryResult(query: WebGLQuery): number {
  3748. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT) as number;
  3749. }
  3750. public beginQuery(algorithmType: number, query: WebGLQuery) {
  3751. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  3752. this._gl.beginQuery(glAlgorithm, query);
  3753. }
  3754. public endQuery(algorithmType: number): Engine {
  3755. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  3756. this._gl.endQuery(glAlgorithm);
  3757. return this;
  3758. }
  3759. private getGlAlgorithmType(algorithmType: number): number {
  3760. return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  3761. }
  3762. // Statics
  3763. public static isSupported(): boolean {
  3764. try {
  3765. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  3766. if (navigator.isCocoonJS) {
  3767. return true;
  3768. }
  3769. var tempcanvas = document.createElement("canvas");
  3770. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3771. return gl != null && !!window.WebGLRenderingContext;
  3772. } catch (e) {
  3773. return false;
  3774. }
  3775. }
  3776. }
  3777. }