threepipe
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

GBufferPlugin.ts 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. import {
  2. BufferGeometry,
  3. Camera,
  4. Color,
  5. DepthTexture,
  6. DoubleSide,
  7. FloatType,
  8. GLSL1,
  9. GLSL3,
  10. IUniform,
  11. NoBlending,
  12. NormalMapTypes,
  13. Object3D,
  14. Scene,
  15. ShaderMaterialParameters,
  16. TangentSpaceNormalMap,
  17. Texture,
  18. TextureDataType,
  19. UniformsLib,
  20. UniformsUtils,
  21. UnsignedByteType,
  22. UnsignedIntType,
  23. UnsignedShortType,
  24. Vector2,
  25. Vector4,
  26. WebGLMultipleRenderTargets,
  27. WebGLRenderer,
  28. WebGLRenderTarget,
  29. } from 'three'
  30. import {GBufferRenderPass} from '../../postprocessing'
  31. import {ThreeViewer} from '../../viewer'
  32. import {MaterialExtension, updateMaterialDefines} from '../../materials'
  33. import {PipelinePassPlugin} from '../base/PipelinePassPlugin'
  34. import {uiFolderContainer, uiImage} from 'uiconfig.js'
  35. import {shaderReplaceString} from '../../utils'
  36. import GBufferUnpack from './shaders/GBufferPlugin.unpack.glsl'
  37. import GBufferMatVert from './shaders/GBufferPlugin.mat.vert.glsl'
  38. import GBufferMatFrag from './shaders/GBufferPlugin.mat.frag.glsl'
  39. import {
  40. ICamera,
  41. IMaterial,
  42. IMaterialParameters,
  43. IRenderManager,
  44. IScene,
  45. ITexture,
  46. PhysicalMaterial,
  47. ShaderMaterial2,
  48. } from '../../core'
  49. export type GBufferPluginEventTypes = ''
  50. type GBufferPluginTarget = WebGLMultipleRenderTargets | WebGLRenderTarget
  51. // export type GBufferPluginTarget = WebGLRenderTarget
  52. export type GBufferPluginPass = GBufferRenderPass<'gbuffer', GBufferPluginTarget>
  53. export interface GBufferUpdaterContext {
  54. material: IMaterial, renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D
  55. }
  56. export interface GBufferUpdater {
  57. updateGBufferFlags: (data: Vector4, context: GBufferUpdaterContext) => void
  58. }
  59. /**
  60. * G-Buffer Plugin
  61. *
  62. * Adds a pre-render pass to render the g-buffer(depth+normal+flags) to render target(s) that can be used as gbuffer and for postprocessing.
  63. * @category Plugins
  64. */
  65. @uiFolderContainer('G-Buffer Plugin')
  66. export class GBufferPlugin
  67. extends PipelinePassPlugin<GBufferPluginPass, 'gbuffer', GBufferPluginEventTypes> {
  68. readonly passId = 'gbuffer'
  69. public static readonly PluginType = 'GBuffer'
  70. target?: GBufferPluginTarget
  71. // @uiConfig(/* {readOnly: true}*/) // todo: fix bug in uiconfig or tpImageGenerator because of which 0 index is not showing in the UI, when we uncomment this
  72. textures: Texture[] = []
  73. @uiImage(/* {readOnly: true}*/)
  74. get normalDepthTexture(): ITexture|undefined {
  75. return this.textures[0]
  76. }
  77. @uiImage(/* {readOnly: true}*/)
  78. get flagsTexture(): ITexture|undefined {
  79. return this.textures[1]
  80. }
  81. @uiImage(/* {readOnly: true}*/)
  82. get depthTexture(): (ITexture&DepthTexture)|undefined {
  83. return this.target?.depthTexture
  84. }
  85. // @uiConfig() // not supported in this material yet
  86. material?: GBufferMaterial
  87. // @onChange(GBufferPlugin.prototype._depthPackingChanged)
  88. // @uiDropdown('Depth Packing', threeConstMappings.DepthPackingStrategies.uiConfig) packing: DepthPackingStrategies
  89. // @onChange2(GBufferPlugin.prototype._createTargetAndMaterial)
  90. // @uiDropdown('Buffer Type', threeConstMappings.TextureDataType.uiConfig)
  91. readonly bufferType: TextureDataType // cannot be changed after creation (for now)
  92. // @uiToggle()
  93. // @onChange2(GBufferPlugin.prototype._createTargetAndMaterial)
  94. readonly isPrimaryGBuffer: boolean // cannot be changed after creation (for now)
  95. // protected _depthPackingChanged() {
  96. // this.material.depthPacking = this.depthPacking
  97. // this.material.needsUpdate = true
  98. // if (this.unpackExtension && this.unpackExtension.extraDefines) {
  99. // this.unpackExtension.extraDefines.DEPTH_PACKING = this.depthPacking
  100. // this.unpackExtension.setDirty?.()
  101. // }
  102. // this.setDirty()
  103. // }
  104. unpackExtension: MaterialExtension = {
  105. shaderExtender: (shader)=>{
  106. shader.fragmentShader = shaderReplaceString(shader.fragmentShader,
  107. '#include <packing>',
  108. '\n' + GBufferUnpack + '\n', {append: true})
  109. },
  110. extraUniforms: {
  111. tNormalDepth: ()=>({value: this.normalDepthTexture}),
  112. tGBufferFlags: ()=>({value: this.flagsTexture}),
  113. tGBufferDepthTexture: ()=>({value: this.depthTexture}),
  114. },
  115. extraDefines: {
  116. // ['GBUFFER_PACKING']: BasicDepthPacking,
  117. ['HAS_NORMAL_DEPTH_BUFFER']: ()=>this.normalDepthTexture ? 1 : undefined,
  118. ['GBUFFER_HAS_DEPTH_TEXTURE']: ()=>this.depthTexture ? 1 : undefined,
  119. ['GBUFFER_HAS_FLAGS']: ()=>this.flagsTexture ? 1 : undefined,
  120. // ['HAS_FLAGS_BUFFER']: ()=>this.flagsTexture ? 1 : undefined,
  121. ['HAS_GBUFFER']: ()=>this.isPrimaryGBuffer && this.normalDepthTexture ? 1 : undefined,
  122. },
  123. priority: 100,
  124. isCompatible: () => true,
  125. }
  126. private _isPrimaryGBufferSet = false
  127. protected _createTargetAndMaterial(recreateTarget = true) {
  128. if (!this._viewer) return
  129. if (recreateTarget) this._disposeTarget()
  130. const useMultiple = this._viewer?.renderManager.isWebGL2 && this.renderFlagsBuffer
  131. if (!this.target) {
  132. this.target = this._viewer.renderManager.createTarget<GBufferPluginTarget>(
  133. {
  134. depthBuffer: true,
  135. samples: this._viewer.renderManager.composerTarget.samples || 0,
  136. type: this.bufferType,
  137. textureCount: useMultiple ? 2 : 1,
  138. depthTexture: this.renderDepthTexture,
  139. depthTextureType: this.depthTextureType,
  140. // magFilter: NearestFilter,
  141. // minFilter: NearestFilter,
  142. // generateMipmaps: false,
  143. // encoding: LinearEncoding,
  144. })
  145. if (Array.isArray(this.target.texture)) {
  146. this.target.texture[0].name = 'gbufferDepthNormal'
  147. this.target.texture[1].name = 'gbufferFlags'
  148. this.textures = this.target.texture
  149. } else {
  150. this.target.texture.name = 'gbufferDepthNormal'
  151. this.textures.push(this.target.texture)
  152. }
  153. }
  154. if (!this.material) {
  155. this.material = new GBufferMaterial(useMultiple, {
  156. blending: NoBlending,
  157. transparent: true,
  158. })
  159. }
  160. if (this._pass) this._pass.target = this.target
  161. if (this.isPrimaryGBuffer) {
  162. this._viewer.renderManager.gbufferTarget = this.target
  163. this._viewer.renderManager.screenPass.material.registerMaterialExtensions([this.unpackExtension])
  164. this._isPrimaryGBufferSet = true
  165. }
  166. }
  167. protected _disposeTarget() {
  168. if (!this._viewer) return
  169. if (this.target) {
  170. this._viewer.renderManager.disposeTarget(this.target)
  171. this.target = undefined
  172. }
  173. this.textures = []
  174. if (this._isPrimaryGBufferSet) { // using a separate flag as when isPrimaryGBuffer is changed, we cannot check it.
  175. this._viewer.renderManager.gbufferTarget = undefined
  176. // this._viewer.renderManager.screenPass.material.unregisterMaterialExtensions([this.unpackExtension]) // todo
  177. this._isPrimaryGBufferSet = false
  178. }
  179. }
  180. protected _createPass() {
  181. this._createTargetAndMaterial(true)
  182. if (!this.target) throw new Error('GBufferPlugin: target not created')
  183. if (!this.material) throw new Error('GBufferPlugin: material not created')
  184. this.material.userData.isGBufferMaterial = true
  185. const pass = new GBufferRenderPass(this.passId, this.target, this.material, new Color(1, 1, 1), 1)
  186. const preprocessMaterial = pass.preprocessMaterial
  187. pass.preprocessMaterial = (m) => preprocessMaterial(m, m.userData.renderToDepth) // if renderToDepth is undefined then renderToGbuffer is taken internally
  188. pass.before = ['render']
  189. pass.after = []
  190. pass.required = ['render']
  191. return pass
  192. }
  193. protected _beforeRender(scene: IScene, camera: ICamera, renderManager: IRenderManager): boolean {
  194. if (!super._beforeRender(scene, camera, renderManager) || !this.material) return false
  195. camera.updateShaderProperties(this.material)
  196. return true
  197. }
  198. constructor(
  199. bufferType: TextureDataType = UnsignedByteType,
  200. isPrimaryGBuffer = true,
  201. enabled = true,
  202. public renderFlagsBuffer: boolean = true,
  203. public renderDepthTexture: boolean = false,
  204. public depthTextureType: typeof UnsignedShortType | typeof UnsignedIntType | typeof FloatType /* | typeof UnsignedInt248Type*/ = UnsignedIntType,
  205. // packing: DepthPackingStrategies = BasicDepthPacking,
  206. ) {
  207. super()
  208. this.enabled = enabled
  209. this.bufferType = bufferType
  210. this.isPrimaryGBuffer = isPrimaryGBuffer
  211. // this.depthPacking = depthPacking
  212. }
  213. registerGBufferUpdater(key: string, updater: GBufferUpdater['updateGBufferFlags']): void {
  214. if (this.material) this.material.flagUpdaters.set(key, updater)
  215. }
  216. unregisterGBufferUpdater(key: string): void {
  217. if (this.material) this.material.flagUpdaters.delete(key)
  218. }
  219. onRemove(viewer: ThreeViewer): void {
  220. this._disposeTarget()
  221. this.material?.dispose()
  222. this.material = undefined
  223. return super.onRemove(viewer)
  224. }
  225. /**
  226. * @deprecated use {@link normalDepthTexture} instead
  227. */
  228. getDepthNormal() {
  229. return this.textures.length > 0 ? this.textures[0] : undefined
  230. }
  231. /**
  232. * @deprecated use {@link flagsTexture} instead
  233. */
  234. getFlagsTexture() {
  235. return this.textures.length > 1 ? this.textures[1] : undefined
  236. }
  237. /**
  238. * @deprecated use {@link target} instead
  239. */
  240. getTarget() {
  241. return this.target
  242. }
  243. /**
  244. * @deprecated use {@link unpackExtension} instead
  245. */
  246. getUnpackSnippet(): string {
  247. return GBufferUnpack
  248. }
  249. /**
  250. * @deprecated use {@link unpackExtension} instead, it adds the same uniforms and defines
  251. * @param material
  252. */
  253. updateShaderProperties(material: {defines: Record<string, string | number | undefined>; uniforms: {[p: string]: IUniform}, needsUpdate?: boolean}): this {
  254. if (material.uniforms.tNormalDepth) material.uniforms.tNormalDepth.value = this.normalDepthTexture ?? undefined
  255. else this._viewer?.console.warn('BaseRenderer: no uniform: tNormalDepth')
  256. if (material.uniforms.tGBufferFlags) {
  257. material.uniforms.tGBufferFlags.value = this.flagsTexture ?? undefined
  258. const t = material.uniforms.tGBufferFlags.value ? 1 : 0
  259. if (t !== material.defines.GBUFFER_HAS_FLAGS) {
  260. material.defines.GBUFFER_HAS_FLAGS = t
  261. material.needsUpdate = true
  262. }
  263. }
  264. return this
  265. }
  266. }
  267. /**
  268. * Renders DepthNormal to a texture and flags to another
  269. */
  270. export class GBufferMaterial extends ShaderMaterial2 {
  271. constructor(multipleRT = true, parameters?: ShaderMaterialParameters & IMaterialParameters) {
  272. super({
  273. vertexShader: GBufferMatVert,
  274. fragmentShader: GBufferMatFrag,
  275. uniforms: UniformsUtils.merge([
  276. UniformsLib.common,
  277. UniformsLib.bumpmap,
  278. UniformsLib.normalmap,
  279. UniformsLib.displacementmap,
  280. {
  281. cameraNearFar: {value: new Vector2(0.1, 1000)}, // this has to be set from outside
  282. flags: {value: new Vector4(255, 255, 255, 255)},
  283. },
  284. ]),
  285. defines: {
  286. // eslint-disable-next-line @typescript-eslint/naming-convention
  287. IS_GLSL3: multipleRT ? '1' : '0',
  288. },
  289. glslVersion: multipleRT ? GLSL3 : GLSL1,
  290. ...parameters,
  291. })
  292. this.reset()
  293. }
  294. flagUpdaters: Map<string, GBufferUpdater['updateGBufferFlags']> = new Map()
  295. normalMapType: NormalMapTypes = TangentSpaceNormalMap
  296. flatShading = false
  297. onBeforeRender(renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D) {
  298. super.onBeforeRender(renderer, scene, camera, geometry, object)
  299. let material = (object as any).material as IMaterial & Partial<PhysicalMaterial>
  300. if (Array.isArray(material)) { // todo: add support for multi materials.
  301. material = material[0]
  302. }
  303. if (!material) return
  304. const setMap = (key: keyof IMaterial)=>{
  305. const map = material[key]
  306. if (!map) return
  307. this.uniforms[key].value = map
  308. if (!this.uniforms[key + 'Transform']) console.error('GBufferMaterial: ' + key + 'Transform is not defined in uniform')
  309. else renderer.materials.refreshTransformUniform(map, this.uniforms[key + 'Transform'])
  310. }
  311. setMap('map')
  312. if (material.side !== undefined) this.side = material.side ?? DoubleSide
  313. setMap('alphaMap')
  314. if (material.alphaTest !== undefined) this.alphaTest = material.alphaTest < 1e-4 ? 1e-4 : material.alphaTest
  315. setMap('bumpMap')
  316. if (material.bumpScale !== undefined) this.uniforms.bumpScale.value = material.bumpScale
  317. setMap('normalMap')
  318. if (material.normalScale !== undefined) this.uniforms.normalScale.value.copy(material.normalScale)
  319. if (material.normalMapType !== undefined) this.normalMapType = material.normalMapType
  320. if (material.flatShading !== undefined) this.flatShading = material.flatShading
  321. setMap('displacementMap')
  322. if (material.displacementScale !== undefined) this.uniforms.displacementScale.value = material.displacementScale
  323. if (material.displacementBias !== undefined) this.uniforms.displacementBias.value = material.displacementBias
  324. if (material.wireframe !== undefined) this.wireframe = material.wireframe
  325. if (material.wireframeLinewidth !== undefined) this.wireframeLinewidth = material.wireframeLinewidth
  326. /*
  327. GBuffer Flags has the following data
  328. 1st Rendertarget has Depth and Normal buffers
  329. 2nd Render Target::
  330. x : Empty
  331. y : first 3 bits lut index, second 5 bits bevel radius
  332. z : material id (userData.gBufferData?.materialId, userData.matId)
  333. w : this field is for setting bits - lutEnable-0, tonemap-1, bloom-2
  334. */
  335. this.uniforms.flags.value.set(255, 255, 255, 255)
  336. const materialId = material.userData.gBufferData?.materialId ?? material.userData.matId // matId for backward compatibility
  337. this.uniforms.flags.value.z = materialId || 0
  338. this.flagUpdaters.forEach((updater)=> updater(this.uniforms.flags.value, {material, renderer, scene, camera, geometry, object}))
  339. this.uniforms.flags.value.x /= 255
  340. this.uniforms.flags.value.y /= 255
  341. this.uniforms.flags.value.z /= 255
  342. this.uniforms.flags.value.w /= 255
  343. this.uniformsNeedUpdate = true
  344. updateMaterialDefines({
  345. // ['USE_ALPHAMAP']: this.uniforms.alphaMap.value ? 1 : undefined,
  346. ['ALPHAMAP_UV']: this.uniforms.alphaMap.value ? 'uv' : undefined, // todo use getChannel, see WebGLPrograms.js
  347. ['USE_DISPLACEMENTMAP']: this.uniforms.displacementMap.value ? 1 : undefined,
  348. ['DISPLACEMENTMAP_UV']: this.uniforms.displacementMap.value ? 'uv' : undefined, // todo use getChannel, see WebGLPrograms.js
  349. ['ALPHA_I_RGBA_PACKING']: material.userData.ALPHA_I_RGBA_PACKING ? 1 : undefined,
  350. ['FORCED_LINEAR_DEPTH']: material.userData.forcedLinearDepth ?? undefined,
  351. }, material)
  352. // todo: do the same in DepthBufferPlugin and NormalBufferPlugin
  353. // what about the material extension settings in the userData of the source materials?
  354. if (material.materialExtensions?.length) {
  355. this.registerMaterialExtensions(material.materialExtensions)
  356. }
  357. // this.transparent = true
  358. this.needsUpdate = true
  359. }
  360. onAfterRender(renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, object: Object3D) {
  361. super.onAfterRender(renderer, scene, camera, geometry, object)
  362. let material = (object as any).material as IMaterial & Partial<PhysicalMaterial>
  363. if (Array.isArray(material)) { // todo: add support for multi materials.
  364. material = material[0]
  365. }
  366. if (!material) return
  367. if (material.materialExtensions?.length) {
  368. this.unregisterMaterialExtensions(material.materialExtensions)
  369. }
  370. this.reset()
  371. }
  372. reset() {
  373. this.uniforms.map.value = null
  374. this.side = DoubleSide
  375. this.uniforms.alphaMap.value = null
  376. this.alphaTest = 0.001
  377. this.uniforms.bumpMap.value = null
  378. this.uniforms.bumpScale.value = 1
  379. this.uniforms.normalMap.value = null
  380. this.uniforms.normalScale.value.set(1, 1)
  381. this.normalMapType = TangentSpaceNormalMap
  382. this.flatShading = false
  383. this.uniforms.displacementMap.value = null
  384. this.uniforms.displacementScale.value = 1
  385. this.uniforms.displacementBias.value = 0
  386. this.uniforms.flags.value.set(255, 255, 255, 255)
  387. this.wireframe = false
  388. this.wireframeLinewidth = 1
  389. }
  390. }
  391. /**
  392. * @deprecated use GBufferMaterial instead
  393. */
  394. export class DepthNormalMaterial extends GBufferMaterial {
  395. constructor(multipleRT: boolean, parameters?: ShaderMaterialParameters & IMaterialParameters) {
  396. super(multipleRT, parameters)
  397. console.warn('DepthNormalMaterial is deprecated, use GBufferMaterial instead')
  398. }
  399. }