-
Notifications
You must be signed in to change notification settings - Fork 12
/
CustomBumpMapPlugin.ts
304 lines (271 loc) · 12.3 KB
/
CustomBumpMapPlugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import {Matrix3, SRGBColorSpace, Texture} from 'three'
import {AViewerPluginSync, ThreeViewer} from '../../viewer'
import {uiFolderContainer, UiObjectConfig, uiToggle} from 'uiconfig.js'
import {serialize} from 'ts-browser-helpers'
import {IMaterial, IObject3D, ITexture, PhysicalMaterial} from '../../core'
import {MaterialExtension, updateMaterialDefines} from '../../materials'
import {shaderReplaceString} from '../../utils'
import {GLTFLoader2, GLTFWriter2} from '../../assetmanager'
import type {GLTFLoaderPlugin, GLTFParser} from 'three/examples/jsm/loaders/GLTFLoader'
import CustomBumpMapPluginShader from './shaders/CustomBumpMapPlugin.glsl'
import {matDefine} from '../../three'
import {makeSamplerUi} from '../../ui/image-ui'
/**
* Custom Bump Map Plugin
* Adds a material extension to PhysicalMaterial to support custom bump maps.
* A Custom bump map is similar to the built-in bump map, but allows using an extra bump map and scale to give a combined effect.
* This plugin also has support for bicubic filtering of the custom bump map and is enabled by default.
* It also adds a UI to the material to edit the settings.
* It uses WEBGI_materials_custom_bump_map glTF extension to save the settings in glTF files.
* @category Plugins
*/
@uiFolderContainer('Custom BumpMap (MatExt)')
export class CustomBumpMapPlugin extends AViewerPluginSync<''> {
static readonly PluginType = 'CustomBumpMapPlugin'
@uiToggle('Enabled', (that: CustomBumpMapPlugin)=>({onChange: that.setDirty}))
@serialize() enabled = true
@uiToggle('Bicubic', (that: CustomBumpMapPlugin)=>({onChange: that.setDirty}))
@matDefine('CUSTOM_BUMP_MAP_BICUBIC', undefined, true, CustomBumpMapPlugin.prototype.setDirty)
@serialize() bicubicFiltering = true
private _defines: any = {
['CUSTOM_BUMP_MAP_DEBUG']: false,
['CUSTOM_BUMP_MAP_BICUBIC']: true,
}
private _uniforms: any = {
customBumpUvTransform: {value: new Matrix3()},
customBumpScale: {value: 0.001},
customBumpMap: {value: null},
}
public enableCustomBump(material: IMaterial, map?: ITexture, scale?: number): boolean {
const ud = material?.userData
if (!ud) return false
if (ud._hasCustomBump === undefined) {
const meshes = material.appliedMeshes
let possible = true
if (meshes) for (const {geometry} of meshes) {
if (geometry && (!geometry.attributes.position || !geometry.attributes.normal || !geometry.attributes.uv)) {
possible = false
}
// if (possible && !geometry.attributes.tangent) {
// geometry.computeTangents()
// }
}
if (!possible) {
return false
}
}
ud._hasCustomBump = true
ud._customBumpScale = scale ?? ud._customBumpScale ?? 0.001
ud._customBumpMap = map ?? ud._customBumpMap ?? null
if (material.setDirty) material.setDirty()
return true
}
readonly materialExtension: MaterialExtension = {
parsFragmentSnippet: (_, material: PhysicalMaterial)=>{
if (this.isDisabled() || !material?.userData._hasCustomBump) return ''
return CustomBumpMapPluginShader
},
shaderExtender: (shader, material: PhysicalMaterial) => {
if (this.isDisabled() || !material?.userData._hasCustomBump) return
const customBumpMap = material.userData._customBumpMap
if (!customBumpMap) return
shader.fragmentShader = shaderReplaceString(shader.fragmentShader, '#glMarker beforeAccumulation',
`
#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd_cb(), faceDirection );
#endif
`, {prepend: true}
)
shader.vertexShader = shaderReplaceString(shader.vertexShader, '#include <uv_pars_vertex>',
`
#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
varying vec2 vCustomBumpUv;
uniform mat3 customBumpUvTransform;
#endif
`, {prepend: true},
)
shader.vertexShader = shaderReplaceString(shader.vertexShader, '#include <uv_vertex>',
`
#if defined(CUSTOM_BUMP_MAP_ENABLED) && CUSTOM_BUMP_MAP_ENABLED > 0
vCustomBumpUv = ( customBumpUvTransform * vec3( uv, 1 ) ).xy;
#endif
`, {prepend: true},
)
shader.defines.USE_UV = ''
},
onObjectRender: (object: IObject3D, material) => {
const userData = material.userData
if (!userData?._hasCustomBump) return
if (!object.isMesh || !object.geometry) return
const tex = userData._customBumpMap?.isTexture ? userData._customBumpMap : null
this._uniforms.customBumpMap.value = tex
this._uniforms.customBumpScale.value = tex ? userData._customBumpScale ?? 0 : 0
if (tex) {
tex.updateMatrix()
this._uniforms.customBumpUvTransform.value.copy(tex.matrix)
}
updateMaterialDefines({
...this._defines,
['CUSTOM_BUMP_MAP_ENABLED']: +this.enabled,
}, material)
},
extraUniforms: {
...this._uniforms,
},
computeCacheKey: (material1: PhysicalMaterial) => {
return (this.enabled ? '1' : '0') + (material1.userData._hasCustomBump ? '1' : '0') + material1.userData?._customBumpMap?.uuid
},
isCompatible: (material1: PhysicalMaterial) => material1.isPhysicalMaterial,
getUiConfig: material => {
const viewer = this._viewer!
const enableCustomBump = this.enableCustomBump.bind(this)
const state = material.userData
const config: UiObjectConfig = {
type: 'folder',
label: 'CustomBumpMap',
onChange: (ev)=>{
if (!ev.config) return
this.setDirty()
},
children: [
{
type: 'checkbox',
label: 'Enabled',
get value() {
return state._hasCustomBump || false
},
set value(v) {
if (v === state._hasCustomBump) return
if (v) {
if (!enableCustomBump(material))
viewer.dialog.alert('Cannot add CustomBumpMap.')
} else {
state._hasCustomBump = false
if (material.setDirty) material.setDirty()
}
config.uiRefresh?.(true, 'postFrame')
},
},
{
type: 'slider',
label: 'Bump Scale',
bounds: [-1, 1],
hidden: () => !state._hasCustomBump,
property: [state, '_customBumpScale'],
onChange: this.setDirty,
},
{
type: 'image',
label: 'Bump Map',
hidden: () => !state._hasCustomBump,
property: [state, '_customBumpMap'],
onChange: ()=>{
material.setDirty()
},
},
makeSamplerUi(state as any, '_customBumpMap'),
],
}
return config
},
}
setDirty = (): void => {
this.materialExtension.setDirty?.()
this._viewer?.setDirty()
}
private _loaderCreate({loader}: {loader: GLTFLoader2}) {
if (!loader.isGLTFLoader2) return
loader.register((p) => new GLTFMaterialsCustomBumpMapImport(p))
}
constructor() {
super()
this._loaderCreate = this._loaderCreate.bind(this)
}
onAdded(v: ThreeViewer) {
super.onAdded(v)
// v.addEventListener('preRender', this._preRender)
v.assetManager.materials.registerMaterialExtension(this.materialExtension)
v.assetManager.importer.addEventListener('loaderCreate', this._loaderCreate as any)
v.assetManager.exporter.getExporter('gltf', 'glb')?.extensions?.push(glTFMaterialsCustomBumpMapExport)
// v.getPlugin(GBufferPlugin)?.material?.registerMaterialExtensions([this.materialExtension])
}
onRemove(v: ThreeViewer) {
v.assetManager.materials?.unregisterMaterialExtension(this.materialExtension)
v.assetManager.importer?.removeEventListener('loaderCreate', this._loaderCreate as any)
const exporter = v.assetManager.exporter.getExporter('gltf', 'glb')
if (exporter) {
const index = exporter.extensions?.indexOf(glTFMaterialsCustomBumpMapExport)
if (index !== undefined && index >= 0) exporter.extensions?.splice(index, 1)
}
// v.getPlugin(GBufferPlugin)?.material?.unregisterMaterialExtensions([this.materialExtension])
return super.onRemove(v)
}
public static readonly CUSTOM_BUMP_MAP_GLTF_EXTENSION = 'WEBGI_materials_custom_bump_map'
}
declare module '../../core/IMaterial' {
interface IMaterialUserData {
_hasCustomBump?: boolean
_customBumpMap?: ITexture | null
_customBumpScale?: number
}
}
/**
* FragmentClipping Materials Extension
*
* Specification: https://webgi.xyz/docs/gltf-extensions/WEBGI_materials_fragment_clipping_extension.html
*/
class GLTFMaterialsCustomBumpMapImport implements GLTFLoaderPlugin {
public name: string
public parser: GLTFParser
constructor(parser: GLTFParser) {
this.parser = parser
this.name = CustomBumpMapPlugin.CUSTOM_BUMP_MAP_GLTF_EXTENSION
}
async extendMaterialParams(materialIndex: number, materialParams: any) {
const parser = this.parser
const materialDef = parser.json.materials[materialIndex]
if (!materialDef.extensions || !materialDef.extensions[this.name]) return
const extension = materialDef.extensions[this.name]
if (!materialParams.userData) materialParams.userData = {}
materialParams.userData._hasCustomBump = true // single _ so that its saved when cloning but not when saving
materialParams.userData._customBumpScale = extension.customBumpScale ?? 0.0
const pending = []
const tex = extension.customBumpMap
if (tex) {
pending.push(parser.assignTexture(materialParams.userData, '_customBumpMap', tex).then((t: Texture) => {
// t.format = RGBFormat
t.colorSpace = SRGBColorSpace
}))
}
return Promise.all(pending)
}
// do any mesh or geometry processing here
// afterRoot(result: GLTF): Promise<void> | null {
// result.scene.traverse((object: any) => {
// const mat = object.material?.userData?._hasCustomBump
// if (!mat) return
// const geom = object.geometry
// if (!geom.attributes.tangent) {
// geom.computeTangents()
// geom.attributes.tangent.needsUpdate = true
// }
// })
// return null
// }
}
const glTFMaterialsCustomBumpMapExport = (w: GLTFWriter2)=> ({
writeMaterial: (material: any, materialDef: any) => {
if (!material.isMeshStandardMaterial || !material.userData._hasCustomBump) return
if ((material.userData._customBumpScale || 0) < 0.001) return // todo: is this correct?
materialDef.extensions = materialDef.extensions || {}
const extensionDef: any = {}
extensionDef.customBumpScale = material.userData._customBumpScale || 1.0
if (material.userData._customBumpMap) {
const customBumpMapDef = {index: w.processTexture(material.userData._customBumpMap)}
w.applyTextureTransform(customBumpMapDef, material.userData._customBumpMap)
extensionDef.customBumpMap = customBumpMapDef
}
materialDef.extensions[ CustomBumpMapPlugin.CUSTOM_BUMP_MAP_GLTF_EXTENSION ] = extensionDef
w.extensionsUsed[ CustomBumpMapPlugin.CUSTOM_BUMP_MAP_GLTF_EXTENSION ] = true
},
})