Three.js Shader材质如何获得(贴图)纹理?

时间:2017-05-16 12:58:51

标签: three.js

我这里有一个问题) 我决定使用我的着色器(scene.overrideMaterial),我需要以某种方式获取地图纹理。

MaterialsShader = {
uniforms: {
    time: { type: 'f', value: 0.0 },
},
vertexShader: 
    "varying vec2 vUv; \n\
    void main(){\n\
        vUv = uv;\n\
        vec4 mvPosition = modelViewMatrix * vec4(position, 1.0 );\n\
        gl_Position = projectionMatrix * mvPosition;\n\
    }",
fragmentShader: [
    'varying vec2 vUv;',
    'uniform float opacity;',

    '#ifdef USE_MAP',

        'uniform sampler2D map;',

    '#endif',

    'void main(){',
        'vec3 color = vec3(1.0,0.0,0.0) * opacity;',

        '#ifdef USE_MAP',

            'vec4 mapTexel = texture2D( map, vUv.xy );',

            'gl_FragColor = mapTexel;',

        '#endif',

        //'gl_FragColor.rgb = color;',

    '}'].join("\n")
}

但由于某种原因纹理本身不存在,我得到黑色材料。

var uniforms = THREE.UniformsUtils.clone( MaterialsShader.uniforms );

    uniforms = THREE.UniformsUtils.merge( [uniforms, THREE.UniformsLib['common'],THREE.UniformsLib['lights']] );


var material = new THREE.ShaderMaterial({
    uniforms        : uniforms,
    vertexShader    : MaterialsShader.vertexShader,
    fragmentShader  : MaterialsShader.fragmentShader,
});

如何获得(地图)纹理?

1 个答案:

答案 0 :(得分:2)

1)您需要实际定义map制服......

MaterialsShader = {
uniforms: {
    time: { type: 'f', value: 0.0 },
    map: { type: 't', value: yourLoadedTexture },
},

2)您需要定义USE_MAP才能输入着色器的代码段。将其添加到着色器代码的顶部:

#define USE_MAP true

或者您可以为着色器设置defines属性:

var material = new THREE.ShaderMaterial({
    uniforms        : uniforms,
    vertexShader    : MaterialsShader.vertexShader,
    fragmentShader  : MaterialsShader.fragmentShader,
    map             : yourLoadedTexture,
    defines         : {
        USE_MAP: true
    }
});

这些具有相同的效果。