class SSGIPass {
constructor(scene, camera) {
this.scene = scene;
this.camera = camera;
code
// 创建RT纹理
this.gBufferRT = new THREE.WebGLRenderTarget(
window.innerWidth,
window.innerHeight,
{
minFilter: THREE.NearestFilter,
magFilter: THREE.NearestFilter,
format: THREE.RGBAFormat,
type: THREE.FloatType
}
);
// 创建法线和位置缓冲
this.normalRT = this.gBufferRT.clone();
this.positionRT = this.gBufferRT.clone();
// 创建SSGI着色器
this.ssgiMaterial = new THREE.ShaderMaterial({
uniforms: {
tDiffuse: { value: null },
tNormal: { value: null },
tPosition: { value: null },
cameraNear: { value: camera.near },
cameraFar: { value: camera.far },
resolution: { value: new THREE.Vector2(window.innerWidth, window.innerHeight) },
cameraProjectionMatrix: { value: camera.projectionMatrix },
cameraInverseProjectionMatrix: { value: camera.projectionMatrixInverse }
},
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position, 1.0);
}
`,
fragmentShader: `
uniform sampler2D tDiffuse;
uniform sampler2D tNormal;
uniform sampler2D tPosition;
uniform float cameraNear;
uniform float cameraFar;
uniform vec2 resolution;
uniform mat4 cameraProjectionMatrix;
uniform mat4 cameraInverseProjectionMatrix;
varying vec2 vUv;
float rand(vec2 co) {
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
vec3 getWorldPos(float depth, vec2 coord) {
float z = depth * 2.0 - 1.0;
vec4 clipSpacePosition = vec4(coord * 2.0 - 1.0, z, 1.0);
vec4 viewSpacePosition = cameraInverseProjectionMatrix * clipSpacePosition;
viewSpacePosition /= viewSpacePosition.w;
return viewSpacePosition.xyz;
}
void main() {
vec2 uv = vUv;
vec3 normal = texture2D(tNormal, uv).rgb * 2.0 - 1.0;
vec3 position = texture2D(tPosition, uv).rgb;
vec3 diffuse = texture2D(tDiffuse, uv).rgb;
vec3 indirectLight = vec3(0.0);
float samples = 64.0;
float radius = 1.0;
for(float i = 0.0; i < samples; i++) {
float theta = rand(uv + vec2(i)) * 2.0 * 3.14159;
float phi = rand(uv + vec2(i + 1.0)) * 3.14159 * 0.5;
vec3 sampleVector = vec3(
sin(phi) * cos(theta),
sin(phi) * sin(theta),
cos(phi)
);
sampleVector = normalize(sampleVector);
if(dot(normal, sampleVector) < 0.0) sampleVector = -sampleVector;
vec3 samplePos = position + sampleVector * radius;
vec4 offset = cameraProjectionMatrix * vec4(samplePos, 1.0);
offset.xyz /= offset.w;
offset.xyz = offset.xyz * 0.5 + 0.5;
vec3 sampleNormal = texture2D(tNormal, offset.xy).rgb * 2.0 - 1.0;
vec3 sampleDiffuse = texture2D(tDiffuse, offset.xy).rgb;
float occlusion = max(0.0, dot(normal, sampleVector));
indirectLight += sampleDiffuse * occlusion;
}
indirectLight /= samples;
vec3 finalColor = diffuse + indirectLight * 0.5;
gl_FragColor = vec4(finalColor, 1.0);
}
`
});