使用WebGL将DDS(DXT3)纹理转换为ImageData

时间:2017-09-16 18:55:07

标签: typescript webgl framebuffer dds-format

我正在尝试使用WebGL将DDS texture(主要是DXT1和DXT3)转换为ImageData。这是我的尝试...

let ext = <WEBGL_compressed_texture_s3tc>gl.getExtension('WEBGL_compressed_texture_s3tc');

let texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);

let fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);

gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext.COMPRESSED_RGBA_S3TC_DXT3_EXT, width, height, 0, sourceImage);

gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);

let data = new Uint8Array(width * height * 4);

gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);
gl.deleteFramebuffer(fb);

let image = new ImageData(new Uint8ClampedArray(data), width, height);

其中 gl 是WebGLRenderingContext, sourceImage (Uint8Array)是DXT3格式的纹理。没有任何mipmap或其他东西。我确定,因为我尝试使用this代码段渲染此纹理并且它正常工作。

代码在readPixels函数失败并出现以下错误(Google Chrome):

  

[.Offscreen-For-WebGL-000001F2F3C04690] GL错误   :GL_INVALID_FRAMEBUFFER_OPERATION:glReadPixels:framebuffer   不完整的

我当然正在寻找答案,但没有任何成功。也许this可能有所帮助。如果需要的话,我可以提供一些示例纹理。

1 个答案:

答案 0 :(得分:2)

您无法渲染为压缩纹理格式,因此将它们附加到帧缓冲区会引发无效的操作错误。您需要将未压缩的纹理附加到帧缓冲区,然后从DXT纹理中绘制一个屏幕空间四边形采样。像这样:

let ext = <WEBGL_compressed_texture_s3tc>gl.getExtension('WEBGL_compressed_texture_s3tc');

// create framebuffer attachment texture
let colorTarget = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, colorTarget);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(
    gl.TEXTURE_2D,
    0,
    gl.RGBA,
    width,
    height,
    0,
    gl.RGBA,
    gl.UNSIGNED_BYTE,
    null
);
// setup framebuffer
let fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTarget, 0);

// create and upload compressed texture
let compressedTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, compressedTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.compressedTexImage2D(gl.TEXTURE_2D, 0, ext.COMPRESSED_RGBA_S3TC_DXT3_EXT, width, height, 0, sourceImage);

gl.viewport(0,0,width,height);
//draw screenspace quad here

// read back uncompressed color data
let data = new Uint8Array(width * height * 4);
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);

gl.deleteFramebuffer(fb);

let imageData = new ImageData(new Uint8ClampedArray(data), width, height);