2013-02-12 132 views
1

我尝试根据它们在最高和最低顶点之间的位置为着色器着色片段。下面是着色器:three.js - 片段着色器基础知识 - 通过它的位置为片段着色

<script type="x-shader/x-vertex" id="vertexshader"> 

    uniform  float span; 

    attribute float displacement; 

    varying  vec3 vNormal; 
    varying  float color_according_to_z; 

       float z_actual; 

    void main() { 
     vNormal = normal; 

     vec3 newPosition = position + normal * vec3(0.0, 0.0, displacement); 
     gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0); 

     z_actual = gl_Position.z + span/2.0; 
     color_according_to_z = 1.0/span * z_actual; 
    } 

</script> 

<script type="x-shader/x-fragment" id="fragmentshader"> 

    uniform  float span; 

    varying  float color_according_to_z; 

    void main() 
    { 
     gl_FragColor = vec4(color_according_to_z, 0.5, 0.5, 1.0); 
    } 

</script> 

这里是我的渲染功能:

function render() { 
    requestAnimationFrame(render); 

    plane.rotation.x = global_x_rotation; 
    plane.rotation.z = global_z_rotation; 

    for(var i = attributes.displacement.value.length - 1; i >= 0; i--) { 
     attributes.displacement.value[i] = attributes.displacement.value[i] - 0.5 + Math.random(); 
    }; 

    uniforms.lowest = attributes.displacement.value.min(); 
    uniforms.highest = attributes.displacement.value.max(); 
    uniforms.span = uniforms.highest - uniforms.lowest; 

    attributes.displacement.needsUpdate = true; 

    uniforms.lowest.needsUpdate = true; 
    uniforms.highest.needsUpdate = true; 
    uniforms.span.needsUpdate = true; 

    renderer.render(scene, camera); 
} 

我改变从帧的位移框架和重新计算最高和最低的顶点之间的跨度。

最后一块,如何绘制一个片段根据它的位置朝着最高或最低,我还不知道。

Here is a jsfiddle with the mentioned code.

+0

但不尝试你的代码,它看起来像你对我已经拥有了你所需要的。你在看什么?你可以张贴截图吗? – 2013-02-12 08:59:58

+0

我给你做了一个小屏幕录制:http://cl.ly/3I3D0D3l3C1Q。顶点移动得很好,但着色不起作用。 – thgie 2013-02-12 10:13:01

+0

不知道我是否想在工作中打开一个名为“shagging.mov”的东西= O – 2013-02-12 10:14:50

回答

1

你有几个错误,我可以看到。检查你的变量中的NaN。

着色器逻辑看起来不错,除了它可能不会产生所需的颜色。

var max = -1.0e30; 
var min = +1.0e30; 
var x; 
for(var i = attributes.displacement.value.length - 1; i >= 0; i--) { 
    x = attributes.displacement.value[i] += - 0.5 + Math.random(); 
    if (x < min) min = x; 
    if (x > max) max = x; 
}; 

uniforms.lowest.value = min; // lowest.value ! 
uniforms.highest.value = max; 
uniforms.span.value = max - min; 

attributes.displacement.needsUpdate = true; 

//uniforms.lowest.needsUpdate = true; // not needed for uniforms 
//uniforms.highest.needsUpdate = true; 
//uniforms.span.needsUpdate = true; 

小提琴:http://jsfiddle.net/c2jry/2/

+0

uniforms.span在我最后一次检查时计算得很好。你有没有按照你在这里陈述的方式去做的特殊原因? – thgie 2013-02-12 10:47:41

+0

您遗漏了.value。 - span:{type:'f',value:0.0} – WestLangley 2013-02-12 10:50:27

+0

我当然这样做。谢谢你指出一个。 – thgie 2013-02-12 10:57:09