Problem with one shader for multiple materials

Hello, i have problem with shader. i have code like that:

function loadModel(...)  {
        var test = "\nvec3 col = vec3( " + Math.random() + ", " + Math.random() + ", " + Math.random() + " );";
        var materials = [
            new THREE.MeshPhongMaterial({
                color: Settings.ModelMeshColors.Normal,
                side: THREE.DoubleSide,
                flatShading: true,
                polygonOffset: true,
                polygonOffsetFactor: 1,
                polygonOffsetUnits: 1,
                userData: { shaderAreaConditions: test },
                onBeforeCompile: shaderTest
            })
        ];
...
}
shaderTest = function (shader)
{
    shader.vertexShader = (
            "varying vec3 vPos;\n" +
            shader.vertexShader + "\n")
        .replace(
            "#include <begin_vertex>",
            "#include <begin_vertex>\n" +
            "vPos = (modelMatrix * vec4(position, 1.0)).xyz;");

shader.fragmentShader = (
            "varying vec3 vPos;\n" +
            shader.fragmentShader + "\n")
        .replace("vec4 diffuseColor = vec4( diffuse, opacity );",
             this.userData.shaderAreaConditions +
            "\nvec4 diffuseColor = vec4( col, opacity );");
}

and always models have the same color like first loaded. like that randoms run only once

Notice onBeforeCompile runs only once and the js code string of it contributes to a identifier so programs can be shared.

You might see if this plugin helps you as well, as you can use per-mesh uniforms with a single material with it.

1 Like