我正在尝试重复使用现有的basic,lambert和phong材质,这样我就可以在镜像反射上出现颠簸,法线贴图,..等等。我使用的是最新版本的three.js,即87.
我尝试使用onBeforeCompile函数追加并替换部分MeshBasicMaterial顶点和片段代码,但我的镜像没有显示。 有人可以请帮助。谢谢。
以下是我在mirror.js中所做的事情
/ *注释掉了使用shaderLib镜像着色器的现有代码
var mirrorShader = THREE.ShaderLib[ "mirror" ];
var mirrorUniforms = THREE.UniformsUtils.clone( mirrorShader.uniforms );
//console.log('opacity:', this.mirror_opacity)
mirrorUniforms['opacity'].value = this.mirror_opacity;
this.material = new THREE.ShaderMaterial( {
fragmentShader: mirrorShader.fragmentShader,
vertexShader: mirrorShader.vertexShader,
uniforms: mirrorUniforms,
transparent: true
} );
this.material.uniforms.mirrorSampler.value = this.renderTarget.texture;
this.material.uniforms.mirrorColor.value = mirrorColor;
this.material.uniforms.textureMatrix.value = this.textureMatrix;
* /
/ *这是我用* /
替换的材料 var textureLoader = new THREE.TextureLoader();
var texture = textureLoader.load("images/test.jpg");
this.material = new THREE.MeshBasicMaterial({ map: texture});
var mirror_texture = this.renderTarget.texture;
this.material.onBeforeCompile = function ( shader ) {
let mirrormap_pars_vertex = [
'uniform mat4 textureMatrix;',
'varying vec2 texCoord;',
'varying vec4 mirrorCoord;\n',
] .join('\n');
shader.vertexShader = mirrormap_pars_vertex + shader.vertexShader;
shader.vertextShader = shader.vertexShader.replace(
'#include <begin_vertex>',
[
'vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );',
'vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
'mirrorCoord = textureMatrix * worldPosition;',
'texCoord = uv;',
'gl_Position = projectionMatrix * mvPosition;\n',
].join( '\n' )
);
let mirrormap_pars_fragment = [
'uniform vec3 mirrorColor;',
'uniform sampler2D mirrorSampler;',
'uniform sampler2D maskSampler;',
'varying vec4 mirrorCoord;',
'varying vec2 texCoord;\n',
].join('\n');
shader.fragmentShader = mirrormap_pars_fragment + shader.fragmentShader;
shader.fragmentShader = shader.fragmentShader.replace(
'#include <map_fragment>',
[
'#ifdef USE_MAP\n',
'vec4 mask = texture2D(maskSampler, texCoord);',
'vec4 color = texture2DProj(mirrorSampler, mirrorCoord);',
//'vec4 texelColor = texture2D( map, vUv );',
//'color = vec4(blendOverlay(mirrorColor.r, color.r), blendOverlay(mirrorColor.g, color.g), blendOverlay(mirrorColor.b, color.b), opacity);',
//'color.a *= texture2D(maskSampler, texCoord).g;'
'diffuseColor *= color;',
'#endif\n',
].join( '\n' )
);
shader.uniforms.mirrorSampler = {type : "t", value : mirror_texture};
shader.uniforms.textureMatrix = { type: "m4", value: new THREE.Matrix4() };
shader.uniforms.maskSampler = {type: "t", value: null}
shader.uniforms.mirrorColor = { type: "c", value: new THREE.Color(0x7F7F7F) };
console.log("shader", shader )