首页 > 解决方案 > Three.js Cubemap reflection shader rotation

问题描述

I'm trying to write my own reflection shader however the reflection does not work correctly when I try to rotate the sphere. It works only when my sphere is static. Here is my GLSL code:

sphereMaterial = new THREE.ShaderMaterial({
    uniforms: {
      uCubeMap: { value: cubeCamera.renderTarget.texture },
    },
    vertexShader: `
      varying vec2 vUv;
      varying vec3 vViewVector;
      varying vec3 vNormal;

      void main() {
        vec4 modelPosition = modelMatrix * vec4(position, 1.0);
        vec4 viewPosition = viewMatrix * modelPosition;
        vec4 projectedPosition = projectionMatrix * viewPosition;

        vViewVector = modelPosition.xyz - cameraPosition;
        vNormal = normal;

        gl_Position = projectedPosition;
      }
    `,
    fragmentShader: `
      uniform samplerCube uCubeMap;

      varying vec3 vViewVector;
      varying vec3 vNormal;

      void main() {
        vec3 reflectedDirection = normalize(reflect(vViewVector, vNormal));
        reflectedDirection.x = -reflectedDirection.x;

        vec3 textureColor = textureCube(uCubeMap, reflectedDirection).rgb;

        gl_FragColor = vec4(textureColor, 1.0);
      }
    `,
  });

Complete example: https://codepen.io/marianban/pen/VwPeYer?editors=0010 The sphere rotation is on the line 143 sphereGroup.rotation.x += 0.01;. It works fine if you comment it. It looks like that the reflection is not taking the sphere rotation into account.

I found several similar questions: GLSL cubemap reflection shader, Texturing Spheres with Cubemaps (not reflection maps) but unfortunately they didn't help me.

标签: three.jsglslshader

解决方案


推荐阅读