threepipe
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

iMaterialCommons.ts 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import {
  2. AddEquation,
  3. AlwaysStencilFunc,
  4. ColorManagement,
  5. FrontSide,
  6. KeepStencilOp,
  7. LessEqualDepth,
  8. Material,
  9. MaterialParameters,
  10. NormalBlending,
  11. OneMinusSrcAlphaFactor,
  12. Scene,
  13. Shader,
  14. SrcAlphaFactor,
  15. WebGLRenderer,
  16. } from 'three'
  17. import {copyProps} from 'ts-browser-helpers'
  18. import {copyMaterialUserData} from '../../utils/serialization'
  19. import {MaterialExtender, MaterialExtension} from '../../materials'
  20. import {IScene} from '../IScene'
  21. import {IMaterial, IMaterialEventMap, IMaterialSetDirtyOptions} from '../IMaterial'
  22. import {isInScene} from '../../three/utils'
  23. /**
  24. * Map of all material properties and their default values in three.js - Material.js
  25. * This is used to copy properties and serialize/deserialize them.
  26. * @note: Upgrade note: keep updated from three.js/src/Material.js:22
  27. */
  28. export const threeMaterialPropList = {
  29. // uuid: '', // DONT COPY, should remain commented
  30. name: '',
  31. blending: NormalBlending,
  32. side: FrontSide,
  33. vertexColors: false,
  34. opacity: 1,
  35. transparent: false,
  36. blendSrc: SrcAlphaFactor,
  37. blendDst: OneMinusSrcAlphaFactor,
  38. blendEquation: AddEquation,
  39. blendSrcAlpha: null,
  40. blendDstAlpha: null,
  41. blendEquationAlpha: null,
  42. blendColor: '#000000',
  43. blendAlpha: 0,
  44. depthFunc: LessEqualDepth,
  45. depthTest: true,
  46. depthWrite: true,
  47. stencilWriteMask: 0xff,
  48. stencilFunc: AlwaysStencilFunc,
  49. stencilRef: 0,
  50. stencilFuncMask: 0xff,
  51. stencilFail: KeepStencilOp,
  52. stencilZFail: KeepStencilOp,
  53. stencilZPass: KeepStencilOp,
  54. stencilWrite: false,
  55. clippingPlanes: null,
  56. clipIntersection: false,
  57. clipShadows: false,
  58. shadowSide: null,
  59. colorWrite: true,
  60. precision: null,
  61. polygonOffset: false,
  62. polygonOffsetFactor: 0,
  63. polygonOffsetUnits: 0,
  64. dithering: false,
  65. alphaToCoverage: false,
  66. premultipliedAlpha: false,
  67. forceSinglePass: false,
  68. visible: true,
  69. toneMapped: true,
  70. userData: {},
  71. // wireframeLinecap: 'round',
  72. // wireframeLinejoin: 'round',
  73. alphaTest: 0,
  74. alphaHash: false,
  75. // fog: true,
  76. }
  77. export const iMaterialCommons = {
  78. threeMaterialPropList,
  79. setDirty: function(this: IMaterial, options?: IMaterialSetDirtyOptions): void {
  80. if (options?.needsUpdate !== false) this.needsUpdate = true
  81. this.dispatchEvent({bubbleToObject: true, bubbleToParent: true, ...options, type: 'materialUpdate'}) // this sets sceneUpdate in root scene
  82. if (options?.last !== false) this.uiConfig?.uiRefresh?.(true, 'postFrame', 1)
  83. },
  84. setValues: (superSetValues: Material['setValues']): IMaterial['setValues'] =>
  85. function(this: IMaterial, parameters: Material | (MaterialParameters & {type?: string})): IMaterial {
  86. // legacy check for old color management(non-sRGB) in material.setValues todo: move this to Material.fromJSON
  87. const legacyColors = (parameters as any)?.metadata && (parameters as any)?.metadata.version <= 4.5
  88. const lastColorManagementEnabled = ColorManagement.enabled
  89. if (legacyColors) ColorManagement.enabled = false
  90. const propList = this.constructor.MaterialProperties
  91. const params: any = !propList ? {...parameters} : copyProps(parameters, {} as any, Array.from(Object.keys(propList)))
  92. // remove undefined values
  93. for (const key of Object.keys(params)) if (params[key] === undefined) delete params[key]
  94. const userData = params.userData
  95. delete params.userData
  96. // todo: can migrate to @serialize for properties which have UI etc and use super.setValues for the rest like threeMaterialPropList
  97. superSetValues.call(this, params)
  98. if (userData) copyMaterialUserData(this.userData, userData)
  99. if (legacyColors) ColorManagement.enabled = lastColorManagementEnabled
  100. this.setDirty?.()
  101. return this
  102. },
  103. dispose: (superDispose: Material['dispose']): IMaterial['dispose'] =>
  104. function(this: IMaterial, force = true): void {
  105. if (!force && (this.userData.disposeOnIdle === false || isInScene(this))) return
  106. superDispose.call(this)
  107. },
  108. clone: (superClone: Material['clone']): IMaterial['clone'] =>
  109. function(this: IMaterial, track = false): IMaterial {
  110. if (track) {
  111. if (!this.userData.cloneId) {
  112. this.userData.cloneId = '0'
  113. }
  114. if (!this.userData.cloneCount) {
  115. this.userData.cloneCount = 0
  116. }
  117. this.userData.cloneCount += 1
  118. }
  119. const material: IMaterial = this.generator?.({})?.setValues(this, false) ?? superClone.call(this)
  120. if (track) {
  121. material.userData.cloneId = material.userData.cloneId + '_' + this.userData.cloneCount
  122. material.userData.cloneCount = 0
  123. material.name = (material.name || 'mat') + '_' + material.userData.cloneId
  124. }
  125. return material
  126. },
  127. dispatchEvent: (superDispatchEvent: Material['dispatchEvent']): IMaterial['dispatchEvent'] =>
  128. function(this: IMaterial, event): void {
  129. superDispatchEvent.call(this, event)
  130. const type = event.type
  131. if ((event as IMaterialEventMap['materialUpdate']).bubbleToObject && (
  132. type === 'beforeDeserialize' || type === 'materialUpdate' || type === 'textureUpdate' // todo - add more events
  133. )) {
  134. this.appliedMeshes.forEach(m => m.dispatchEvent({...event, material: this, type}))
  135. }
  136. },
  137. customProgramCacheKey: function(this: IMaterial): string {
  138. return MaterialExtender.CacheKeyForExtensions(this, this.materialExtensions) + this.userData.inverseAlphaMap
  139. },
  140. registerMaterialExtensions: function(this: IMaterial, customMaterialExtensions: MaterialExtension[]): void {
  141. MaterialExtender.RegisterExtensions(this, customMaterialExtensions)
  142. },
  143. unregisterMaterialExtensions: function(this: IMaterial, customMaterialExtensions: MaterialExtension[]): void {
  144. MaterialExtender.UnregisterExtensions(this, customMaterialExtensions)
  145. },
  146. // shader is not Shader but WebglUniforms.getParameters return value type so includes defines
  147. onBeforeCompile: function(this: IMaterial, shader: Shader, renderer: WebGLRenderer): void {
  148. if (this.materialExtensions) MaterialExtender.ApplyMaterialExtensions(this, shader, this.materialExtensions, renderer)
  149. this.dispatchEvent({type: 'beforeCompile', shader, renderer})
  150. shader.fragmentShader = shader.fragmentShader.replaceAll('#glMarker', '// ')
  151. shader.vertexShader = shader.vertexShader.replaceAll('#glMarker', '// ')
  152. },
  153. onBeforeRender: function(this: IMaterial, renderer, scene: Scene & Partial<IScene>, camera, geometry, object) {
  154. if (this.envMapIntensity !== undefined && !this.userData.separateEnvMapIntensity && scene.envMapIntensity !== undefined) {
  155. this.userData.__envIntensity = this.envMapIntensity
  156. this.envMapIntensity = scene.envMapIntensity
  157. }
  158. if (this.defines && this.envMap !== undefined && scene.fixedEnvMapDirection !== undefined) {
  159. if (scene.fixedEnvMapDirection) {
  160. if (!this.defines.FIX_ENV_DIRECTION) {
  161. this.defines.FIX_ENV_DIRECTION = '1'
  162. this.needsUpdate = true
  163. }
  164. } else if (this.defines.FIX_ENV_DIRECTION !== undefined) {
  165. delete this.defines.FIX_ENV_DIRECTION
  166. this.needsUpdate = true
  167. }
  168. }
  169. this.dispatchEvent({type: 'beforeRender', renderer, scene, camera, geometry, object})
  170. } as IMaterial['onBeforeRender'],
  171. onAfterRender: function(this: IMaterial, renderer, scene: Scene & Partial<IScene>, camera, geometry, object) {
  172. if (this.userData.__envIntensity !== undefined) {
  173. this.envMapIntensity = this.userData.__envIntensity
  174. delete this.userData.__envIntensity
  175. }
  176. this.dispatchEvent({type: 'afterRender', renderer, scene, camera, geometry, object})
  177. } as IMaterial['onAfterRender'],
  178. onBeforeCompileOverride: (superOnBeforeCompile: Material['onBeforeCompile']): IMaterial['onBeforeCompile'] =>
  179. function(this: IMaterial, shader: Shader, renderer: WebGLRenderer): void {
  180. iMaterialCommons.onBeforeCompile.call(this, shader, renderer)
  181. superOnBeforeCompile.call(this, shader, renderer)
  182. },
  183. onBeforeRenderOverride: (superOnBeforeRender: Material['onBeforeRender']): IMaterial['onBeforeRender'] =>
  184. function(this: IMaterial, ...args: Parameters<Material['onBeforeRender']>): void {
  185. superOnBeforeRender.call(this, ...args)
  186. iMaterialCommons.onBeforeRender.call(this, ...args)
  187. },
  188. onAfterRenderOverride: (superOnAfterRender: Material['onAfterRender']): IMaterial['onAfterRender'] =>
  189. function(this: IMaterial, ...args: Parameters<Material['onAfterRender']>): void {
  190. superOnAfterRender.call(this, ...args)
  191. iMaterialCommons.onAfterRender.call(this, ...args)
  192. },
  193. customProgramCacheKeyOverride: (superCustomPropertyCacheKey: Material['customProgramCacheKey']): IMaterial['customProgramCacheKey'] =>
  194. function(this: IMaterial): string {
  195. return superCustomPropertyCacheKey.call(this) + iMaterialCommons.customProgramCacheKey.call(this)
  196. },
  197. upgradeMaterial: upgradeMaterial,
  198. // todo;
  199. } as const
  200. /**
  201. * Convert a standard three.js {@link Material} to {@link IMaterial}
  202. */
  203. export function upgradeMaterial(this: IMaterial): IMaterial {
  204. if (!this.isMaterial) {
  205. console.error('Material is not a material', this)
  206. return this
  207. }
  208. if (!this.setDirty) this.setDirty = iMaterialCommons.setDirty
  209. if (!this.appliedMeshes) this.appliedMeshes = new Set()
  210. if (!this.userData) this.userData = {}
  211. this.userData.uuid = this.uuid // for serialization
  212. // legacy
  213. if (!this.userData.setDirty) this.userData.setDirty = (e: any) => {
  214. console.warn('userData.setDirty is deprecated. Use setDirty instead.')
  215. this.setDirty(e)
  216. }
  217. if (this.assetType === 'material') return this // already upgraded
  218. this.assetType = 'material'
  219. this.setValues = iMaterialCommons.setValues(this.setValues)
  220. this.dispose = iMaterialCommons.dispose(this.dispose)
  221. this.clone = iMaterialCommons.clone(this.clone)
  222. this.dispatchEvent = iMaterialCommons.dispatchEvent(this.dispatchEvent)
  223. // material extensions
  224. if (!this.extraUniformsToUpload) this.extraUniformsToUpload = {}
  225. if (!this.materialExtensions) this.materialExtensions = []
  226. if (!this.registerMaterialExtensions) this.registerMaterialExtensions = iMaterialCommons.registerMaterialExtensions
  227. if (!this.unregisterMaterialExtensions) this.unregisterMaterialExtensions = iMaterialCommons.unregisterMaterialExtensions
  228. this.onBeforeCompile = iMaterialCommons.onBeforeCompileOverride(this.onBeforeCompile)
  229. this.onBeforeRender = iMaterialCommons.onBeforeRenderOverride(this.onBeforeRender)
  230. this.onAfterRender = iMaterialCommons.onAfterRenderOverride(this.onAfterRender)
  231. this.customProgramCacheKey = iMaterialCommons.customProgramCacheKeyOverride(this.customProgramCacheKey)
  232. // todo: add uiconfig, serialization, other stuff from UnlitMaterial?
  233. // dispose uiconfig etc. on dispose
  234. return this
  235. }