ShadowMesh.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import {
  2. Matrix4,
  3. Mesh,
  4. MeshBasicMaterial
  5. } from '../../../build/three.module.js';
  6. /**
  7. * A shadow Mesh that follows a shadow-casting Mesh in the scene, but is confined to a single plane.
  8. */
  9. const _shadowMatrix = new Matrix4();
  10. class ShadowMesh extends Mesh {
  11. constructor( mesh ) {
  12. const shadowMaterial = new MeshBasicMaterial( {
  13. color: 0x000000,
  14. transparent: true,
  15. opacity: 0.6,
  16. depthWrite: false
  17. } );
  18. super( mesh.geometry, shadowMaterial );
  19. this.meshMatrix = mesh.matrixWorld;
  20. this.frustumCulled = false;
  21. this.matrixAutoUpdate = false;
  22. }
  23. update( plane, lightPosition4D ) {
  24. // based on https://www.opengl.org/archives/resources/features/StencilTalk/tsld021.htm
  25. const dot = plane.normal.x * lightPosition4D.x +
  26. plane.normal.y * lightPosition4D.y +
  27. plane.normal.z * lightPosition4D.z +
  28. - plane.constant * lightPosition4D.w;
  29. const sme = _shadowMatrix.elements;
  30. sme[ 0 ] = dot - lightPosition4D.x * plane.normal.x;
  31. sme[ 4 ] = - lightPosition4D.x * plane.normal.y;
  32. sme[ 8 ] = - lightPosition4D.x * plane.normal.z;
  33. sme[ 12 ] = - lightPosition4D.x * - plane.constant;
  34. sme[ 1 ] = - lightPosition4D.y * plane.normal.x;
  35. sme[ 5 ] = dot - lightPosition4D.y * plane.normal.y;
  36. sme[ 9 ] = - lightPosition4D.y * plane.normal.z;
  37. sme[ 13 ] = - lightPosition4D.y * - plane.constant;
  38. sme[ 2 ] = - lightPosition4D.z * plane.normal.x;
  39. sme[ 6 ] = - lightPosition4D.z * plane.normal.y;
  40. sme[ 10 ] = dot - lightPosition4D.z * plane.normal.z;
  41. sme[ 14 ] = - lightPosition4D.z * - plane.constant;
  42. sme[ 3 ] = - lightPosition4D.w * plane.normal.x;
  43. sme[ 7 ] = - lightPosition4D.w * plane.normal.y;
  44. sme[ 11 ] = - lightPosition4D.w * plane.normal.z;
  45. sme[ 15 ] = dot - lightPosition4D.w * - plane.constant;
  46. this.matrix.multiplyMatrices( _shadowMatrix, this.meshMatrix );
  47. }
  48. }
  49. ShadowMesh.prototype.isShadowMesh = true;
  50. export { ShadowMesh };