render: SSAO

This commit is contained in:
Edgaru089 2022-02-05 19:25:44 +08:00
parent 05a85ac27f
commit 92b0ace7a2
9 changed files with 289 additions and 26 deletions

View File

@ -9,6 +9,16 @@ var (
//go:embed shader/world/shadowmap.vert
WorldShaderShadowmapVert string
//go:embed shader/world/ssao.frag
WorldShaderSSAOFrag string
//go:embed shader/world/ssao.vert
WorldShaderSSAOVert string
//go:embed shader/world/ssao_blur.frag
WorldShaderSSAOBlurFrag string
//go:embed shader/world/ssao_blur.vert
WorldShaderSSAOBlurVert string
//go:embed shader/world/geometry.frag
WorldShaderGeometryFrag string
//go:embed shader/world/geometry.vert

View File

@ -4,7 +4,7 @@ uniform sampler2D tex;
in vec3 fragPosWorld;
in float fragPosLightspaceZ;
in float fragDepthNDC;
in float fragDepthView;
in vec2 fragTexCoord;
in vec3 fragNormal;
in float fragLight;
@ -19,9 +19,9 @@ const float gamma = 2.2;
void main() {
outputPosition.xyz = fragPosWorld;
outputPosition.w = fragPosLightspaceZ;
outputPosition.w = fragDepthView;
outputNormal.xyz = fragNormal;
outputNormal.w = fragDepthNDC;
outputNormal.w = fragPosLightspaceZ;
outputColor = texture(tex, fragTexCoord);
outputColor = vec4(pow(outputColor.rgb, vec3(gamma)), outputColor.a);
}

View File

@ -14,7 +14,7 @@ layout (location = 3) in float light;
out vec3 fragPosWorld;
out float fragPosLightspaceZ;
out float fragDepthNDC;
out float fragDepthView;
out vec2 fragTexCoord;
out vec3 fragNormal;
out float fragLight;
@ -25,14 +25,16 @@ void main() {
fragNormal = normalize(normal);
fragLight = light;
gl_Position = projection * view * model * vec4(vert, 1);
fragDepthNDC = gl_Position.z / gl_Position.w;
vec4 pos4 = model * vec4(vert, 1);
fragPosWorld = pos4.xyz / pos4.w;
vec4 fragPosLightspace = lightspace * vec4(fragPosWorld, 1.0f);
fragPosLightspaceZ = fragPosLightspace.z / fragPosLightspace.w *0.5f + 0.5f;
vec4 posView = view * pos4;
fragDepthView = posView.z;
gl_Position = projection * posView;
fragPosWorld -= viewPos;
}

View File

@ -6,6 +6,8 @@ uniform vec3 viewPos;
uniform vec3 sun;
uniform vec4 fogColor;
uniform sampler2D ssaoAmbient; // Ambient strength from SSAO pass
// G-Buffers
uniform sampler2D gPos;
uniform sampler2D gNorm;
@ -40,12 +42,12 @@ void loadGBuffer() {
fragNormal = fragGNormal.xyz;
if (fragNormal == vec3(0.0f, 0.0f, 0.0f))
discard;
fragPosLightspaceZ = fragGNormal.w;
gl_FragDepth = fragGNormal.w * 0.5 + 0.5;
vec4 fragGPos = texture(gPos, fragPosScreen);
fragPos = vec4(fragGPos.xyz + viewPos, 1.0f);
fragPosLightspaceZ = fragGPos.w;
fragColor = texture(gColor, fragPosScreen);
fragPosLightspace = lightspace * fragPos;
@ -56,7 +58,7 @@ void main() {
loadGBuffer();
light = ambient;
light = ambient * texture(ssaoAmbient, fragPosScreen).r;
lightSun();

View File

@ -0,0 +1,78 @@
#version 330
#define SSAO_SAMPLE_COUNT 32
const float radius = 0.5, bias = 0;
uniform vec3 viewPos;
uniform mat4 view, projection;
uniform float time; // current time in seconds, for extra noise
uniform sampler2D rand;
uniform vec2 randSize; // in pixels
// SSAO samples (normalized, in tangent space)
layout (std140) uniform uboSamples {
vec3 samples[SSAO_SAMPLE_COUNT];
};
// G-Buffers
uniform sampler2D gPos;
uniform sampler2D gNorm;
// Fragment information from G-Buffers
vec3 fragPos; // World position
vec3 fragNormal; // World normal
float fragDepthView;
in vec2 fragPosScreen;
layout (location = 0) out float output;
// A random number generator from the web.
// https://stackoverflow.com/questions/12964279/whats-the-origin-of-this-glsl-rand-one-liner
float whatever(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
void loadGBuffer() {
vec4 fragGNormal = texture(gNorm, fragPosScreen);
fragNormal = fragGNormal.xyz;
if (fragNormal == vec3(0.0f, 0.0f, 0.0f))
discard;
vec4 fragGPos = texture(gPos, fragPosScreen);
fragPos = fragGPos.xyz + viewPos;
fragDepthView = fragGPos.w;
gl_FragDepth = fragGPos.w * 0.5 + 0.5;
}
void main() {
loadGBuffer();
vec4 randval = texture(rand, gl_FragCoord.xy / randSize);
vec3 tangent = normalize(randval.xyz - fragNormal*dot(randval.xyz, fragNormal));
vec3 bitangent = cross(fragNormal, tangent);
mat3 TBN = mat3(tangent, bitangent, fragNormal);
float occlusion = 0;
for (int i = 0; i < SSAO_SAMPLE_COUNT; i++) {
vec3 samplePos = TBN * samples[i];
samplePos = fragPos + samplePos * radius;
vec4 viewpos = view * vec4(samplePos, 1.0);
vec4 ndcpos = projection * viewpos;
ndcpos.xyz /= ndcpos.w;
float sampleDepth = texture(gPos, ndcpos.xy*0.5 + 0.5).w;
float rangeCheck = smoothstep(0.0, 1.0, radius / abs(fragDepthView - sampleDepth));
occlusion += (sampleDepth >= viewpos.z/viewpos.w + bias ? 1.0 : 0.0) * rangeCheck;
}
output = 1.0 - (occlusion / SSAO_SAMPLE_COUNT);
}

View File

@ -0,0 +1,12 @@
#version 330
layout (location = 0) in vec2 vert;
layout (location = 1) in vec2 texCoord;
out vec2 fragPosScreen;
void main() {
gl_Position = vec4(vert, 0.0f, 1);
fragPosScreen = texCoord;
}

View File

@ -0,0 +1,20 @@
#version 330
uniform sampler2D input;
uniform vec2 screenSize;
in vec2 fragPosScreen;
layout (location = 0) out float output;
void main() {
output = 0;
for (int i = -3; i <= 3; i++)
for (int j = -3; j <= 3; j++)
output += texture(input, fragPosScreen + vec2(i, j) / screenSize).r;
output /= 49.0;
}

View File

@ -0,0 +1,12 @@
#version 330
layout (location = 0) in vec2 vert;
layout (location = 1) in vec2 texCoord;
out vec2 fragPosScreen;
void main() {
gl_Position = vec4(vert, 0.0f, 1);
fragPosScreen = texCoord;
}

View File

@ -1,8 +1,14 @@
package render
import (
"errors"
"math/rand"
"time"
"unsafe"
"edgaru089.ml/go/gl01/internal/asset"
"edgaru089.ml/go/gl01/internal/io"
"edgaru089.ml/go/gl01/internal/util"
"edgaru089.ml/go/gl01/internal/util/itype"
"edgaru089.ml/go/gl01/internal/world"
"github.com/go-gl/gl/all-core/gl"
@ -10,14 +16,22 @@ import (
"github.com/inkyblackness/imgui-go/v4"
)
const (
SSAOSampleCount = 32 // Number of samples in the SSAO pass. Must stay the same with ssao.frag
)
var (
ShadowmapSize = itype.Vec2i{6144, 6144} // Size of the shadow mapping
RandomSize = itype.Vec2i{32, 32} // Size of the random mapping
)
// WorldRenderer holds texture/shader resource and viewport
// information for world rendering.
type WorldRenderer struct {
lastDisplaySize itype.Vec2i
startTime time.Time
texRand uint32 // random texture mapping, RGBA8 (0~1)
// Depth mapping pass
depthmap struct {
@ -29,12 +43,27 @@ type WorldRenderer struct {
gbuffer struct {
fbo uint32 // The Framebuffer object.
// Textures. Position/Lightspace Depth; Normal/Depth; Diffuse Color/Specular Intensity.
// Textures. Position/Depth(View Space); Normal/Lightspace Depth; Diffuse Color/Specular Intensity.
pos, norm, color uint32
depth uint32
depth uint32 // Depth renderbuffer.
shader *Shader // Geometry pass shaders.
}
// Screen-Space Ambient Occlusion (SSAO) pass
ssao struct {
fbo uint32 // Framebuffer
ambient uint32 // Ambient strength output texture [0,1] (Red channel)
uboSamples uint32 // Uniform Buffer Object pointing to the array of samples
shader *Shader // SSAO pass shader
// SSAO blur pass
blur struct {
fbo uint32
output uint32
shader *Shader
}
}
// Deferred lighting pass
lighting struct {
shader *Shader // Deferred lighting pass shaders
@ -47,7 +76,7 @@ type WorldRenderer struct {
// Output pass
output struct {
fbo uint32 // Output framebuffer object.
fbo uint32 // Output framebuffer object, rendering to the output texture.
tex uint32 // Output texture, rendered to the back buffer at the end.
//depth uint32 // Output depth renderbuffer, use gbuffer.depth
shader *Shader // Shader used to copy output.tex to back buffer.
@ -64,23 +93,31 @@ func (r *WorldRenderer) Init(w *world.World) (err error) {
r.depthmap.shader, err = NewShader(asset.WorldShaderShadowmapVert, asset.WorldShaderShadowmapFrag)
if err != nil {
return err
return errors.New("depthmap: " + err.Error())
}
r.gbuffer.shader, err = NewShader(asset.WorldShaderGeometryVert, asset.WorldShaderGeometryFrag)
if err != nil {
return err
return errors.New("gbuffer: " + err.Error())
}
r.ssao.shader, err = NewShader(asset.WorldShaderSSAOVert, asset.WorldShaderSSAOFrag)
if err != nil {
return errors.New("ssao: " + err.Error())
}
r.ssao.blur.shader, err = NewShader(asset.WorldShaderSSAOBlurVert, asset.WorldShaderSSAOBlurFrag)
if err != nil {
return errors.New("ssao_blur: " + err.Error())
}
r.lighting.shader, err = NewShader(asset.WorldShaderLightingVert, asset.WorldShaderLightingFrag)
if err != nil {
return err
return errors.New("lighting: " + err.Error())
}
r.water.shader, err = NewShader(asset.WorldShaderWaterVert, asset.WorldShaderWaterFrag)
if err != nil {
return err
return errors.New("water: " + err.Error())
}
r.output.shader, err = NewShader(asset.WorldShaderOutputVert, asset.WorldShaderOutputFrag)
if err != nil {
return err
return errors.New("output: " + err.Error())
}
asset.InitWorldTextureAtlas()
@ -97,6 +134,23 @@ func (r *WorldRenderer) Init(w *world.World) (err error) {
gl.BindFragDataLocation(r.water.shader.Handle(), 0, gl.Str("outputColor\x00"))
gl.BindFragDataLocation(r.output.shader.Handle(), 0, gl.Str("outputColor\x00"))
// generate random mapping
{
data := make([]uint32, RandomSize[0]*RandomSize[1])
for i := range data {
data[i] = rand.Uint32()
}
gl.GenTextures(1, &r.texRand)
gl.BindTexture(gl.TEXTURE_2D, r.texRand)
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, int32(RandomSize[0]), int32(RandomSize[1]), 0, gl.RGBA, gl.UNSIGNED_BYTE, util.Ptr(data))
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
}
r.ssao.shader.SetUniformTextureHandle("rand", r.texRand)
r.ssao.shader.SetUniformVec2f("randSize", RandomSize.ToFloat32())
// generate the depthmap and depthmap FBO
gl.GenFramebuffers(1, &r.depthmap.fbo)
gl.GenTextures(1, &r.depthmap.tex)
@ -126,6 +180,10 @@ func (r *WorldRenderer) Init(w *world.World) (err error) {
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RGBA, gl.FLOAT, nil)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_BORDER)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_BORDER)
borderColor = []float32{1, 1, 1, 1}
gl.TexParameterfv(gl.TEXTURE_2D, gl.TEXTURE_BORDER_COLOR, &borderColor[0])
gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, r.gbuffer.pos, 0)
// normal
gl.GenTextures(1, &r.gbuffer.norm)
@ -153,6 +211,48 @@ func (r *WorldRenderer) Init(w *world.World) (err error) {
r.lighting.shader.SetUniformTextureHandle("gPos", r.gbuffer.pos)
r.lighting.shader.SetUniformTextureHandle("gNorm", r.gbuffer.norm)
r.lighting.shader.SetUniformTextureHandle("gColor", r.gbuffer.color)
r.ssao.shader.SetUniformTextureHandle("gPos", r.gbuffer.pos)
r.ssao.shader.SetUniformTextureHandle("gNorm", r.gbuffer.norm)
// generate SSAO friends
gl.GenFramebuffers(1, &r.ssao.fbo)
gl.BindFramebuffer(gl.FRAMEBUFFER, r.ssao.fbo)
// ambient strength texture
gl.GenTextures(1, &r.ssao.ambient)
gl.BindTexture(gl.TEXTURE_2D, r.ssao.ambient)
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RED, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RED, gl.UNSIGNED_BYTE, nil)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, r.ssao.ambient, 0)
r.ssao.blur.shader.SetUniformTextureHandle("input", r.ssao.ambient)
// uniform buffer object for samples
ssaoSamples := make([]itype.Vec4f, SSAOSampleCount)
for i := range ssaoSamples {
sample := itype.Vec3d{rand.Float64()*2 - 1, rand.Float64()*2 - 1, rand.Float64() + 0.05}
sample = sample.Normalize().Multiply(rand.Float64()).Multiply(rand.Float64())
ssaoSamples[i] = itype.Vec4f{
float32(sample[0]),
float32(sample[1]),
float32(sample[2]),
0,
}
}
gl.GenBuffers(1, &r.ssao.uboSamples)
gl.BindBuffer(gl.UNIFORM_BUFFER, r.ssao.uboSamples)
gl.BufferData(gl.UNIFORM_BUFFER, int(unsafe.Sizeof(float32(0))*4*SSAOSampleCount), util.Ptr(ssaoSamples), gl.STATIC_DRAW)
// bind UBO (onto binding 0 for now)
gl.BindBufferBase(gl.UNIFORM_BUFFER, 0, r.ssao.uboSamples)
gl.UniformBlockBinding(r.ssao.shader.Handle(), gl.GetUniformBlockIndex(r.ssao.shader.Handle(), gl.Str("uboSamples\x00")), 0)
// SSAO blur pass
gl.GenFramebuffers(1, &r.ssao.blur.fbo)
gl.BindFramebuffer(gl.FRAMEBUFFER, r.ssao.blur.fbo)
gl.GenTextures(1, &r.ssao.blur.output)
gl.BindTexture(gl.TEXTURE_2D, r.ssao.blur.output)
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RED, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RED, gl.UNSIGNED_BYTE, nil)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, r.ssao.blur.output, 0)
r.lighting.shader.SetUniformTextureHandle("ssaoAmbient", r.ssao.blur.output)
// generate the output texture and friends
gl.GenFramebuffers(1, &r.output.fbo)
@ -171,6 +271,7 @@ func (r *WorldRenderer) Init(w *world.World) (err error) {
gl.BindFramebuffer(gl.FRAMEBUFFER, 0)
r.lastDisplaySize = io.DisplaySize
r.startTime = time.Now()
initScreenQuad()
@ -191,15 +292,19 @@ func (r *WorldRenderer) Render(world *world.World, view *View) {
// re-generate the G-buffers if the display size changed
if r.lastDisplaySize != io.DisplaySize {
gl.BindTexture(gl.TEXTURE_2D, r.gbuffer.pos)
gl.BindTexture(gl.TEXTURE_2D, r.gbuffer.pos) // G-Buffer, Position
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RGBA, gl.FLOAT, nil)
gl.BindTexture(gl.TEXTURE_2D, r.gbuffer.norm) // G-Buffer, Normal
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RGBA, gl.FLOAT, nil)
gl.BindTexture(gl.TEXTURE_2D, r.gbuffer.norm)
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RGBA, gl.FLOAT, nil)
gl.BindTexture(gl.TEXTURE_2D, r.gbuffer.color)
gl.BindTexture(gl.TEXTURE_2D, r.gbuffer.color) // G-Buffer, Albedo Color
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RGBA, gl.UNSIGNED_BYTE, nil)
gl.BindRenderbuffer(gl.RENDERBUFFER, r.gbuffer.depth)
gl.BindRenderbuffer(gl.RENDERBUFFER, r.gbuffer.depth) // G-Buffer, Depth (Renderbuffer)
gl.RenderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]))
gl.BindTexture(gl.TEXTURE_2D, r.output.tex)
gl.BindTexture(gl.TEXTURE_2D, r.ssao.ambient) // SSAO Output Ambient Strength
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RED, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RED, gl.UNSIGNED_BYTE, nil)
gl.BindTexture(gl.TEXTURE_2D, r.ssao.blur.output) // SSAO Blurred Output
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RED, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RED, gl.UNSIGNED_BYTE, nil)
gl.BindTexture(gl.TEXTURE_2D, r.output.tex) // Output Texture
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, int32(io.DisplaySize[0]), int32(io.DisplaySize[1]), 0, gl.RGBA, gl.UNSIGNED_BYTE, nil)
r.lastDisplaySize = io.DisplaySize
}
@ -250,7 +355,29 @@ func (r *WorldRenderer) Render(world *world.World, view *View) {
world.Render()
// 3. Render the actual output with deferred lighting
// 3/1. SSAO pass
gl.BindFramebuffer(gl.FRAMEBUFFER, r.ssao.fbo)
gl.ClearColor(1, 1, 1, 1)
gl.Clear(gl.COLOR_BUFFER_BIT)
r.ssao.shader.UseProgram()
r.ssao.shader.BindTextures()
r.ssao.shader.SetUniformMat4("view", view.View())
r.ssao.shader.SetUniformMat4("projection", view.Perspective())
r.ssao.shader.SetUniformVec3f("viewPos", view.EyePos)
r.ssao.shader.SetUniformFloat("time", float32(time.Since(r.startTime).Seconds()))
DrawScreenQuad()
// 3/2. SSAO blur pass (TODO)
gl.BindFramebuffer(gl.FRAMEBUFFER, r.ssao.blur.fbo)
r.ssao.blur.shader.UseProgram()
r.ssao.blur.shader.BindTextures()
r.ssao.blur.shader.SetUniformVec2f("screenSize", r.lastDisplaySize.ToFloat32())
DrawScreenQuad()
// 4. Render the actual output with deferred lighting
gl.BindFramebuffer(gl.FRAMEBUFFER, r.output.fbo)
gl.ClearColor(io.ClearColor[0], io.ClearColor[1], io.ClearColor[2], io.ClearColor[3])
gl.Clear(gl.COLOR_BUFFER_BIT)
@ -264,7 +391,7 @@ func (r *WorldRenderer) Render(world *world.World, view *View) {
DrawScreenQuad()
// 4. Render water
// 5. Render water
gl.Enable(gl.DEPTH_TEST)
gl.DepthFunc(gl.LESS)
gl.Enable(gl.CULL_FACE)