ProgressiveLightMap.js 11 KB

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