ProgressiveLightMap.js 11 KB

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