Threejs 渲染阴影流程

效果展示

首先我们通过创建场景,为场景添加1个平行光,1个平面,1 个球体;并渲染带阴影的场景。

ini 复制代码
const settings = {
  cameraX: 6,
  cameraY: 12,
  posX: -3.5,
  posY: 7.5,
  posZ: 5.0,
  targetX: 3.5,
  targetY: 0,
  targetZ: 3.5,
  projWidth: 10,
  projHeight: 10,
  perspective: false,
  fieldOfView: 120,
  bias: -0.006
};

export function DirectionLightShadowInThree(canvas: HTMLCanvasElement) {

  const { width, height } = canvas.getBoundingClientRect();

  const aspect = width / height;

  const scene = new Scene();

  const renderer = new WebGL1Renderer({
    canvas
  });
  renderer.shadowMap.enabled = true;
  renderer.outputColorSpace = LinearSRGBColorSpace;
  // renderer.shadowMap.type = PCFSoftShadowMap;
  // renderer.outputEncoding = THREE.sRGBEncoding;
  // 这个开启才会渲染阴影贴图
    // 创建一个数字纹理
    const data = new Uint8Array([  // data
      0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC,
      0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF,
      0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC,
      0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF,
      0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC,
      0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF,
      0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC,
      0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF,
    ]);
    
    // const dataTexture = new DataTexture(data, 8, 8, LuminanceFormat, UnsignedByteType)
  
    // dataTexture.needsUpdate = true;
    // create a buffer with color data
  
  const _width = 8;
  const _height = 8;
  
  const camera = new PerspectiveCamera(60, aspect, 1, 2000);
  camera.position.set(
    settings.cameraX,
    settings.cameraY,
    15
  );
  camera.lookAt(new Vector3())
  // // used the buffer to create a DataTexture
  
  const texture = new DataTexture( data, _width, _height, LuminanceFormat, UnsignedByteType);
  // texture.mipmaps = [texture]
  texture.needsUpdate = true;


  const dirLight = new DirectionalLight();
  dirLight.castShadow = true;
  dirLight.target.position.set( 0, 0, 0 );

  // const lighthelper = new DirectionalLightHelper(dirLight);
  const planeMat = new MeshPhongMaterial({
    map: texture,
    color: new Color(0.5, 0.5, 1)
  });
  const sphereMat = new MeshPhongMaterial({
    map: texture,
    color: new Color(1, 0.5, 0.5)
  });

  const sphereGeometry = new SphereGeometry(1, 32, 24);
  
  const planeGeo = new PlaneGeometry(20, 20);

  dirLight.position.set(settings.posX, settings.posY, settings.posZ);

  dirLight.lookAt(new Vector3())

  const plane = new Mesh(planeGeo, planeMat);

  plane.receiveShadow = true;
  
  plane.rotation.x = - 0.5 * Math.PI;
  
  const sphere = new Mesh(sphereGeometry, sphereMat);

  sphere.castShadow = true;
  sphere.position.set(2, 3, 4);
  // sphere.updateMatrixWorld();
  scene.add(plane)

  scene.add(dirLight)
  scene.add(sphere)

  renderer.render(scene, camera);



}

threejs 渲染阴影的前置条件是

  1. 开启渲染器的阴影贴图 就是 renderer.shadowMap.enabled = true;
  2. 对需要投身阴影的模型设置 castShadow 属性为 true
  3. 对需要能产生阴影的光设置 castShadow 属性为 true
  4. 需要接收阴影的模型设置 receiveShadow 属性为 true

最终效果如下图所示

Threejs 是如何产生模型阴影的

  1. 根据灯光信息,渲染阴影贴图

1.1 首先记录能产生阴影的灯光

csharp 复制代码
// projectObject 函数内会有这样一段,处理灯光

if ( object.isLight ) {

        currentRenderState.pushLight( object );

        if ( object.castShadow ) {

                currentRenderState.pushShadow( object );

        }

}

1.2 根据灯光 执行WebGLShadowMap 的render 渲染阴影贴图 // 渲染灯光下的深度信息 // 渲染了尝试贴图后 shadowMap.render( shadowsArray, scene, camera );

以示例代码说明,此处用的是平行光。会在DirectilnalLightShadow 中保存渲染后的阴影深度信息(就是通过 WebGLRenderTarget 记录纹理,结合 MeshDepthMaterial)。

1.3 将贴图信息写入着色器中,供后面生成程序时用

在 setupLights 方法中会将相应光的贴图信息写入WebGLUniforms 中,后面传入着色器内。

ini 复制代码
if ( light.isDirectionalLight ) {
// 平行光
const uniforms = cache.get( light );

uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );

if ( light.castShadow ) {

        const shadow = light.shadow;

        const shadowUniforms = shadowCache.get( light );

        shadowUniforms.shadowBias = shadow.bias;
        shadowUniforms.shadowNormalBias = shadow.normalBias;
        shadowUniforms.shadowRadius = shadow.radius;
        shadowUniforms.shadowMapSize = shadow.mapSize;

        state.directionalShadow[ directionalLength ] = shadowUniforms;
        state.directionalShadowMap[ directionalLength ] = shadowMap;
        state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;

        numDirectionalShadows ++;

}

state.directional[ directionalLength ] = uniforms;

directionalLength ++;

}

src/renderers/shaders/shaderChunk/shadowmap_pars_vertext.glsl

定义

ini 复制代码
    // 灯光的模型矩阵
    uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
    varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];

src/renderers/shaders/shaderChunk/shadowmap_vertext.glsl 计算阴影纹理坐标

ini 复制代码
#if NUM_DIR_LIGHT_SHADOWS > 0

#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
   // worldPosition 模型的 position
   shadowWorldPosition = worldPosition + 
   vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
   
   vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;

}
       

src/renderers/shaders/shaderChunk/shadowmap_pars_fragment.glsl 定义变量

ini 复制代码
   
    // 获取深度贴图
    uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
    // 贴图纹理坐标
    varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
    

src/renderers/shaders/shaderChunk/lights_fragment_begin.glsl 中调用 getShadow 获取阴影信息

ini 复制代码
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )

 DirectionalLight directionalLight;
 #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
 DirectionalLightShadow directionalLightShadow;
 #endif

 #pragma unroll_loop_start
 for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {

 	directionalLight = directionalLights[ i ];

 	getDirectionalLightInfo( directionalLight, geometry, directLight );

 	#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
 	directionalLightShadow = directionalLightShadows[ i ];
 	directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) 
 		? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) 
 		: 1.0;
 	#endif

 	RE_Direct( directLight, geometry, material, reflectedLight );

 }
相关推荐
患得患失94928 分钟前
【前端】【vscode】【.vscode/settings.json】为单个项目配置自动格式化和开发环境
前端·vscode·json
飛_31 分钟前
解决VSCode无法加载Json架构问题
java·服务器·前端
YGY Webgis糕手之路3 小时前
OpenLayers 综合案例-轨迹回放
前端·经验分享·笔记·vue·web
90后的晨仔3 小时前
🚨XSS 攻击全解:什么是跨站脚本攻击?前端如何防御?
前端·vue.js
Ares-Wang3 小时前
JavaScript》》JS》 Var、Let、Const 大总结
开发语言·前端·javascript
90后的晨仔3 小时前
Vue 模板语法完全指南:从插值表达式到动态指令,彻底搞懂 Vue 模板语言
前端·vue.js
德育处主任4 小时前
p5.js 正方形square的基础用法
前端·数据可视化·canvas
烛阴4 小时前
Mix - Bilinear Interpolation
前端·webgl
90后的晨仔4 小时前
Vue 3 应用实例详解:从 createApp 到 mount,你真正掌握了吗?
前端·vue.js
德育处主任4 小时前
p5.js 矩形rect绘制教程
前端·数据可视化·canvas