2013-03-11 159 views
9

我想通过计算着色器在OpenGL中进行一些光线追踪,并且遇到了一个奇怪的问题。此刻,我只想显示一个没有任何阴影的球体。我的计算着色器发射的光线为每个像素,看起来像这样:通过计算着色器在OpenGL中进行光线追踪

#version 430 
struct Sphere{ 
    vec4 position; 
    float radius; 
}; 

struct Ray{ 
    vec3 origin; 
    vec3 dir; 
}; 

uniform image2D outputTexture; 
uniform uint  width; 
uniform uint  height; 

float hitSphere(Ray r, Sphere s){ 

    float s_vv = dot(r.dir, r.dir); 
    float s_ov = dot(r.origin, r.dir); 
    float s_mv = dot(s.position.xyz, r.dir); 
    float s_mm = dot(s.position.xyz, s.position.xyz); 
    float s_mo = dot(s.position.xyz, r.origin); 
    float s_oo = dot(r.origin, r.origin); 

    float d = s_ov*s_ov-2*s_ov*s_mv+s_mv*s_mv-s_vv*(s_mm-2*s_mo*s_oo-s.radius*s.radius); 

    if(d < 0){ 
     return -1.0f; 
    } else if(d == 0){ 
     return (s_mv-s_ov)/s_vv; 
    } else { 
     float t1 = 0, t2 = 0; 
     t1 = s_mv-s_ov; 

     t2 = (t1-sqrt(d))/s_vv; 
     t1 = (t1+sqrt(d))/s_vv; 

     return t1>t2? t2 : t1 ; 
    } 
} 

layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in; 
void main(){ 
    uint x = gl_GlobalInvocationID.x; 
    uint y = gl_GlobalInvocationID.y; 

    if(x < 1024 && y < 768){ 
     float t = 0.0f; 
     Ray r = {vec3(0,0,0), vec3(width/2-x, height/2-y, 1000)}; 
     Sphere sp ={vec4(0, 0, 35, 1), 5.0f}; 

     t = hitSphere(r, sp); 

     if(t <= -0.001f){ 
      imageStore(outputTexture, ivec2(x, y), vec4(0.0, 0.0, 0.0, 1.0)); 
     } else { 
      imageStore(outputTexture, ivec2(x, y), vec4(0.0, 1.0, 0.0, 1.0)); 
     } 

     if(x == 550 && y == 390){ 
      imageStore(outputTexture, ivec2(x, y), vec4(1.0, 0.0, 0.0, 1.0)); 
     } 
    } 
} 

当我运行的应用程序,我获得下面的图片: enter image description here

但是当我运行的CPU,我得到相同的算法以下更令人信服的图像: enter image description here

首先,我以为我没有派遣足够的工作组,以便不是每个像素都获得自己的计算着色器调用,但事实并非如此。正如您在GPU渲染图像中看到的那样,中间有一个红色像素,它是由计算着色器中的最后一行引起的。这可以为每个其他像素重现。

我使用分辨率为1024x768的时刻,这是我如何分配我的计算着色器:

#define WORK_GROUP_SIZE 16 
void OpenGLRaytracer::renderScene(int width, int height){ 
    glUseProgram(_progID); 

    glDispatchCompute(width/WORK_GROUP_SIZE, height/WORK_GROUP_SIZE,1); 

    glMemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT); 
} 

哪里错了吗?浮点计算的准确性可能存在问题吗?

+0

奇怪这个应用程序看起来很像我的东西在周六做.. – 2013-03-11 17:53:42

+0

你碰到过这种奇怪的行为? – Stan 2013-03-11 18:06:12

+0

你的'#version'指令在哪里? – genpfault 2013-03-11 18:46:05

回答

3

错就错在这条线:

Ray r = {vec3(0,0,0), vec3(width/2-x, height/2-y, 1000)}; 

由于宽度,高度,x和y是UINT变量我会得到问题时,术语宽/ 2-x变成是负面的。

这解决了这个问题:

Ray r = {vec3(0,0,0), vec3(float(width)/2.0f-float(x), float(height)/2.0f-float(y), 1000)};