ShadowMesh.js 2.0 KB

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