ProgressiveLightMap.js 11 KB

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