threepipe
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

GBufferPlugin.ts 18KB

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