WebGLCubeUVMaps.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import { CubeReflectionMapping, CubeRefractionMapping, EquirectangularReflectionMapping, EquirectangularRefractionMapping } from '../../constants.js';
  2. import { PMREMGenerator } from '../../extras/PMREMGenerator.js';
  3. function WebGLCubeUVMaps( renderer ) {
  4. let cubeUVmaps = new WeakMap();
  5. let pmremGenerator = null;
  6. function get( texture ) {
  7. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  8. const mapping = texture.mapping;
  9. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  11. if ( isEquirectMap || isCubeMap ) {
  12. // equirect/cube map to cubeUV conversion
  13. if ( cubeUVmaps.has( texture ) ) {
  14. return cubeUVmaps.get( texture ).texture;
  15. } else {
  16. const image = texture.image;
  17. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  18. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  19. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  20. cubeUVmaps.set( texture, renderTarget );
  21. texture.addEventListener( 'dispose', onTextureDispose );
  22. return renderTarget.texture;
  23. } else {
  24. // image not yet ready. try the conversion next frame
  25. return null;
  26. }
  27. }
  28. }
  29. }
  30. return texture;
  31. }
  32. function isCubeTextureComplete( image ) {
  33. let count = 0;
  34. const length = 6;
  35. for ( let i = 0; i < length; i ++ ) {
  36. if ( image[ i ] !== undefined ) count ++;
  37. }
  38. return count === length;
  39. }
  40. function onTextureDispose( event ) {
  41. const texture = event.target;
  42. texture.removeEventListener( 'dispose', onTextureDispose );
  43. const cubemapUV = cubeUVmaps.get( texture );
  44. if ( cubemapUV !== undefined ) {
  45. cubeUVmaps.delete( texture );
  46. cubemapUV.dispose();
  47. }
  48. }
  49. function dispose() {
  50. cubeUVmaps = new WeakMap();
  51. if ( pmremGenerator !== null ) {
  52. pmremGenerator.dispose();
  53. pmremGenerator = null;
  54. }
  55. }
  56. return {
  57. get: get,
  58. dispose: dispose
  59. };
  60. }
  61. export { WebGLCubeUVMaps };