【问题标题】:Three.js Particle System different texture for each particleThree.js Particle System 为每个粒子设置不同的纹理
【发布时间】:2013-08-19 21:40:47
【问题描述】:

在 Three.js 中,我加载了 1000 个粒子和 2 个不同的纹理。

var particleCount = 1000;
var texture1 = THREE.ImageUtils.loadTexture( 'texture1.png' );
var texture2 = THREE.ImageUtils.loadTexture( 'texture2.png' );

var customUniforms = {
    texture:   {type: "t", value: texture1} // how do you set this value per a particle?
};

var customAttributes = {
    customColor:   {type: "c", value: []},
    customSize: {type: "f", value: []}
};

for(var p = 0; p < particleCount; p++ )
{
    customAttributes.customColor.value[p] = new THREE.Color(0xFFFFFF * Math.random());
    customAttributes.customSize.value[p] = size;

    //  .. place particle and push to particles code
}

var shaderMaterial = new THREE.ShaderMaterial({
        uniforms:       customUniforms,
        attributes:     customAttributes,
        vertexShader:   document.getElementById( 'vertexshader' ).textContent,
        fragmentShader: document.getElementById( 'fragmentshader' ).textContent,
        transparent: true,
        alphaTest: 0.5
});

这是片段着色器:

uniform sampler2D texture;
varying vec3 vColor;
void main()
{
    // calculates a color for the particle
    gl_FragColor = vec4( vColor, 1.0 );
    // sets particle texture to desired color
    gl_FragColor = gl_FragColor * texture2D( texture, gl_PointCoord );
}

如何向每个粒子的片段着色器发送不同的纹理?

【问题讨论】:

标签: javascript three.js webgl


【解决方案1】:

嗯...通过属性发送纹理索引。

每个粒子都是单点。 (点精灵)
每个点都有位置(通过属性)和其他属性。 (通过属性或制服)
Position 通常是 vec3 (x, y, z) 转换为 vec4(position, 1.0) 的类型。
我不知道 three.js 是否使用第四个元素(来自 vec4 的“w”),但您可以尝试通过它发送纹理索引。

顶点:

attribute vec4 vertPos; //x, y, z, w = texture index (you can use own, custom attribute)
varying float texIndex;
...
texIndex = vertPos.w;
...

片段:

...
if(texIndex == 0) tex = texture2D(texture0, gl_PointCoord);
else tex = texture2D(texture1, gl_PointCoord);
...

我没有测试过。
我从来没有用过这个库。

【讨论】:

  • 这样的事情会起作用。您需要将每个纹理传递给片段着色器,如果您添加更多纹理以供选择,这并不理想。
  • @wwwuser 所以最后你是怎么做到的?任何 sudo 代码或 jsfiddle ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 2017-12-11
  • 1970-01-01
相关资源
最近更新 更多