Ruan Sunkel
Ruan Sunkel

Reputation: 211

Metal Fragment Shader, access current framebuffer color

I am writing a metal shader.

All I want is to access the current color of the fragment.

For example.

At the end of my fragment shader, when I put return currentColor + 0.1, for example

The result will be screen going from black to white at FPS. This is a basic program that draws a triangle strip that fills the screen. Ultimate aim is writing a path tracer inside the shader, I have done this with opengl + glsl. I am having trouble with the buffers. I thought an easy solution is to just pass the current output color back to the shader and average it in there.

These are the shaders:

#include <metal_stdlib>
using namespace metal;
#import "AAPLShaderTypes.h"

vertex float4 vertexShader(uint vertexID [[vertex_id]], constant AAPLVertex *vertices [[buffer(AAPLVertexInputIndexVertices)]], constant vector_uint2 *viewportSizePointer [[buffer(AAPLVertexInputIndexViewportSize)]], constant vector_float4 * seeds) {

    float4 clipSpacePosition = vector_float4(0.0, 0.0, 0.0, 1.0);

    float2 pixelSpacePosition = vertices[vertexID].position.xy;
    vector_float2 viewportSize = vector_float2(*viewportSizePointer);
    clipSpacePosition.xy = pixelSpacePosition / (viewportSize / 2.0);

    return clipSpacePosition;
}

fragment float4 fragmentShader()
{
    // I want to do this
    // return currentColor + 0.1;

    return float4(1.0, 1.0, 1.0, 1.0);
}

Upvotes: 1

Views: 1419

Answers (1)

Ruan Sunkel
Ruan Sunkel

Reputation: 211

No worries, the answer was staring me in the face the whole time.

Pass in the current color into the fragment shader with float4 color0 [[color(0)]]

With these 2 options set renderPassDescriptor.colorAttachments[0].storeAction = MTLStoreActionStore; renderPassDescriptor.colorAttachments[0].loadAction = MTLLoadActionLoad;

My problem was not the color, it was in calculating the average. In my case I could not do regular average, as in add up all the colors so far and divide by the number of samples.

What I actually needed to do was calculate a Moving average.

https://en.wikipedia.org/wiki/Moving_average#Cumulative_moving_average

Upvotes: 4

Related Questions