0
0

ProgressiveLightMap.js 11 KB

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