C++ C++;着色问题

C++ C++;着色问题,c++,directx,shader,C++,Directx,Shader,我正在使用Nvidia CG和Direct3D9,对以下代码有疑问 它进行编译,但不“加载”(使用cgLoadProgramwrapper),因此产生的故障被简单地描述为发生了D3D故障 它是使用着色器模型设置为3.0 有趣的是,该着色器在以下情况下加载良好: float2 tex = float2(1, 1); float2 dtex = float2(0.01, 0.01); float h = 1.0 - tex2D(height_texture1, tex); float height

我正在使用
Nvidia CG
Direct3D9
,对以下代码有疑问

它进行编译,但不“加载”(使用
cgLoadProgram
wrapper),因此产生的故障被简单地描述为发生了
D3D故障

它是使用着色器模型设置为
3.0

有趣的是,该着色器在以下情况下加载良好:

float2 tex = float2(1, 1);
float2 dtex = float2(0.01, 0.01);

float h = 1.0 - tex2D(height_texture1, tex);
float height = 1.00;

while ( h < height )
{
    height -= 0.1;
    tex += dtex;

    // Remove the next line and it works (not as expected,
    // of course)
    h = tex2D( height_texture1, tex );
}
1)手动展开while语句(对许多
if{}
语句)

2)使用循环中的
tex2D
功能删除行

3)切换到着色器模型
2\u X
并手动展开循环


着色器代码的问题部分:

float2 tex = float2(1, 1);
float2 dtex = float2(0.01, 0.01);

float h = 1.0 - tex2D(height_texture1, tex);
float height = 1.00;

while ( h < height )
{
    height -= 0.1;
    tex += dtex;

    // Remove the next line and it works (not as expected,
    // of course)
    h = tex2D( height_texture1, tex );
}
float2tex=float2(1,1);
float2dtex=float2(0.01,0.01);
浮点数h=1.0-tex2D(高度×纹理1,tex);
浮子高度=1.00;
而(h<高度)
{
高度-=0.1;
tex+=dtex;
//移除下一行,它就会工作(不符合预期,
//(当然可以)
h=tex2D(高度×纹理1,tex);
}
如果有人知道为什么会发生这种情况,或者可以在非CG环境中测试类似的代码,或者可以在其他方面帮助我,我在等你;)


谢谢。

我认为您需要在纹理坐标上使用ddx/ddy确定循环之前的梯度,然后使用
tex2D(sampler2D samp、float2 s、float2 dx、float2 dy)

GPU始终渲染四边形而不是像素(即使在像素边界上-渲染后端会丢弃多余的像素)。这样做是因为它允许它始终计算屏幕空间纹理导数,即使在使用计算的纹理坐标时也是如此。它只需要取像素中心的值之间的差值

但是,当使用动态分支时(如问题中的代码中),这不起作用,因为单个像素处的着色器处理器可能在控制流中发散。因此,在程序流发散之前,您需要通过ddx/ddy手动计算导数