ProgressiveLightMapGPU.js 9.6 KB

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