ProgressiveLightMapGPU.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import { DoubleSide, FloatType, HalfFloatType, PlaneGeometry, Mesh, RenderTarget, Scene, MeshPhongNodeMaterial, NodeMaterial } from 'three/webgpu';
  2. import { add, float, mix, output, sub, texture, uniform, uv, vec2, vec4 } from 'three/tsl';
  3. import { potpack } from '../libs/potpack.module.js';
  4. /**
  5. * Progressive Light Map Accumulator, by [zalo]{@link https://github.com/zalo/}.
  6. *
  7. * To use, simply construct a `ProgressiveLightMap` object,
  8. * `plmap.addObjectsToLightMap(object)` an array of semi-static
  9. * objects and lights to the class once, and then call
  10. * `plmap.update(camera)` every frame to begin accumulating
  11. * lighting samples.
  12. *
  13. * This should begin accumulating lightmaps which apply to
  14. * your objects, so you can start jittering lighting to achieve
  15. * the texture-space effect you're looking for.
  16. *
  17. * This class can only be used with {@link WebGPURenderer}.
  18. * When using {@link WebGLRenderer}, import from `ProgressiveLightMap.js`.
  19. *
  20. * @three_import import { ProgressiveLightMap } from 'three/addons/misc/ProgressiveLightMapGPU.js';
  21. */
  22. class ProgressiveLightMap {
  23. /**
  24. * @param {WebGPURenderer} renderer - The renderer.
  25. * @param {number} [resolution=1024] - The side-long dimension of the total lightmap.
  26. */
  27. constructor( renderer, resolution = 1024 ) {
  28. /**
  29. * The renderer.
  30. *
  31. * @type {WebGPURenderer}
  32. */
  33. this.renderer = renderer;
  34. /**
  35. * The side-long dimension of the total lightmap.
  36. *
  37. * @type {number}
  38. * @default 1024
  39. */
  40. this.resolution = resolution;
  41. this._lightMapContainers = [];
  42. this._scene = new Scene();
  43. this._buffer1Active = false;
  44. this._labelMesh = null;
  45. this._blurringPlane = null;
  46. // Create the Progressive LightMap Texture
  47. const type = /(Android|iPad|iPhone|iPod)/g.test( navigator.userAgent ) ? HalfFloatType : FloatType;
  48. this._progressiveLightMap1 = new RenderTarget( this.resolution, this.resolution, { type: type } );
  49. this._progressiveLightMap2 = new RenderTarget( this.resolution, this.resolution, { type: type } );
  50. this._progressiveLightMap2.texture.channel = 1;
  51. // uniforms
  52. this._averagingWindow = uniform( 100 );
  53. this._previousShadowMap = texture( this._progressiveLightMap1.texture );
  54. // materials
  55. const uvNode = uv( 1 ).flipY();
  56. this._uvMat = new MeshPhongNodeMaterial();
  57. this._uvMat.vertexNode = vec4( sub( uvNode, vec2( 0.5 ) ).mul( 2 ), 1, 1 );
  58. this._uvMat.outputNode = vec4( mix( this._previousShadowMap.sample( uv( 1 ) ), output, float( 1 ).div( this._averagingWindow ) ) );
  59. }
  60. /**
  61. * Sets these objects' materials' lightmaps and modifies their uv1's.
  62. *
  63. * @param {Array<Object3D>} objects - An array of objects and lights to set up your lightmap.
  64. */
  65. addObjectsToLightMap( objects ) {
  66. // Prepare list of UV bounding boxes for packing later...
  67. const uv_boxes = [];
  68. const padding = 3 / this.resolution;
  69. for ( let ob = 0; ob < objects.length; ob ++ ) {
  70. const object = objects[ ob ];
  71. // If this object is a light, simply add it to the internal scene
  72. if ( object.isLight ) {
  73. this._scene.attach( object ); continue;
  74. }
  75. if ( object.geometry.hasAttribute( 'uv' ) === false ) {
  76. console.warn( 'THREE.ProgressiveLightMap: All lightmap objects need uvs.' ); continue;
  77. }
  78. if ( this._blurringPlane === null ) {
  79. this._initializeBlurPlane();
  80. }
  81. // Apply the lightmap to the object
  82. object.material.lightMap = this._progressiveLightMap2.texture;
  83. object.material.dithering = true;
  84. object.castShadow = true;
  85. object.receiveShadow = true;
  86. object.renderOrder = 1000 + ob;
  87. // Prepare UV boxes for potpack (potpack will update x and y)
  88. // TODO: Size these by object surface area
  89. uv_boxes.push( { w: 1 + ( padding * 2 ), h: 1 + ( padding * 2 ), index: ob, x: 0, y: 0 } );
  90. this._lightMapContainers.push( { basicMat: object.material, object: object } );
  91. }
  92. // Pack the objects' lightmap UVs into the same global space
  93. const dimensions = potpack( uv_boxes );
  94. uv_boxes.forEach( ( box ) => {
  95. const uv1 = objects[ box.index ].geometry.getAttribute( 'uv' ).clone();
  96. for ( let i = 0; i < uv1.array.length; i += uv1.itemSize ) {
  97. uv1.array[ i ] = ( uv1.array[ i ] + box.x + padding ) / dimensions.w;
  98. uv1.array[ i + 1 ] = 1 - ( ( uv1.array[ i + 1 ] + box.y + padding ) / dimensions.h );
  99. }
  100. objects[ box.index ].geometry.setAttribute( 'uv1', uv1 );
  101. objects[ box.index ].geometry.getAttribute( 'uv1' ).needsUpdate = true;
  102. } );
  103. }
  104. /**
  105. * Frees all internal resources.
  106. */
  107. dispose() {
  108. this._progressiveLightMap1.dispose();
  109. this._progressiveLightMap2.dispose();
  110. this._uvMat.dispose();
  111. if ( this._blurringPlane !== null ) {
  112. this._blurringPlane.geometry.dispose();
  113. this._blurringPlane.material.dispose();
  114. }
  115. if ( this._labelMesh !== null ) {
  116. this._labelMesh.geometry.dispose();
  117. this._labelMesh.material.dispose();
  118. }
  119. }
  120. /**
  121. * This function renders each mesh one at a time into their respective surface maps.
  122. *
  123. * @param {Camera} camera - The camera the scene is rendered with.
  124. * @param {number} [blendWindow=100] - When >1, samples will accumulate over time.
  125. * @param {boolean} [blurEdges=true] - Whether to fix UV Edges via blurring.
  126. */
  127. update( camera, blendWindow = 100, blurEdges = true ) {
  128. if ( this._blurringPlane === null ) {
  129. return;
  130. }
  131. // Store the original Render Target
  132. const currentRenderTarget = this.renderer.getRenderTarget();
  133. // The blurring plane applies blur to the seams of the lightmap
  134. this._blurringPlane.visible = blurEdges;
  135. // Steal the Object3D from the real world to our special dimension
  136. for ( let l = 0; l < this._lightMapContainers.length; l ++ ) {
  137. this._lightMapContainers[ l ].object.oldScene = this._lightMapContainers[ l ].object.parent;
  138. this._scene.attach( this._lightMapContainers[ l ].object );
  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._averagingWindow.value = blendWindow;
  143. this._lightMapContainers[ l ].object.material = this._uvMat;
  144. this._lightMapContainers[ l ].object.oldFrustumCulled = this._lightMapContainers[ l ].object.frustumCulled;
  145. this._lightMapContainers[ l ].object.frustumCulled = false;
  146. }
  147. // Ping-pong two surface buffers for reading/writing
  148. const activeMap = this._buffer1Active ? this._progressiveLightMap1 : this._progressiveLightMap2;
  149. const inactiveMap = this._buffer1Active ? this._progressiveLightMap2 : this._progressiveLightMap1;
  150. // Render the object's surface maps
  151. this.renderer.setRenderTarget( activeMap );
  152. this._previousShadowMap.value = inactiveMap.texture;
  153. this._buffer1Active = ! this._buffer1Active;
  154. this.renderer.render( this._scene, camera );
  155. // Restore the object's Real-time Material and add it back to the original world
  156. for ( let l = 0; l < this._lightMapContainers.length; l ++ ) {
  157. this._lightMapContainers[ l ].object.frustumCulled = this._lightMapContainers[ l ].object.oldFrustumCulled;
  158. this._lightMapContainers[ l ].object.material = this._lightMapContainers[ l ].basicMat;
  159. this._lightMapContainers[ l ].object.oldScene.attach( this._lightMapContainers[ l ].object );
  160. }
  161. // Restore the original Render Target
  162. this.renderer.setRenderTarget( currentRenderTarget );
  163. }
  164. /**
  165. * Draws the lightmap in the main scene. Call this after adding the objects to it.
  166. *
  167. * @param {boolean} visible - Whether the debug plane should be visible
  168. * @param {Vector3} [position] - Where the debug plane should be drawn
  169. */
  170. showDebugLightmap( visible, position = null ) {
  171. if ( this._lightMapContainers.length === 0 ) {
  172. console.warn( 'THREE.ProgressiveLightMap: Call .showDebugLightmap() after adding the objects.' );
  173. return;
  174. }
  175. if ( this._labelMesh === null ) {
  176. const labelMaterial = new NodeMaterial();
  177. labelMaterial.colorNode = texture( this._progressiveLightMap1.texture ).sample( uv().flipY() );
  178. labelMaterial.side = DoubleSide;
  179. const labelGeometry = new PlaneGeometry( 100, 100 );
  180. this._labelMesh = new Mesh( labelGeometry, labelMaterial );
  181. this._labelMesh.position.y = 250;
  182. this._lightMapContainers[ 0 ].object.parent.add( this._labelMesh );
  183. }
  184. if ( position !== null ) {
  185. this._labelMesh.position.copy( position );
  186. }
  187. this._labelMesh.visible = visible;
  188. }
  189. /**
  190. * Creates the Blurring Plane.
  191. *
  192. * @private
  193. */
  194. _initializeBlurPlane() {
  195. const blurMaterial = new NodeMaterial();
  196. blurMaterial.polygonOffset = true;
  197. blurMaterial.polygonOffsetFactor = - 1;
  198. blurMaterial.polygonOffsetUnits = 3;
  199. blurMaterial.vertexNode = vec4( sub( uv(), vec2( 0.5 ) ).mul( 2 ), 1, 1 );
  200. const uvNode = uv().flipY().toVar();
  201. const pixelOffset = float( 0.5 ).div( float( this.resolution ) ).toVar();
  202. const color = add(
  203. this._previousShadowMap.sample( uvNode.add( vec2( pixelOffset, 0 ) ) ),
  204. this._previousShadowMap.sample( uvNode.add( vec2( 0, pixelOffset ) ) ),
  205. this._previousShadowMap.sample( uvNode.add( vec2( 0, pixelOffset.negate() ) ) ),
  206. this._previousShadowMap.sample( uvNode.add( vec2( pixelOffset.negate(), 0 ) ) ),
  207. this._previousShadowMap.sample( uvNode.add( vec2( pixelOffset, pixelOffset ) ) ),
  208. this._previousShadowMap.sample( uvNode.add( vec2( pixelOffset.negate(), pixelOffset ) ) ),
  209. this._previousShadowMap.sample( uvNode.add( vec2( pixelOffset, pixelOffset.negate() ) ) ),
  210. this._previousShadowMap.sample( uvNode.add( vec2( pixelOffset.negate(), pixelOffset.negate() ) ) ),
  211. ).div( 8 );
  212. blurMaterial.fragmentNode = color;
  213. this._blurringPlane = new Mesh( new PlaneGeometry( 1, 1 ), blurMaterial );
  214. this._blurringPlane.name = 'Blurring Plane';
  215. this._blurringPlane.frustumCulled = false;
  216. this._blurringPlane.renderOrder = 0;
  217. this._blurringPlane.material.depthWrite = false;
  218. this._scene.add( this._blurringPlane );
  219. }
  220. }
  221. export { ProgressiveLightMap };