ProgressiveLightMap.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. ( function () {
  2. /**
  3. * Progressive Light Map Accumulator, by [zalo](https://github.com/zalo/)
  4. *
  5. * To use, simply construct a `ProgressiveLightMap` object,
  6. * `plmap.addObjectsToLightMap(object)` an array of semi-static
  7. * objects and lights to the class once, and then call
  8. * `plmap.update(camera)` every frame to begin accumulating
  9. * lighting samples.
  10. *
  11. * This should begin accumulating lightmaps which apply to
  12. * your objects, so you can start jittering lighting to achieve
  13. * the texture-space effect you're looking for.
  14. *
  15. * @param {WebGLRenderer} renderer A WebGL Rendering Context
  16. * @param {number} res The side-long dimension of you total lightmap
  17. */
  18. class ProgressiveLightMap {
  19. constructor( renderer, res = 1024 ) {
  20. this.renderer = renderer;
  21. this.res = res;
  22. this.lightMapContainers = [];
  23. this.compiled = false;
  24. this.scene = new THREE.Scene();
  25. this.scene.background = null;
  26. this.tinyTarget = new THREE.WebGLRenderTarget( 1, 1 );
  27. this.buffer1Active = false;
  28. this.firstUpdate = true;
  29. this.warned = false; // Create the Progressive LightMap Texture
  30. const format = /(Android|iPad|iPhone|iPod)/g.test( navigator.userAgent ) ? THREE.HalfFloatType : THREE.FloatType;
  31. this.progressiveLightMap1 = new THREE.WebGLRenderTarget( this.res, this.res, {
  32. type: format
  33. } );
  34. this.progressiveLightMap2 = new THREE.WebGLRenderTarget( this.res, this.res, {
  35. type: format
  36. } ); // Inject some spicy new logic into a standard phong material
  37. this.uvMat = new THREE.MeshPhongMaterial();
  38. this.uvMat.uniforms = {};
  39. this.uvMat.onBeforeCompile = shader => {
  40. // Vertex Shader: Set Vertex Positions to the Unwrapped UV Positions
  41. shader.vertexShader = '#define USE_LIGHTMAP\n' + shader.vertexShader.slice( 0, - 1 ) + ' gl_Position = vec4((uv2 - 0.5) * 2.0, 1.0, 1.0); }'; // Fragment Shader: Set Pixels to average in the Previous frame's Shadows
  42. const bodyStart = shader.fragmentShader.indexOf( 'void main() {' );
  43. shader.fragmentShader = 'varying vec2 vUv2;\n' + shader.fragmentShader.slice( 0, bodyStart ) + ' uniform sampler2D previousShadowMap;\n uniform float averagingWindow;\n' + shader.fragmentShader.slice( bodyStart - 1, - 1 ) + `\nvec3 texelOld = texture2D(previousShadowMap, vUv2).rgb;
  44. gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/averagingWindow);
  45. }`; // Set the Previous Frame's Texture Buffer and Averaging Window
  46. shader.uniforms.previousShadowMap = {
  47. value: this.progressiveLightMap1.texture
  48. };
  49. shader.uniforms.averagingWindow = {
  50. value: 100
  51. };
  52. this.uvMat.uniforms = shader.uniforms; // Set the new Shader to this
  53. this.uvMat.userData.shader = shader;
  54. this.compiled = true;
  55. };
  56. }
  57. /**
  58. * Sets these objects' materials' lightmaps and modifies their uv2's.
  59. * @param {Object3D} objects An array of objects and lights to set up your lightmap.
  60. */
  61. addObjectsToLightMap( objects ) {
  62. // Prepare list of UV bounding boxes for packing later...
  63. this.uv_boxes = [];
  64. const padding = 3 / this.res;
  65. for ( let ob = 0; ob < objects.length; ob ++ ) {
  66. const object = objects[ ob ]; // If this object is a light, simply add it to the internal scene
  67. if ( object.isLight ) {
  68. this.scene.attach( object );
  69. continue;
  70. }
  71. if ( ! object.geometry.hasAttribute( 'uv' ) ) {
  72. console.warn( 'All lightmap objects need UVs!' );
  73. continue;
  74. }
  75. if ( this.blurringPlane == null ) {
  76. this._initializeBlurPlane( this.res, this.progressiveLightMap1 );
  77. } // Apply the lightmap to the object
  78. object.material.lightMap = this.progressiveLightMap2.texture;
  79. object.material.dithering = true;
  80. object.castShadow = true;
  81. object.receiveShadow = true;
  82. object.renderOrder = 1000 + ob; // Prepare UV boxes for potpack
  83. // TODO: Size these by object surface area
  84. this.uv_boxes.push( {
  85. w: 1 + padding * 2,
  86. h: 1 + padding * 2,
  87. index: ob
  88. } );
  89. this.lightMapContainers.push( {
  90. basicMat: object.material,
  91. object: object
  92. } );
  93. this.compiled = false;
  94. } // Pack the objects' lightmap UVs into the same global space
  95. const dimensions = potpack( this.uv_boxes );
  96. this.uv_boxes.forEach( box => {
  97. const uv2 = objects[ box.index ].geometry.getAttribute( 'uv' ).clone();
  98. for ( let i = 0; i < uv2.array.length; i += uv2.itemSize ) {
  99. uv2.array[ i ] = ( uv2.array[ i ] + box.x + padding ) / dimensions.w;
  100. uv2.array[ i + 1 ] = ( uv2.array[ i + 1 ] + box.y + padding ) / dimensions.h;
  101. }
  102. objects[ box.index ].geometry.setAttribute( 'uv2', uv2 );
  103. objects[ box.index ].geometry.getAttribute( 'uv2' ).needsUpdate = true;
  104. } );
  105. }
  106. /**
  107. * This function renders each mesh one at a time into their respective surface maps
  108. * @param {Camera} camera Standard Rendering Camera
  109. * @param {number} blendWindow When >1, samples will accumulate over time.
  110. * @param {boolean} blurEdges Whether to fix UV Edges via blurring
  111. */
  112. update( camera, blendWindow = 100, blurEdges = true ) {
  113. if ( this.blurringPlane == null ) {
  114. return;
  115. } // Store the original Render Target
  116. const oldTarget = this.renderer.getRenderTarget(); // The blurring plane applies blur to the seams of the lightmap
  117. this.blurringPlane.visible = blurEdges; // Steal the Object3D from the real world to our special dimension
  118. for ( let l = 0; l < this.lightMapContainers.length; l ++ ) {
  119. this.lightMapContainers[ l ].object.oldScene = this.lightMapContainers[ l ].object.parent;
  120. this.scene.attach( this.lightMapContainers[ l ].object );
  121. } // Render once normally to initialize everything
  122. if ( this.firstUpdate ) {
  123. this.renderer.setRenderTarget( this.tinyTarget ); // Tiny for Speed
  124. this.renderer.render( this.scene, camera );
  125. this.firstUpdate = false;
  126. } // Set each object's material to the UV Unwrapped Surface Mapping Version
  127. for ( let l = 0; l < this.lightMapContainers.length; l ++ ) {
  128. this.uvMat.uniforms.averagingWindow = {
  129. value: blendWindow
  130. };
  131. this.lightMapContainers[ l ].object.material = this.uvMat;
  132. this.lightMapContainers[ l ].object.oldFrustumCulled = this.lightMapContainers[ l ].object.frustumCulled;
  133. this.lightMapContainers[ l ].object.frustumCulled = false;
  134. } // Ping-pong two surface buffers for reading/writing
  135. const activeMap = this.buffer1Active ? this.progressiveLightMap1 : this.progressiveLightMap2;
  136. const inactiveMap = this.buffer1Active ? this.progressiveLightMap2 : this.progressiveLightMap1; // Render the object's surface maps
  137. this.renderer.setRenderTarget( activeMap );
  138. this.uvMat.uniforms.previousShadowMap = {
  139. value: inactiveMap.texture
  140. };
  141. this.blurringPlane.material.uniforms.previousShadowMap = {
  142. value: inactiveMap.texture
  143. };
  144. this.buffer1Active = ! this.buffer1Active;
  145. this.renderer.render( this.scene, camera ); // Restore the object's Real-time Material and add it back to the original world
  146. for ( let l = 0; l < this.lightMapContainers.length; l ++ ) {
  147. this.lightMapContainers[ l ].object.frustumCulled = this.lightMapContainers[ l ].object.oldFrustumCulled;
  148. this.lightMapContainers[ l ].object.material = this.lightMapContainers[ l ].basicMat;
  149. this.lightMapContainers[ l ].object.oldScene.attach( this.lightMapContainers[ l ].object );
  150. } // Restore the original Render Target
  151. this.renderer.setRenderTarget( oldTarget );
  152. }
  153. /** DEBUG
  154. * Draw the lightmap in the main scene. Call this after adding the objects to it.
  155. * @param {boolean} visible Whether the debug plane should be visible
  156. * @param {Vector3} position Where the debug plane should be drawn
  157. */
  158. showDebugLightmap( visible, position = undefined ) {
  159. if ( this.lightMapContainers.length == 0 ) {
  160. if ( ! this.warned ) {
  161. console.warn( 'Call this after adding the objects!' );
  162. this.warned = true;
  163. }
  164. return;
  165. }
  166. if ( this.labelMesh == null ) {
  167. this.labelMaterial = new THREE.MeshBasicMaterial( {
  168. map: this.progressiveLightMap1.texture,
  169. side: THREE.DoubleSide
  170. } );
  171. this.labelPlane = new THREE.PlaneGeometry( 100, 100 );
  172. this.labelMesh = new THREE.Mesh( this.labelPlane, this.labelMaterial );
  173. this.labelMesh.position.y = 250;
  174. this.lightMapContainers[ 0 ].object.parent.add( this.labelMesh );
  175. }
  176. if ( position != undefined ) {
  177. this.labelMesh.position.copy( position );
  178. }
  179. this.labelMesh.visible = visible;
  180. }
  181. /**
  182. * INTERNAL Creates the Blurring Plane
  183. * @param {number} res The square resolution of this object's lightMap.
  184. * @param {WebGLRenderTexture} lightMap The lightmap to initialize the plane with.
  185. */
  186. _initializeBlurPlane( res, lightMap = null ) {
  187. const blurMaterial = new THREE.MeshBasicMaterial();
  188. blurMaterial.uniforms = {
  189. previousShadowMap: {
  190. value: null
  191. },
  192. pixelOffset: {
  193. value: 1.0 / res
  194. },
  195. polygonOffset: true,
  196. polygonOffsetFactor: - 1,
  197. polygonOffsetUnits: 3.0
  198. };
  199. blurMaterial.onBeforeCompile = shader => {
  200. // Vertex Shader: Set Vertex Positions to the Unwrapped UV Positions
  201. shader.vertexShader = '#define USE_UV\n' + shader.vertexShader.slice( 0, - 1 ) + ' gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }'; // Fragment Shader: Set Pixels to 9-tap box blur the current frame's Shadows
  202. const bodyStart = shader.fragmentShader.indexOf( 'void main() {' );
  203. shader.fragmentShader = '#define USE_UV\n' + shader.fragmentShader.slice( 0, bodyStart ) + ' uniform sampler2D previousShadowMap;\n uniform float pixelOffset;\n' + shader.fragmentShader.slice( bodyStart - 1, - 1 ) + ` gl_FragColor.rgb = (
  204. texture2D(previousShadowMap, vUv + vec2( pixelOffset, 0.0 )).rgb +
  205. texture2D(previousShadowMap, vUv + vec2( 0.0 , pixelOffset)).rgb +
  206. texture2D(previousShadowMap, vUv + vec2( 0.0 , -pixelOffset)).rgb +
  207. texture2D(previousShadowMap, vUv + vec2(-pixelOffset, 0.0 )).rgb +
  208. texture2D(previousShadowMap, vUv + vec2( pixelOffset, pixelOffset)).rgb +
  209. texture2D(previousShadowMap, vUv + vec2(-pixelOffset, pixelOffset)).rgb +
  210. texture2D(previousShadowMap, vUv + vec2( pixelOffset, -pixelOffset)).rgb +
  211. texture2D(previousShadowMap, vUv + vec2(-pixelOffset, -pixelOffset)).rgb)/8.0;
  212. }`; // Set the LightMap Accumulation Buffer
  213. shader.uniforms.previousShadowMap = {
  214. value: lightMap.texture
  215. };
  216. shader.uniforms.pixelOffset = {
  217. value: 0.5 / res
  218. };
  219. blurMaterial.uniforms = shader.uniforms; // Set the new Shader to this
  220. blurMaterial.userData.shader = shader;
  221. this.compiled = true;
  222. };
  223. this.blurringPlane = new THREE.Mesh( new THREE.PlaneBufferGeometry( 1, 1 ), blurMaterial );
  224. this.blurringPlane.name = 'Blurring Plane';
  225. this.blurringPlane.frustumCulled = false;
  226. this.blurringPlane.renderOrder = 0;
  227. this.blurringPlane.material.depthWrite = false;
  228. this.scene.add( this.blurringPlane );
  229. }
  230. }
  231. THREE.ProgressiveLightMap = ProgressiveLightMap;
  232. } )();