ProgressiveLightMap.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { DoubleSide, FloatType, HalfFloatType, Mesh, MeshBasicMaterial, MeshPhongMaterial, PlaneGeometry, Scene, WebGLRenderTarget } 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 An instance of WebGLRenderer.
  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.scene = new Scene();
  25. this.buffer1Active = false;
  26. this.firstUpdate = true;
  27. this.labelMesh = null;
  28. this.blurringPlane = null;
  29. // Create the Progressive LightMap Texture
  30. const format = /(Android|iPad|iPhone|iPod)/g.test( navigator.userAgent ) ? HalfFloatType : FloatType;
  31. this.progressiveLightMap1 = new WebGLRenderTarget( this.res, this.res, { type: format } );
  32. this.progressiveLightMap2 = new WebGLRenderTarget( this.res, this.res, { type: format } );
  33. this.progressiveLightMap2.texture.channel = 1;
  34. // Inject some spicy new logic into a standard phong material
  35. this.uvMat = new MeshPhongMaterial();
  36. this.uvMat.uniforms = {};
  37. this.uvMat.onBeforeCompile = ( shader ) => {
  38. // Vertex Shader: Set Vertex Positions to the Unwrapped UV Positions
  39. shader.vertexShader =
  40. 'attribute vec2 uv1;\n' +
  41. '#define USE_LIGHTMAP\n' +
  42. '#define LIGHTMAP_UV uv1\n' +
  43. shader.vertexShader.slice( 0, - 1 ) +
  44. ' gl_Position = vec4((LIGHTMAP_UV - 0.5) * 2.0, 1.0, 1.0); }';
  45. // Fragment Shader: Set Pixels to average in the Previous frame's Shadows
  46. const bodyStart = shader.fragmentShader.indexOf( 'void main() {' );
  47. shader.fragmentShader =
  48. '#define USE_LIGHTMAP\n' +
  49. shader.fragmentShader.slice( 0, bodyStart ) +
  50. ' uniform sampler2D previousShadowMap;\n uniform float averagingWindow;\n' +
  51. shader.fragmentShader.slice( bodyStart - 1, - 1 ) +
  52. `\nvec3 texelOld = texture2D(previousShadowMap, vLightMapUv).rgb;
  53. gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/averagingWindow);
  54. }`;
  55. // Set the Previous Frame's Texture Buffer and Averaging Window
  56. shader.uniforms.previousShadowMap = { value: this.progressiveLightMap1.texture };
  57. shader.uniforms.averagingWindow = { value: 100 };
  58. this.uvMat.uniforms = shader.uniforms;
  59. // Set the new Shader to this
  60. this.uvMat.userData.shader = shader;
  61. };
  62. }
  63. /**
  64. * Sets these objects' materials' lightmaps and modifies their uv1'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' ) === false ) {
  77. console.warn( 'THREE.ProgressiveLightMap: 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. }
  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 uv1 = objects[ box.index ].geometry.getAttribute( 'uv' ).clone();
  98. for ( let i = 0; i < uv1.array.length; i += uv1.itemSize ) {
  99. uv1.array[ i ] = ( uv1.array[ i ] + box.x + padding ) / dimensions.w;
  100. uv1.array[ i + 1 ] = ( uv1.array[ i + 1 ] + box.y + padding ) / dimensions.h;
  101. }
  102. objects[ box.index ].geometry.setAttribute( 'uv1', uv1 );
  103. objects[ box.index ].geometry.getAttribute( 'uv1' ).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. }
  116. // Store the original Render Target
  117. const oldTarget = this.renderer.getRenderTarget();
  118. // The blurring plane applies blur to the seams of the lightmap
  119. this.blurringPlane.visible = blurEdges;
  120. // Steal the Object3D from the real world to our special dimension
  121. for ( let l = 0; l < this.lightMapContainers.length; l ++ ) {
  122. this.lightMapContainers[ l ].object.oldScene =
  123. this.lightMapContainers[ l ].object.parent;
  124. this.scene.attach( this.lightMapContainers[ l ].object );
  125. }
  126. // Initialize everything
  127. if ( this.firstUpdate === true ) {
  128. this.renderer.compile( this.scene, camera );
  129. this.firstUpdate = false;
  130. }
  131. // Set each object's material to the UV Unwrapped Surface Mapping Version
  132. for ( let l = 0; l < this.lightMapContainers.length; l ++ ) {
  133. this.uvMat.uniforms.averagingWindow = { value: blendWindow };
  134. this.lightMapContainers[ l ].object.material = this.uvMat;
  135. this.lightMapContainers[ l ].object.oldFrustumCulled =
  136. this.lightMapContainers[ l ].object.frustumCulled;
  137. this.lightMapContainers[ l ].object.frustumCulled = false;
  138. }
  139. // Ping-pong two surface buffers for reading/writing
  140. const activeMap = this.buffer1Active ? this.progressiveLightMap1 : this.progressiveLightMap2;
  141. const inactiveMap = this.buffer1Active ? this.progressiveLightMap2 : this.progressiveLightMap1;
  142. // Render the object's surface maps
  143. this.renderer.setRenderTarget( activeMap );
  144. this.uvMat.uniforms.previousShadowMap = { value: inactiveMap.texture };
  145. this.blurringPlane.material.uniforms.previousShadowMap = { value: inactiveMap.texture };
  146. this.buffer1Active = ! this.buffer1Active;
  147. this.renderer.render( this.scene, camera );
  148. // Restore the object's Real-time Material and add it back to the original world
  149. for ( let l = 0; l < this.lightMapContainers.length; l ++ ) {
  150. this.lightMapContainers[ l ].object.frustumCulled =
  151. this.lightMapContainers[ l ].object.oldFrustumCulled;
  152. this.lightMapContainers[ l ].object.material = this.lightMapContainers[ l ].basicMat;
  153. this.lightMapContainers[ l ].object.oldScene.attach( this.lightMapContainers[ l ].object );
  154. }
  155. // Restore the original Render Target
  156. this.renderer.setRenderTarget( oldTarget );
  157. }
  158. /** DEBUG
  159. * Draw the lightmap in the main scene. Call this after adding the objects to it.
  160. * @param {boolean} visible Whether the debug plane should be visible
  161. * @param {Vector3} position Where the debug plane should be drawn
  162. */
  163. showDebugLightmap( visible, position = undefined ) {
  164. if ( this.lightMapContainers.length === 0 ) {
  165. console.warn( 'THREE.ProgressiveLightMap: Call .showDebugLightmap() after adding the objects.' );
  166. return;
  167. }
  168. if ( this.labelMesh === null ) {
  169. const labelMaterial = new MeshBasicMaterial( { map: this.progressiveLightMap1.texture, side: DoubleSide } );
  170. const labelGeometry = new PlaneGeometry( 100, 100 );
  171. this.labelMesh = new Mesh( labelGeometry, labelMaterial );
  172. this.labelMesh.position.y = 250;
  173. this.lightMapContainers[ 0 ].object.parent.add( this.labelMesh );
  174. }
  175. if ( position !== undefined ) {
  176. this.labelMesh.position.copy( position );
  177. }
  178. this.labelMesh.visible = visible;
  179. }
  180. /**
  181. * INTERNAL Creates the Blurring Plane
  182. * @param {number} res The square resolution of this object's lightMap.
  183. * @param {WebGLRenderTexture} lightMap The lightmap to initialize the plane with.
  184. */
  185. _initializeBlurPlane( res, lightMap = null ) {
  186. const blurMaterial = new MeshBasicMaterial();
  187. blurMaterial.uniforms = { previousShadowMap: { value: null },
  188. pixelOffset: { value: 1.0 / res },
  189. polygonOffset: true, polygonOffsetFactor: - 1, polygonOffsetUnits: 3.0 };
  190. blurMaterial.onBeforeCompile = ( shader ) => {
  191. // Vertex Shader: Set Vertex Positions to the Unwrapped UV Positions
  192. shader.vertexShader =
  193. '#define USE_UV\n' +
  194. shader.vertexShader.slice( 0, - 1 ) +
  195. ' gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }';
  196. // Fragment Shader: Set Pixels to 9-tap box blur the current frame's Shadows
  197. const bodyStart = shader.fragmentShader.indexOf( 'void main() {' );
  198. shader.fragmentShader =
  199. '#define USE_UV\n' +
  200. shader.fragmentShader.slice( 0, bodyStart ) +
  201. ' uniform sampler2D previousShadowMap;\n uniform float pixelOffset;\n' +
  202. shader.fragmentShader.slice( bodyStart - 1, - 1 ) +
  203. ` 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. }`;
  213. // Set the LightMap Accumulation Buffer
  214. shader.uniforms.previousShadowMap = { value: lightMap.texture };
  215. shader.uniforms.pixelOffset = { value: 0.5 / res };
  216. blurMaterial.uniforms = shader.uniforms;
  217. // Set the new Shader to this
  218. blurMaterial.userData.shader = shader;
  219. };
  220. this.blurringPlane = new Mesh( new PlaneGeometry( 1, 1 ), blurMaterial );
  221. this.blurringPlane.name = 'Blurring Plane';
  222. this.blurringPlane.frustumCulled = false;
  223. this.blurringPlane.renderOrder = 0;
  224. this.blurringPlane.material.depthWrite = false;
  225. this.scene.add( this.blurringPlane );
  226. }
  227. /**
  228. * Frees all internal resources.
  229. */
  230. dispose() {
  231. this.progressiveLightMap1.dispose();
  232. this.progressiveLightMap2.dispose();
  233. this.uvMat.dispose();
  234. if ( this.blurringPlane !== null ) {
  235. this.blurringPlane.geometry.dispose();
  236. this.blurringPlane.material.dispose();
  237. }
  238. if ( this.labelMesh !== null ) {
  239. this.labelMesh.geometry.dispose();
  240. this.labelMesh.material.dispose();
  241. }
  242. }
  243. }
  244. export { ProgressiveLightMap };
粤ICP备19079148号