Duane J
Duane J

Reputation: 1823

Where to store cached data for access within vertex shader?

Is there a reasonable place to store computed data for a vertex shader that is computed once, and then used many times (i.e. for each vertex)?

I'm writing a shader that follows a catmull-rom curve, and I need to pre-compute (just once!) a series of evenly spaced positions along the curve so that I can plot text glyphs correctly. Once computed, I intend to use the evenly spaced array of positions as a fast lookup.

It's possible there could be hundreds of vec3 or vec4 points in this cache, depending on how finely sliced into arclengths the spline is.

Would such data best be placed in a uniform? A texture? Something else?

Upvotes: 1

Views: 219

Answers (1)

M -
M -

Reputation: 28472

This question is pretty broad, but if you're thinking of performing calculations in the GPU, then you're looking for a THREE.WebGLRenderTarget. Instead of rendering a shader to the <canvas> you can render it to a RenderTarget, which stores the result in a texture that you can attach to other materials later.

Take a look at this example,

  1. They perform position calculations in a fragment shader
  2. These positions gets stored in a RenderTarget's texture
  3. The texture is then passed to a plane to displace the vertex.y positions.

Here's some pseudocode on how it could be achieved:

// Create renderTarget
const renderTarget = new THREE.WebGLRenderTarget(width, height);

// Perform GPU calculations, store result in renderTarget.texture
renderer.setRenderTarget(renderTarget);
renderer.render(calculationScene, calculationCamera);

// Resulting texture can now be assigned to materials
object.material.map = renderTarget.texture;

// Now we render to canvas as usual
renderer.setRenderTarget(null);
renderer.render(scene, camera);

This texture data could be used in lieu of a vec3 or vec4 if you use RGB or RGBA channels respectively.

Upvotes: 2

Related Questions