在 three.js 中将数组传递给着色器的正确方法
Proper way to pass array to shader in three.js
我有一个简单的程序,我试图将一组固定值(本质上是查找 table)传递给着色器。调用代码如下所示:
var displacement = [];
for ( var y=0; y<46; y++ ) {
for ( var x=0; x<46; x++ ) {
var sVal = Math.sin((((x/5.0)*40.0)/360.0)*Math.PI*2.0);
var index = x + 46 * y;
displacement[index] = sVal;
}
}
planeGeometry.addAttribute( 'displacement', new THREE.BufferAttribute( displacement, 1 ) );
var shaderMaterial = new THREE.ShaderMaterial({
uniforms: uniforms, // pass the "uniforms" vars
//attributes: attributes, // and the attributes
side:THREE.DoubleSide, // want the texture on both sides of the wave
vertexShader: vs, // pointers to the shaders
fragmentShader: fs
});
着色器看起来像这样:
<script id="vertexShader" type="x-shader/x-fragment">
varying vec2 vUv;
attribute float displacement;
uniform float amplitude;
void main() {
vUv = uv;
vec3 newPosition = position + normal * vec3(displacement * amplitude);
gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
}
</script>
在 r72 之前,我在着色器 material 的构造函数中将数组作为属性传递,但现在它必须作为 bufferGeometry 属性传递。旧方法行得通,但现在我得到
[.CommandBufferContext]GL 错误:GL_INVALID_OPERATION:glDrawElements:尝试访问属性 1
中超出范围的顶点
我已经尝试了很多方法来做到这一点,但其中 none 行得通。有谁知道正确的做法吗?
您需要为位移数组使用类型化数组,而不是 JS 数组。
var displacement = new Float32Array( size );
three.js r.75
我有一个简单的程序,我试图将一组固定值(本质上是查找 table)传递给着色器。调用代码如下所示:
var displacement = [];
for ( var y=0; y<46; y++ ) {
for ( var x=0; x<46; x++ ) {
var sVal = Math.sin((((x/5.0)*40.0)/360.0)*Math.PI*2.0);
var index = x + 46 * y;
displacement[index] = sVal;
}
}
planeGeometry.addAttribute( 'displacement', new THREE.BufferAttribute( displacement, 1 ) );
var shaderMaterial = new THREE.ShaderMaterial({
uniforms: uniforms, // pass the "uniforms" vars
//attributes: attributes, // and the attributes
side:THREE.DoubleSide, // want the texture on both sides of the wave
vertexShader: vs, // pointers to the shaders
fragmentShader: fs
});
着色器看起来像这样:
<script id="vertexShader" type="x-shader/x-fragment">
varying vec2 vUv;
attribute float displacement;
uniform float amplitude;
void main() {
vUv = uv;
vec3 newPosition = position + normal * vec3(displacement * amplitude);
gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
}
</script>
在 r72 之前,我在着色器 material 的构造函数中将数组作为属性传递,但现在它必须作为 bufferGeometry 属性传递。旧方法行得通,但现在我得到
[.CommandBufferContext]GL 错误:GL_INVALID_OPERATION:glDrawElements:尝试访问属性 1
中超出范围的顶点我已经尝试了很多方法来做到这一点,但其中 none 行得通。有谁知道正确的做法吗?
您需要为位移数组使用类型化数组,而不是 JS 数组。
var displacement = new Float32Array( size );
three.js r.75