three.js中的部分纹理更新

时间:2018-11-13 16:27:21

标签: three.js webgl texture2d

我在three.js中将大纹理作为地图上传到片段着色器。

此纹理是2D画布,我可以在上面绘制随机形状。

在绘制时,我只想更新已更改的纹理部分。更新整个纹理(最大3000x3000像素)太慢了。

但是,我无法执行部分更新。 texSubImage2D在我的场景中没有任何作用。

控制台中没有错误-我希望我错过了一个步骤,但仍无法弄清楚。

//
// create drawing canvas 2D and related textures
//

this._canvas = document.createElement('canvas');
this._canvas.width = maxSliceDimensionsX;
this._canvas.height = maxSliceDimensionsY;

this._canvasContext = this._canvas.getContext('2d')!;
this._canvasContext.fillStyle = 'rgba(0, 0, 0, 0)';
this._canvasContext.fillRect(0, 0, window.innerWidth, window.innerHeight);

this._texture = new Texture(this._canvas);
this._texture.magFilter = NearestFilter;
this._texture.minFilter = NearestFilter;

// const data = new Uint8Array(maxSliceDimensionsX * maxSliceDimensionsY * 4);
// this._texture2 = new THREE.DataTexture(data, maxSliceDimensionsX, maxSliceDimensionsY, THREE.RGBAFormat);

this._brushMaterial = new MeshBasicMaterial({
  map: this._texture,
  side: DoubleSide,
  transparent: true,
});
...


// in the render loop
renderLoop() {
   ...
   // grab random values as a test
   const imageData = this._canvasContext.getImageData(100, 100, 200, 200);
   const uint8Array = new Uint8Array(imageData.data.buffer);

   // activate texture?
   renderer.setTexture2D(this._texture, 0 );
   // update subtexture
   const context = renderer.getContext();
   context.texSubImage2D( context.TEXTURE_2D, 0, 0, 0, 200, 200, context.RGBA, context.UNSIGNED_BYTE, uint8Array);

   // updating the whole texture works as expected but is slow
   // this._texture.needsUpdate = true;

    // Render new scene
    renderer.render(scene, this._camera);

}

谢谢, 尼古拉斯

1 个答案:

答案 0 :(得分:0)

在创建纹理之后,我们必须通知three该纹理需要上载到GPU。

我们只需要在创建时将其设置为1即可,而不是在渲染循环中设置。

this._texture = new Texture(this._canvas);
this._texture.magFilter = NearestFilter;
this._texture.minFilter = NearestFilter;

// MUST BE ADDED
this._texture.needsUpdate = true;