WebGLTextures.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  1. import { LinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, RGBFormat, RGBAFormat, DepthFormat, DepthStencilFormat, UnsignedShortType, UnsignedIntType, UnsignedInt248Type, FloatType, HalfFloatType, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping } from '../../constants.js';
  2. import { MathUtils } from '../../math/MathUtils.js';
  3. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  4. const isWebGL2 = capabilities.isWebGL2;
  5. const maxTextures = capabilities.maxTextures;
  6. const maxCubemapSize = capabilities.maxCubemapSize;
  7. const maxTextureSize = capabilities.maxTextureSize;
  8. const maxSamples = capabilities.maxSamples;
  9. const _videoTextures = new WeakMap();
  10. let _canvas;
  11. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14. let useOffscreenCanvas = false;
  15. try {
  16. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  17. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  18. } catch ( err ) {
  19. // Ignore any errors
  20. }
  21. function createCanvas( width, height ) {
  22. // Use OffscreenCanvas when available. Specially needed in web workers
  23. return useOffscreenCanvas ?
  24. new OffscreenCanvas( width, height ) :
  25. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  26. }
  27. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  28. let scale = 1;
  29. // handle case if texture exceeds max size
  30. if ( image.width > maxSize || image.height > maxSize ) {
  31. scale = maxSize / Math.max( image.width, image.height );
  32. }
  33. // only perform resize if necessary
  34. if ( scale < 1 || needsPowerOfTwo === true ) {
  35. // only perform resize for certain image types
  36. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  37. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  38. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  39. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  40. const width = floor( scale * image.width );
  41. const height = floor( scale * image.height );
  42. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  43. // cube textures can't reuse the same canvas
  44. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  45. canvas.width = width;
  46. canvas.height = height;
  47. const context = canvas.getContext( '2d' );
  48. context.drawImage( image, 0, 0, width, height );
  49. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  50. return canvas;
  51. } else {
  52. if ( 'data' in image ) {
  53. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  54. }
  55. return image;
  56. }
  57. }
  58. return image;
  59. }
  60. function isPowerOfTwo( image ) {
  61. return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
  62. }
  63. function textureNeedsPowerOfTwo( texture ) {
  64. if ( isWebGL2 ) return false;
  65. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  66. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  67. }
  68. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  69. return texture.generateMipmaps && supportsMips &&
  70. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  71. }
  72. function generateMipmap( target, texture, width, height ) {
  73. _gl.generateMipmap( target );
  74. const textureProperties = properties.get( texture );
  75. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  76. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  77. }
  78. function getInternalFormat( internalFormatName, glFormat, glType ) {
  79. if ( isWebGL2 === false ) return glFormat;
  80. if ( internalFormatName !== null ) {
  81. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  82. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  83. }
  84. let internalFormat = glFormat;
  85. if ( glFormat === _gl.RED ) {
  86. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  87. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  88. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  89. }
  90. if ( glFormat === _gl.RGB ) {
  91. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGB32F;
  92. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGB16F;
  93. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8;
  94. }
  95. if ( glFormat === _gl.RGBA ) {
  96. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  97. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  98. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8;
  99. }
  100. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  101. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  102. extensions.get( 'EXT_color_buffer_float' );
  103. }
  104. return internalFormat;
  105. }
  106. // Fallback filters for non-power-of-2 textures
  107. function filterFallback( f ) {
  108. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  109. return _gl.NEAREST;
  110. }
  111. return _gl.LINEAR;
  112. }
  113. //
  114. function onTextureDispose( event ) {
  115. const texture = event.target;
  116. texture.removeEventListener( 'dispose', onTextureDispose );
  117. deallocateTexture( texture );
  118. if ( texture.isVideoTexture ) {
  119. _videoTextures.delete( texture );
  120. }
  121. info.memory.textures --;
  122. }
  123. function onRenderTargetDispose( event ) {
  124. const renderTarget = event.target;
  125. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  126. deallocateRenderTarget( renderTarget );
  127. info.memory.textures --;
  128. }
  129. //
  130. function deallocateTexture( texture ) {
  131. const textureProperties = properties.get( texture );
  132. if ( textureProperties.__webglInit === undefined ) return;
  133. _gl.deleteTexture( textureProperties.__webglTexture );
  134. properties.remove( texture );
  135. }
  136. function deallocateRenderTarget( renderTarget ) {
  137. const renderTargetProperties = properties.get( renderTarget );
  138. const textureProperties = properties.get( renderTarget.texture );
  139. if ( ! renderTarget ) return;
  140. if ( textureProperties.__webglTexture !== undefined ) {
  141. _gl.deleteTexture( textureProperties.__webglTexture );
  142. }
  143. if ( renderTarget.depthTexture ) {
  144. renderTarget.depthTexture.dispose();
  145. }
  146. if ( renderTarget.isWebGLCubeRenderTarget ) {
  147. for ( let i = 0; i < 6; i ++ ) {
  148. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  149. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  150. }
  151. } else {
  152. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  153. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  154. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  155. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  156. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  157. }
  158. properties.remove( renderTarget.texture );
  159. properties.remove( renderTarget );
  160. }
  161. //
  162. let textureUnits = 0;
  163. function resetTextureUnits() {
  164. textureUnits = 0;
  165. }
  166. function allocateTextureUnit() {
  167. const textureUnit = textureUnits;
  168. if ( textureUnit >= maxTextures ) {
  169. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  170. }
  171. textureUnits += 1;
  172. return textureUnit;
  173. }
  174. //
  175. function setTexture2D( texture, slot ) {
  176. const textureProperties = properties.get( texture );
  177. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  178. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  179. const image = texture.image;
  180. if ( image === undefined ) {
  181. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  182. } else if ( image.complete === false ) {
  183. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  184. } else {
  185. uploadTexture( textureProperties, texture, slot );
  186. return;
  187. }
  188. }
  189. state.activeTexture( _gl.TEXTURE0 + slot );
  190. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  191. }
  192. function setTexture2DArray( texture, slot ) {
  193. const textureProperties = properties.get( texture );
  194. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  195. uploadTexture( textureProperties, texture, slot );
  196. return;
  197. }
  198. state.activeTexture( _gl.TEXTURE0 + slot );
  199. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture );
  200. }
  201. function setTexture3D( texture, slot ) {
  202. const textureProperties = properties.get( texture );
  203. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  204. uploadTexture( textureProperties, texture, slot );
  205. return;
  206. }
  207. state.activeTexture( _gl.TEXTURE0 + slot );
  208. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture );
  209. }
  210. function setTextureCube( texture, slot ) {
  211. const textureProperties = properties.get( texture );
  212. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  213. uploadCubeTexture( textureProperties, texture, slot );
  214. return;
  215. }
  216. state.activeTexture( _gl.TEXTURE0 + slot );
  217. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  218. }
  219. const wrappingToGL = {
  220. [ RepeatWrapping ]: _gl.REPEAT,
  221. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  222. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  223. };
  224. const filterToGL = {
  225. [ NearestFilter ]: _gl.NEAREST,
  226. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  227. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  228. [ LinearFilter ]: _gl.LINEAR,
  229. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  230. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  231. };
  232. function setTextureParameters( textureType, texture, supportsMips ) {
  233. if ( supportsMips ) {
  234. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  235. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  236. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  237. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  238. }
  239. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  240. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  241. } else {
  242. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  243. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  244. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  245. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  246. }
  247. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  248. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  249. }
  250. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  251. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  252. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  253. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  254. }
  255. }
  256. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  257. if ( extension ) {
  258. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  259. if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  260. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  261. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  262. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  263. }
  264. }
  265. }
  266. function initTexture( textureProperties, texture ) {
  267. if ( textureProperties.__webglInit === undefined ) {
  268. textureProperties.__webglInit = true;
  269. texture.addEventListener( 'dispose', onTextureDispose );
  270. textureProperties.__webglTexture = _gl.createTexture();
  271. info.memory.textures ++;
  272. }
  273. }
  274. function uploadTexture( textureProperties, texture, slot ) {
  275. let textureType = _gl.TEXTURE_2D;
  276. if ( texture.isDataTexture2DArray ) textureType = _gl.TEXTURE_2D_ARRAY;
  277. if ( texture.isDataTexture3D ) textureType = _gl.TEXTURE_3D;
  278. initTexture( textureProperties, texture );
  279. state.activeTexture( _gl.TEXTURE0 + slot );
  280. state.bindTexture( textureType, textureProperties.__webglTexture );
  281. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  282. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  283. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  284. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  285. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  286. const supportsMips = isPowerOfTwo( image ) || isWebGL2,
  287. glFormat = utils.convert( texture.format );
  288. let glType = utils.convert( texture.type ),
  289. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  290. setTextureParameters( textureType, texture, supportsMips );
  291. let mipmap;
  292. const mipmaps = texture.mipmaps;
  293. if ( texture.isDepthTexture ) {
  294. // populate depth texture with dummy data
  295. glInternalFormat = _gl.DEPTH_COMPONENT;
  296. if ( isWebGL2 ) {
  297. if ( texture.type === FloatType ) {
  298. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  299. } else if ( texture.type === UnsignedIntType ) {
  300. glInternalFormat = _gl.DEPTH_COMPONENT24;
  301. } else if ( texture.type === UnsignedInt248Type ) {
  302. glInternalFormat = _gl.DEPTH24_STENCIL8;
  303. } else {
  304. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  305. }
  306. } else {
  307. if ( texture.type === FloatType ) {
  308. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  309. }
  310. }
  311. // validation checks for WebGL 1
  312. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  313. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  314. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  315. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  316. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  317. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  318. texture.type = UnsignedShortType;
  319. glType = utils.convert( texture.type );
  320. }
  321. }
  322. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  323. // Depth stencil textures need the DEPTH_STENCIL internal format
  324. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  325. glInternalFormat = _gl.DEPTH_STENCIL;
  326. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  327. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  328. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  329. if ( texture.type !== UnsignedInt248Type ) {
  330. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  331. texture.type = UnsignedInt248Type;
  332. glType = utils.convert( texture.type );
  333. }
  334. }
  335. //
  336. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  337. } else if ( texture.isDataTexture ) {
  338. // use manually created mipmaps if available
  339. // if there are no manual mipmaps
  340. // set 0 level mipmap and then use GL to generate other mipmap levels
  341. if ( mipmaps.length > 0 && supportsMips ) {
  342. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  343. mipmap = mipmaps[ i ];
  344. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  345. }
  346. texture.generateMipmaps = false;
  347. textureProperties.__maxMipLevel = mipmaps.length - 1;
  348. } else {
  349. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  350. textureProperties.__maxMipLevel = 0;
  351. }
  352. } else if ( texture.isCompressedTexture ) {
  353. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  354. mipmap = mipmaps[ i ];
  355. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  356. if ( glFormat !== null ) {
  357. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  358. } else {
  359. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  360. }
  361. } else {
  362. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  363. }
  364. }
  365. textureProperties.__maxMipLevel = mipmaps.length - 1;
  366. } else if ( texture.isDataTexture2DArray ) {
  367. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  368. textureProperties.__maxMipLevel = 0;
  369. } else if ( texture.isDataTexture3D ) {
  370. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  371. textureProperties.__maxMipLevel = 0;
  372. } else {
  373. // regular Texture (image, video, canvas)
  374. // use manually created mipmaps if available
  375. // if there are no manual mipmaps
  376. // set 0 level mipmap and then use GL to generate other mipmap levels
  377. if ( mipmaps.length > 0 && supportsMips ) {
  378. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  379. mipmap = mipmaps[ i ];
  380. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  381. }
  382. texture.generateMipmaps = false;
  383. textureProperties.__maxMipLevel = mipmaps.length - 1;
  384. } else {
  385. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  386. textureProperties.__maxMipLevel = 0;
  387. }
  388. }
  389. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  390. generateMipmap( textureType, texture, image.width, image.height );
  391. }
  392. textureProperties.__version = texture.version;
  393. if ( texture.onUpdate ) texture.onUpdate( texture );
  394. }
  395. function uploadCubeTexture( textureProperties, texture, slot ) {
  396. if ( texture.image.length !== 6 ) return;
  397. initTexture( textureProperties, texture );
  398. state.activeTexture( _gl.TEXTURE0 + slot );
  399. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  400. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  401. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  402. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  403. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  404. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  405. const cubeImage = [];
  406. for ( let i = 0; i < 6; i ++ ) {
  407. if ( ! isCompressed && ! isDataTexture ) {
  408. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  409. } else {
  410. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  411. }
  412. }
  413. const image = cubeImage[ 0 ],
  414. supportsMips = isPowerOfTwo( image ) || isWebGL2,
  415. glFormat = utils.convert( texture.format ),
  416. glType = utils.convert( texture.type ),
  417. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  418. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  419. let mipmaps;
  420. if ( isCompressed ) {
  421. for ( let i = 0; i < 6; i ++ ) {
  422. mipmaps = cubeImage[ i ].mipmaps;
  423. for ( let j = 0; j < mipmaps.length; j ++ ) {
  424. const mipmap = mipmaps[ j ];
  425. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  426. if ( glFormat !== null ) {
  427. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  428. } else {
  429. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  430. }
  431. } else {
  432. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  433. }
  434. }
  435. }
  436. textureProperties.__maxMipLevel = mipmaps.length - 1;
  437. } else {
  438. mipmaps = texture.mipmaps;
  439. for ( let i = 0; i < 6; i ++ ) {
  440. if ( isDataTexture ) {
  441. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  442. for ( let j = 0; j < mipmaps.length; j ++ ) {
  443. const mipmap = mipmaps[ j ];
  444. const mipmapImage = mipmap.image[ i ].image;
  445. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  446. }
  447. } else {
  448. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  449. for ( let j = 0; j < mipmaps.length; j ++ ) {
  450. const mipmap = mipmaps[ j ];
  451. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  452. }
  453. }
  454. }
  455. textureProperties.__maxMipLevel = mipmaps.length;
  456. }
  457. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  458. // We assume images for cube map have the same size.
  459. generateMipmap( _gl.TEXTURE_CUBE_MAP, texture, image.width, image.height );
  460. }
  461. textureProperties.__version = texture.version;
  462. if ( texture.onUpdate ) texture.onUpdate( texture );
  463. }
  464. // Render targets
  465. // Setup storage for target texture and bind it to correct framebuffer
  466. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  467. const glFormat = utils.convert( renderTarget.texture.format );
  468. const glType = utils.convert( renderTarget.texture.type );
  469. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  470. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  471. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  472. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  473. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  474. }
  475. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  476. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  477. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  478. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  479. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  480. if ( isMultisample ) {
  481. const depthTexture = renderTarget.depthTexture;
  482. if ( depthTexture && depthTexture.isDepthTexture ) {
  483. if ( depthTexture.type === FloatType ) {
  484. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  485. } else if ( depthTexture.type === UnsignedIntType ) {
  486. glInternalFormat = _gl.DEPTH_COMPONENT24;
  487. }
  488. }
  489. const samples = getRenderTargetSamples( renderTarget );
  490. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  491. } else {
  492. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  493. }
  494. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  495. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  496. if ( isMultisample ) {
  497. const samples = getRenderTargetSamples( renderTarget );
  498. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  499. } else {
  500. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  501. }
  502. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  503. } else {
  504. const glFormat = utils.convert( renderTarget.texture.format );
  505. const glType = utils.convert( renderTarget.texture.type );
  506. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  507. if ( isMultisample ) {
  508. const samples = getRenderTargetSamples( renderTarget );
  509. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  510. } else {
  511. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  512. }
  513. }
  514. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  515. }
  516. // Setup resources for a Depth Texture for a FBO (needs an extension)
  517. function setupDepthTexture( framebuffer, renderTarget ) {
  518. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  519. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  520. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  521. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  522. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  523. }
  524. // upload an empty depth texture with framebuffer size
  525. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  526. renderTarget.depthTexture.image.width !== renderTarget.width ||
  527. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  528. renderTarget.depthTexture.image.width = renderTarget.width;
  529. renderTarget.depthTexture.image.height = renderTarget.height;
  530. renderTarget.depthTexture.needsUpdate = true;
  531. }
  532. setTexture2D( renderTarget.depthTexture, 0 );
  533. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  534. if ( renderTarget.depthTexture.format === DepthFormat ) {
  535. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  536. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  537. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  538. } else {
  539. throw new Error( 'Unknown depthTexture format' );
  540. }
  541. }
  542. // Setup GL resources for a non-texture depth buffer
  543. function setupDepthRenderbuffer( renderTarget ) {
  544. const renderTargetProperties = properties.get( renderTarget );
  545. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  546. if ( renderTarget.depthTexture ) {
  547. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  548. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  549. } else {
  550. if ( isCube ) {
  551. renderTargetProperties.__webglDepthbuffer = [];
  552. for ( let i = 0; i < 6; i ++ ) {
  553. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  554. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  555. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  556. }
  557. } else {
  558. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  559. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  560. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  561. }
  562. }
  563. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  564. }
  565. // Set up GL resources for the render target
  566. function setupRenderTarget( renderTarget ) {
  567. const renderTargetProperties = properties.get( renderTarget );
  568. const textureProperties = properties.get( renderTarget.texture );
  569. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  570. textureProperties.__webglTexture = _gl.createTexture();
  571. info.memory.textures ++;
  572. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  573. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  574. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  575. // Handles WebGL2 RGBFormat fallback - #18858
  576. if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {
  577. renderTarget.texture.format = RGBAFormat;
  578. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  579. }
  580. // Setup framebuffer
  581. if ( isCube ) {
  582. renderTargetProperties.__webglFramebuffer = [];
  583. for ( let i = 0; i < 6; i ++ ) {
  584. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  585. }
  586. } else {
  587. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  588. if ( isMultisample ) {
  589. if ( isWebGL2 ) {
  590. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  591. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  592. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer );
  593. const glFormat = utils.convert( renderTarget.texture.format );
  594. const glType = utils.convert( renderTarget.texture.type );
  595. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  596. const samples = getRenderTargetSamples( renderTarget );
  597. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  598. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  599. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer );
  600. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  601. if ( renderTarget.depthBuffer ) {
  602. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  603. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  604. }
  605. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  606. } else {
  607. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  608. }
  609. }
  610. }
  611. // Setup color buffer
  612. if ( isCube ) {
  613. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  614. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, supportsMips );
  615. for ( let i = 0; i < 6; i ++ ) {
  616. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  617. }
  618. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  619. generateMipmap( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, renderTarget.width, renderTarget.height );
  620. }
  621. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  622. } else {
  623. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  624. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, supportsMips );
  625. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  626. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  627. generateMipmap( _gl.TEXTURE_2D, renderTarget.texture, renderTarget.width, renderTarget.height );
  628. }
  629. state.bindTexture( _gl.TEXTURE_2D, null );
  630. }
  631. // Setup depth and stencil buffers
  632. if ( renderTarget.depthBuffer ) {
  633. setupDepthRenderbuffer( renderTarget );
  634. }
  635. }
  636. function updateRenderTargetMipmap( renderTarget ) {
  637. const texture = renderTarget.texture;
  638. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  639. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  640. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  641. const webglTexture = properties.get( texture ).__webglTexture;
  642. state.bindTexture( target, webglTexture );
  643. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  644. state.bindTexture( target, null );
  645. }
  646. }
  647. function updateMultisampleRenderTarget( renderTarget ) {
  648. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  649. if ( isWebGL2 ) {
  650. const renderTargetProperties = properties.get( renderTarget );
  651. _gl.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  652. _gl.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  653. const width = renderTarget.width;
  654. const height = renderTarget.height;
  655. let mask = _gl.COLOR_BUFFER_BIT;
  656. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  657. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  658. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  659. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
  660. } else {
  661. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  662. }
  663. }
  664. }
  665. function getRenderTargetSamples( renderTarget ) {
  666. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  667. Math.min( maxSamples, renderTarget.samples ) : 0;
  668. }
  669. function updateVideoTexture( texture ) {
  670. const frame = info.render.frame;
  671. // Check the last frame we updated the VideoTexture
  672. if ( _videoTextures.get( texture ) !== frame ) {
  673. _videoTextures.set( texture, frame );
  674. texture.update();
  675. }
  676. }
  677. // backwards compatibility
  678. let warnedTexture2D = false;
  679. let warnedTextureCube = false;
  680. function safeSetTexture2D( texture, slot ) {
  681. if ( texture && texture.isWebGLRenderTarget ) {
  682. if ( warnedTexture2D === false ) {
  683. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  684. warnedTexture2D = true;
  685. }
  686. texture = texture.texture;
  687. }
  688. setTexture2D( texture, slot );
  689. }
  690. function safeSetTextureCube( texture, slot ) {
  691. if ( texture && texture.isWebGLCubeRenderTarget ) {
  692. if ( warnedTextureCube === false ) {
  693. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  694. warnedTextureCube = true;
  695. }
  696. texture = texture.texture;
  697. }
  698. setTextureCube( texture, slot );
  699. }
  700. //
  701. this.allocateTextureUnit = allocateTextureUnit;
  702. this.resetTextureUnits = resetTextureUnits;
  703. this.setTexture2D = setTexture2D;
  704. this.setTexture2DArray = setTexture2DArray;
  705. this.setTexture3D = setTexture3D;
  706. this.setTextureCube = setTextureCube;
  707. this.setupRenderTarget = setupRenderTarget;
  708. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  709. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  710. this.safeSetTexture2D = safeSetTexture2D;
  711. this.safeSetTextureCube = safeSetTextureCube;
  712. }
  713. export { WebGLTextures };