From 116952bec8a69e53725f32044b658446d8a6458e Mon Sep 17 00:00:00 2001 From: saschawillems Date: Wed, 28 Sep 2016 20:54:45 +0200 Subject: [PATCH] Started work on MSAA with deferred rendering example --- data/shaders/deferredmultisampling/debug.frag | 55 + .../deferredmultisampling/debug.frag.spv | Bin 0 -> 3268 bytes data/shaders/deferredmultisampling/debug.vert | 23 + .../deferredmultisampling/debug.vert.spv | Bin 0 -> 1364 bytes .../deferredmultisampling/deferred.frag | 103 ++ .../deferredmultisampling/deferred.frag.spv | Bin 0 -> 6148 bytes .../deferredmultisampling/deferred.vert | 26 + .../deferredmultisampling/deferred.vert.spv | Bin 0 -> 1468 bytes data/shaders/deferredmultisampling/mrt.frag | 33 + .../deferredmultisampling/mrt.frag.spv | Bin 0 -> 2412 bytes data/shaders/deferredmultisampling/mrt.vert | 52 + .../deferredmultisampling/mrt.vert.spv | Bin 0 -> 3340 bytes .../deferredmultisampling.cpp | 1206 +++++++++++++++++ .../deferredmultisampling.vcxproj | 103 ++ .../deferredmultisampling.vcxproj.filters | 65 + vulkanExamples.sln | 11 + 16 files changed, 1677 insertions(+) create mode 100644 data/shaders/deferredmultisampling/debug.frag create mode 100644 data/shaders/deferredmultisampling/debug.frag.spv create mode 100644 data/shaders/deferredmultisampling/debug.vert create mode 100644 data/shaders/deferredmultisampling/debug.vert.spv create mode 100644 data/shaders/deferredmultisampling/deferred.frag create mode 100644 data/shaders/deferredmultisampling/deferred.frag.spv create mode 100644 data/shaders/deferredmultisampling/deferred.vert create mode 100644 data/shaders/deferredmultisampling/deferred.vert.spv create mode 100644 data/shaders/deferredmultisampling/mrt.frag create mode 100644 data/shaders/deferredmultisampling/mrt.frag.spv create mode 100644 data/shaders/deferredmultisampling/mrt.vert create mode 100644 data/shaders/deferredmultisampling/mrt.vert.spv create mode 100644 deferredmultisampling/deferredmultisampling.cpp create mode 100644 deferredmultisampling/deferredmultisampling.vcxproj create mode 100644 deferredmultisampling/deferredmultisampling.vcxproj.filters diff --git a/data/shaders/deferredmultisampling/debug.frag b/data/shaders/deferredmultisampling/debug.frag new file mode 100644 index 00000000..7e00f775 --- /dev/null +++ b/data/shaders/deferredmultisampling/debug.frag @@ -0,0 +1,55 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2DMS samplerPosition; +layout (binding = 2) uniform sampler2DMS samplerNormal; +layout (binding = 3) uniform sampler2DMS samplerAlbedo; + +layout (location = 0) in vec3 inUV; + +layout (location = 0) out vec4 outFragColor; + +#define NUM_SAMPLES 8 + +vec4 resolve(sampler2DMS tex, ivec2 uv) +{ + vec4 result = vec4(0.0); + int count = 0; + for (int i = 0; i < NUM_SAMPLES; i++) + { + vec4 val = texelFetch(tex, uv, i); + result += val; + count++; + } + return result / float(NUM_SAMPLES); +} + +void main() +{ + ivec2 attDim = textureSize(samplerPosition); + ivec2 UV = ivec2(inUV.st * attDim * 2.0); + + highp int index = 0; + if (inUV.s > 0.5) + { + index = 1; + UV.s -= attDim.x; + } + if (inUV.t > 0.5) + { + index = 2; + UV.t -= attDim.y; + } + + vec3 components[3]; + components[0] = resolve(samplerPosition, UV).rgb; + components[1] = resolve(samplerNormal, UV).rgb; + components[2] = resolve(samplerAlbedo, UV).rgb; + // Uncomment to display specular component + //components[2] = vec3(texture(samplerAlbedo, inUV.st).a); + + // Select component depending on UV + outFragColor.rgb = components[index]; +} \ No newline at end of file diff --git a/data/shaders/deferredmultisampling/debug.frag.spv b/data/shaders/deferredmultisampling/debug.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..b334d148778c1283fbd580b2060d6399866eac5a GIT binary patch literal 3268 zcmZ9NX>(Ln5QcBa!fF5$cElv0q98&51tTy4BpL%j5O*DhWDFA~bHmIe;1&XEm7n}C ze)Xe2%B@Pv=ehTGIp(C^>VA7U-F?ovlkRl~*C$CAe;bnTlYDJY*1?lRIf~qz^ksZv z>gLq3R(tl?snf@e>`%HCnQv>dKIuUh3zb?!dkL(7ZNzD(5L!38Cdsc9=t(vv6I12! z8yCy1>SCo?X;;gwyOr5$vz*?Uug$DMmNv5dbJ%aapYL5luQg;j zpUn6yUCDcsdE`vGu$VTg4bQ>;?qTzoCwgMqJ>T3gH_?yO=Dx<7Gk`Ql`w_VDJAmsb9_>4UwoaJ43!Az2V6Jix za0MSmxBo%9^en@E485!1);tMV<74b&f8M3bInE=E@!YL@0coywPo@t#Y} zG=a`4d5-U(49Qsfl)m7k-YcmF!@K4;;1TyDDy-;DhY;BVe}y0tgCxt_;G zPy*9rjw3GtZNk+BjCG&O!2A?$?3;z{2d0-_0p@G}sj$6O*e8&UVxPCswcC$pBUkra zeBa~b`bMsS67cQVgYRV;X#a(n5#+mt&G+*=d)!32{vuxA4WP|CQja=*AJ*|c-UH4R zb$oBP3VX!(18uLJF(1ISKVctpJ_Op#jl7T0BhT7$xP*sST>vZmaesQG24=e~#N@~HV0x-}mF zeNppkbbZ3Lw&pk3ta%$)Q*Mqmz0*fv62!Tzq8qQ>7|-%CSS`3`{sgRmY5r5lzbkCU z^?+XBx7ZD=X{<4S)7=^1Z=`w7m5$Esj)i*> zPQD+wm$~ZZ`rG^*aAvu`q0a;7j=f(%cklS^K8$WonN#o#Uj*9BD*@x3&$;!vk8v*n zZNZPAdmfLAyEuxj&A2!#ZPCZe=$_ds@tcsZ0B!M>^=b2rJTK=|M*eYh=ZO3h=-MJ* lpSI3B@VuhmQFQygUd(+8{p1?_Sj=)7yYa^SLmzVA-M@gW{3rkb literal 0 HcmV?d00001 diff --git a/data/shaders/deferredmultisampling/debug.vert b/data/shaders/deferredmultisampling/debug.vert new file mode 100644 index 00000000..8082ff78 --- /dev/null +++ b/data/shaders/deferredmultisampling/debug.vert @@ -0,0 +1,23 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; +} ubo; + +layout (location = 0) out vec3 outUV; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + outUV = vec3((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2, 0.0); + gl_Position = vec4(outUV.st * 2.0f - 1.0f, 0.0f, 1.0f); +} diff --git a/data/shaders/deferredmultisampling/debug.vert.spv b/data/shaders/deferredmultisampling/debug.vert.spv new file mode 100644 index 0000000000000000000000000000000000000000..1f650e391949d1bef06b3c063ee725cd1ec9c34d GIT binary patch literal 1364 zcmZ9LTWb?h5XVn*^HOcCwHI&grtw}4MXCs*wtY#3Kv$)GUAD~wgY@m;V?|vu| z{7SwE{(tA}!RUm^%>2*X&dk|rrFG7j8U4HXam%ELEPWy#qMGreXhxdu<3JF{7AenZ{G(P)KNSbGu)TIuUogat0&d8_!E)C`)IM|ip5+U zeND$<6SpJwabP}<+T@}(y>gEYG34#0GtHvB@M|iD*MYt)tsxnRR}@cPY|aDOyc~4! zm!-`f!IorSlnlf(R@UsC(82L%M$8Xvv-F?)&*uL0!a22<#Ss0hN`mp0)>M@_gVEa! zN%{bz7PfoOe{0#~?x{Sb;hUt-MbXNfJ8I5W!>$9=Af!F`@Z>E!V- z*QA3@$1KSP50!!4u87G4&ir4iL-q_#UVQi_zz$?F%k>iT-wHearan1qmgj+FSYj>d z%oqMzVt1tD%h@|&+~=+s9P-#b>0s0dRi8cF7vswrJ(G7=IoR7nF>itWa~EvcN70173>lV967g|b5s7ti9me2yV(>7_bshaMVqNw3Dc}X6;_K&NX9&{>!swGUeB8W~KS8Fl`_2)vX z#Vc$4Jow2e^|P|2@co5y|74j;dP_sYRhH|R8a#JH9cxKo{9^pZDiiQc+3E13mGO~6 zSzA-K1i4T?SRAO-j!Fz8C2CG<;aPk+E`d zoUPQ`<@$G`-%oM&_b&L-s8W5sd!U?WE&fCBDZV=$aV_S<=pA2{L2k}I1|1wP3~f!l zca4vui*vtU|1>`jz&|`cE!l&}X^ov}tZHj~6McTJzHg3`Yc^#+JVpNTBjlFaJ*-St zw^3G%MApN8JMi;-{kF4G%+rdx>ZDE|b>5foa|YBoR((6s#>+2)i#{yjjq}}8wx0OpLp}rl8OZvzQQyquq;4VdteU>=zZiKovO3q& zzZGh%dhL&bx}N=M=N#rh)tOgceNKbwW6kDR05ykt<%LN$t{u-s$)=ysz7jukoC*9^ zkwJfZqb?6~o`udetld~?JMimFatFNoUcm0201dx&@YBF5R%SM?-m2GM**l{y;=Ln&AwO6bPpZ#zP}+mbH2SHYrp>#`GK5le&5=>zi(|`_N@(B zf8Sc=jnwb#z7yE*0c7>>O1fcWXXxEYw~5^!PqMN0|9!yTE9-kV(5I5@?@ziTbWHyb z0AtjTrkD>Vz4`5(a^(96ygF_6O?f@j;8}eX_8gXZH!H zXDIzAHGB&CY2c^*UZ{4dbfQTZ_bI-cxUYAzSC=w!@JfVa=6xCfI7d>{S{uFwTJF+N!I|~o$kor;f>c{`zUbD6Hsmc zCBp^4_uMm{5B%nU^YNProtyYp=se*0JR0h|z7V<$Oi%Jz(6*ecePxneSKsA8z75(A zJh!u<=9T*PJO=t$;HUj@Q0>x~i^s#afp~kK2(Qj_@$FGw0nBBrys8D)1Fz1wE}*}AaO$^>w+GIG_H%(c{h~kW+_U?) zZfVrD7QPL{T{sV3UEBq2>he8x|FQo0@U9+ndE9N`)Y+z37)@F=nsJ@$=*83b_z0Pyg`P`HG zdY#WhRww*Ut+NkZzRpXLjZyEK&dH@9>MX#kvrhMQ5SY`RYl|555z`MJdoyMLM2xoR zhk9dXK?gyc%`kik#Mx*Y0{Ysk%YgQfFNe2Rt(>d&5#V~>Ic;U&o1(1(wENb3ch!vn zb854;V$#Ka#*w|B(Sr&2*pD`2yg%wAW)faq$W!q4^CCYPkW{ROM$g| z-}TjQ-Xlf;=4f;V@ZgFfay3e{#V&*7CIe-5ugj&snK zKZjQ%Yxgc6fZhT;hns=8t>IurHUYG+n2NuFe>fqvTc^Qn(l_(4fIj)-9JhM z|0Q1pzu)W*L?@h_^L=w}b7r{;Nc!I`31+a>0FQEW?E-;VI%-aDHQ zn>9`oPDVQM4Fk{oPLn}6lBNd3og62oTb^TGm<8q>a}sLr%iHw{$LcB`jv3>R-*h}Z zf~mQ$eb-mR;-Vj!rp=!gHJpzgh`D6BB90u>abV(hBrXol#nBtNTyLCnL&Bn0aLXcN zmgI$BOEJ7M>=ju}X-~2$fAWIa^Mq%l@r8d?V%`DVvhb|5C#hInw{ygX$DbK8U%1WE zfBrwr`Kd?!RcY$;_SRK}xx>-RRcY$NksHi+0OxXFm(2o`=cYww$KhKRe|_ulMzL@6 z-<3@+>e0)6X>!0(|A92;fTuo~w*bffW@)=wfq5J3uWA3WG`Wkj755E?5dTD)IdGrk z2XlXLFZ3$V#Ioq=w;0~aYq8AxqJ&xh6boJ`Ip+PVCg89$Njh*o^0+1`BwV1WaH~e-ixE( swgjH#xZASfDw4h`GUq!IeA(lk$-Ao@-19vNZ-@6nzhM0TD8oz1Uu$h)V*mgE literal 0 HcmV?d00001 diff --git a/data/shaders/deferredmultisampling/mrt.frag b/data/shaders/deferredmultisampling/mrt.frag new file mode 100644 index 00000000..5a8f5436 --- /dev/null +++ b/data/shaders/deferredmultisampling/mrt.frag @@ -0,0 +1,33 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (binding = 1) uniform sampler2D samplerColor; +layout (binding = 2) uniform sampler2D samplerNormalMap; + +layout (location = 0) in vec3 inNormal; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inWorldPos; +layout (location = 4) in vec3 inTangent; + +layout (location = 0) out vec4 outPosition; +layout (location = 1) out vec4 outNormal; +layout (location = 2) out vec4 outAlbedo; + +void main() +{ + outPosition = vec4(inWorldPos, 1.0); + + // Calculate normal in tangent space + vec3 N = normalize(inNormal); + N.y = -N.y; + vec3 T = normalize(inTangent); + vec3 B = cross(N, T); + mat3 TBN = mat3(T, B, N); + vec3 tnorm = TBN * normalize(texture(samplerNormalMap, inUV).xyz * 2.0 - vec3(1.0)); + outNormal = vec4(tnorm, 1.0); + + outAlbedo = texture(samplerColor, inUV); +} \ No newline at end of file diff --git a/data/shaders/deferredmultisampling/mrt.frag.spv b/data/shaders/deferredmultisampling/mrt.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..129538fdc15741bdefad7c0282e27c5dd8cd7442 GIT binary patch literal 2412 zcmY+FYjadZ5QfKWHXwwX+{Md=sHk8>42UAIS(G4#5Fils%hrKx#nsK()b8?GtNd=2 zf5~6v7pr`pv(waZQl0L8`!et8nMoQmi~CY~ji3GLr!-y1(hPn|2h&`oSJ$4bEsZDJ zOUqX;n{hZbszh^+q(f;It?U;4(!lG;JaQ6gA>SbD$R_e5a+G@W*%+(AZYljuvso%v z*Saf@JKb?_uNW1RUU&R+vE3VWhtGfMy_k&upF^l$?sNx5x%0Bv>2;T{T;3~Q{F<6{ zs`F`r$Z7a;vN0U@C;edw(yTc4%dO#PunnF-8tDXiay2ghez`sz?G^*fD*i6o?=ap% z_sdPT@0F7ZYotYVC)*#PH#_TO&ZZmKlaf|dY+q`l$Hng6pf{Rs@SxZOs&buIzkK>^ z>NhJsaDPR_z2yM5GI-wG9#(a8=_xw*yfYjON7MS*YUcfN3awUCPU#(kEPc;P-&581 zyX)~*_MNHmHu^l`3V#86Cj0WYo+GW|&a>{zT|e^WUGJxFzo_@lME-HAtXrsV&a}rV z>^ZO&avFZ#D}DL4_`M(Pw~61#zV|`Q`~zt7_02zsc5iX>^_`K}MSOD)BPsoU+x+8L z_O9nUL-S7(KZ9-|F6;HrBF3$M6CIpmzgCW)A$|ed-ofufZ1cr~&nMWfv)uHXXgS)y zzQR98r&|QfbN|~pNzDEA+Zl5{9c=qKck}O{?Imu$zGp5LeC}bh+Lx%5`+dZjg;?jg zcsKm6@Vy)1%fq|iGVVEe7u@F>Z$LhtvCEo&K$>WCJ(ClNa|++LTlW`hzBBc`*5kfe z{hRdj8xA4fgGcP*JdR`x^$I(hF*!!wv5d)ggO2um1F_zGly{t3Gd3vwKotHUZBVzi#`4yy{{SMl@<(X`8pS-Jg z5p%>J@@fyDR}pc=<@fnLe^O)oJH#CS4*Zd^?=yZM9rtJr+gf`Y|10M{z?P?RzrnXC z7H9qtTP)_hfi30=>=Cw@{R4ZPvFYrmZ}AD3_2wIox44dNEavnK+rLNp&S?v&&*=wz QbHwGmi5B}82G^1Q0At9SDgXcg literal 0 HcmV?d00001 diff --git a/data/shaders/deferredmultisampling/mrt.vert b/data/shaders/deferredmultisampling/mrt.vert new file mode 100644 index 00000000..0e62ed02 --- /dev/null +++ b/data/shaders/deferredmultisampling/mrt.vert @@ -0,0 +1,52 @@ +#version 450 + +#extension GL_ARB_separate_shader_objects : enable +#extension GL_ARB_shading_language_420pack : enable + +layout (location = 0) in vec4 inPos; +layout (location = 1) in vec2 inUV; +layout (location = 2) in vec3 inColor; +layout (location = 3) in vec3 inNormal; +layout (location = 4) in vec3 inTangent; + +layout (binding = 0) uniform UBO +{ + mat4 projection; + mat4 model; + mat4 view; + vec4 instancePos[3]; +} ubo; + +layout (location = 0) out vec3 outNormal; +layout (location = 1) out vec2 outUV; +layout (location = 2) out vec3 outColor; +layout (location = 3) out vec3 outWorldPos; +layout (location = 4) out vec3 outTangent; + +out gl_PerVertex +{ + vec4 gl_Position; +}; + +void main() +{ + vec4 tmpPos = vec4(inPos.xyz, 1.0) + ubo.instancePos[gl_InstanceIndex]; + + gl_Position = ubo.projection * ubo.view * ubo.model * tmpPos; + + outUV = inUV; + outUV.t = 1.0 - outUV.t; + + // Vertex position in world space + outWorldPos = vec3(ubo.model * tmpPos); + // GL to Vulkan coord space + outWorldPos.y = -outWorldPos.y; + + // Normal in world space + mat3 mNormal = transpose(inverse(mat3(ubo.model))); + outNormal = mNormal * normalize(inNormal); + outTangent = mNormal * normalize(inTangent); + + // Currently just vertex color + outColor = inColor; +} diff --git a/data/shaders/deferredmultisampling/mrt.vert.spv b/data/shaders/deferredmultisampling/mrt.vert.spv new file mode 100644 index 0000000000000000000000000000000000000000..e3f5cb5d1b7a8925d952c94e42cacb962514f4b0 GIT binary patch literal 3340 zcmZ9O>vj}X5JsEa06`Fui;5Tm0*Xe&fG7eYq@t%S8Q@vHK)F>E~o08nhApgCwC^v4*u;*o+kZuAQ=EB$)04S+-GJNX2-j| z)$xgo=k?f^43>`i>`xAq`VgP(W|j-~Ajgr@$j8VP)?1C+mCNmXHT}i-VKSUz$2OOC?x&qz zpSLb~m$sstm4%ttyLQ=^cV2AvmhM;B`_J+cVjnKw0{era(^~D?6oa$StsU?;1vK@frAJ$v)39)X&BFX7xC+ag#{olG`5VyVm2x#yvwKPVWD> zeqFx3et#h|)okf!U(Uc7;tG7C4@>MFIGg7X&xkjdbD2*r^7-DzSikvv?>fF&VQbRv z+t%;d@1!{FzNvT!(cky1W8YF7=ldNFd=OUt1li1|ei+Sn97T?h&$|+vf0WN%>~f0u z1$KK8U#YOY%Nf6y-FWk#1FP>xlH}R-qu^K2j5YruJ`b^vA};;KhY{nCft@q`<&Klh zxiUwHcI$eT-F~!Nm)N(I^PJb&M-l7v9Pu&4bBuq3U7Nh|V((2(`zX7)tmQaSrz&0B zTj=JIGgf@M;^M3`V3+=9+0A7SVRxS70>6(QXJ14&zh`^LAF+F{`kU`EyLNfc7dv;+ z+b8Je3cJ`jl=D3A{Az{GcMaWG&k*0Juy1RA@y&|!P3O_I#d-J8tySLq=JEH=74d86 z;r|HTS|Y#Lxt9xn=U#uYcIUosckb)Y52T{F8?Qaj2TCalaDz6Q(~O+9C06@%SYS=bYtbChY!)M^N*^B33UDB&Fy#M z5^@@`Zu=7JXAWomQ^Yyf=J!Ettn+;xk#p|#_uVED`QPyoPa)p_WU2S#rqLtLykh;L z-_Ovu_xm}VeDpShUhnM|SReVAjoaw*uHe2vm)lX}zO1+b_BpC{K4%f*_1A8leqZII z|F6*H>iypV%l}&4$6a)}h?zr=7;}pCiQX5{xA(pTCqGYZ-suBGE>`egLj>RNukZg& zjkm|}|F+`wbp`(&x_RX5dA_gl^*ldRyqqiY{D^KI`Ffs4jn@`;{t(^X?8BOaZ=zeP zby-93%jll%Ip&m~XJ0`cBF5>nx8hgPtz!()XOTD3KSi|p9t#zA&a|x~a$@J=F_IzX z6hA@C>1=BAyC&a4jMZ-5wTg?pIk=v816&}H_b2qot1a?&(2dn@-Zr~j)VGP=t886% K@xNrcjQj^Lbmjv9 literal 0 HcmV?d00001 diff --git a/deferredmultisampling/deferredmultisampling.cpp b/deferredmultisampling/deferredmultisampling.cpp new file mode 100644 index 00000000..b984496e --- /dev/null +++ b/deferredmultisampling/deferredmultisampling.cpp @@ -0,0 +1,1206 @@ +/* +* Vulkan Example - Multi sampling with explicit resolve for deferred shading example +* +* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de +* +* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) +*/ + +#include +#include +#include +#include +#include + +#define GLM_FORCE_RADIANS +#define GLM_FORCE_DEPTH_ZERO_TO_ONE +#include +#include + +#include +#include "vulkanexamplebase.h" + +#define VERTEX_BUFFER_BIND_ID 0 +#define ENABLE_VALIDATION false +// todo: check if hardware supports sample number (or select max. supported) +#define SAMPLE_COUNT VK_SAMPLE_COUNT_8_BIT + +// Vertex layout for this example +std::vector vertexLayout = +{ + vkMeshLoader::VERTEX_LAYOUT_POSITION, + vkMeshLoader::VERTEX_LAYOUT_UV, + vkMeshLoader::VERTEX_LAYOUT_COLOR, + vkMeshLoader::VERTEX_LAYOUT_NORMAL, + vkMeshLoader::VERTEX_LAYOUT_TANGENT +}; + +class VulkanExample : public VulkanExampleBase +{ +public: + bool debugDisplay = false; + bool useMSAA = true; + bool useSampleShading = true; + + struct { + struct { + vkTools::VulkanTexture colorMap; + vkTools::VulkanTexture normalMap; + } model; + struct { + vkTools::VulkanTexture colorMap; + vkTools::VulkanTexture normalMap; + } floor; + } textures; + + struct { + vkMeshLoader::MeshBuffer model; + vkMeshLoader::MeshBuffer floor; + vkMeshLoader::MeshBuffer quad; + } meshes; + + struct { + VkPipelineVertexInputStateCreateInfo inputState; + std::vector bindingDescriptions; + std::vector attributeDescriptions; + } vertices; + + struct { + glm::mat4 projection; + glm::mat4 model; + glm::mat4 view; + glm::vec4 instancePos[3]; + } uboVS, uboOffscreenVS; + + struct Light { + glm::vec4 position; + glm::vec3 color; + float radius; + }; + + struct { + Light lights[6]; + glm::vec4 viewPos; + glm::ivec2 windowSize; + } uboFragmentLights; + + struct { + vkTools::UniformData vsFullScreen; + vkTools::UniformData vsOffscreen; + vkTools::UniformData fsLights; + } uniformData; + + struct { + VkPipeline deferred; // Deferred lighting calculation + VkPipeline deferredNoMSAA; // Deferred lighting calculation with explicit MSAA resolve + VkPipeline offscreen; // (Offscreen) scene rendering (fill G-Buffers) + VkPipeline offscreenSampleShading; // (Offscreen) scene rendering (fill G-Buffers) with sample shading rate enabled + VkPipeline debug; // G-Buffers debug display + } pipelines; + + struct { + VkPipelineLayout deferred; + VkPipelineLayout offscreen; + } pipelineLayouts; + + struct { + VkDescriptorSet model; + VkDescriptorSet floor; + } descriptorSets; + + VkDescriptorSet descriptorSet; + VkDescriptorSetLayout descriptorSetLayout; + + // Framebuffer for offscreen rendering + struct FrameBufferAttachment { + VkImage image; + VkDeviceMemory mem; + VkImageView view; + VkFormat format; + }; + struct FrameBuffer { + int32_t width, height; + VkFramebuffer frameBuffer; + FrameBufferAttachment position, normal, albedo; + FrameBufferAttachment depth; + VkRenderPass renderPass; + } offScreenFrameBuf; + + // One sampler for the frame buffer color attachments + VkSampler colorSampler; + + VkCommandBuffer offScreenCmdBuffer = VK_NULL_HANDLE; + + // Semaphore used to synchronize between offscreen and final scene rendering + VkSemaphore offscreenSemaphore = VK_NULL_HANDLE; + + VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) + { + zoom = -8.0f; + rotation = { 0.0f, 0.0f, 0.0f }; + enableTextOverlay = true; + title = "Vulkan Example - Deferred shading (2016 by Sascha Willems)"; + camera.type = Camera::CameraType::firstperson; + camera.movementSpeed = 5.0f; +#ifndef __ANDROID__ + camera.rotationSpeed = 0.25f; +#endif + camera.position = { 2.15f, 0.3f, -8.75f }; + camera.setRotation(glm::vec3(-0.75f, 12.5f, 0.0f)); + camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 256.0f); + paused = true; + } + + ~VulkanExample() + { + // Clean up used Vulkan resources + // Note : Inherited destructor cleans up resources stored in base class + + vkDestroySampler(device, colorSampler, nullptr); + + // Frame buffer + + // Color attachments + vkDestroyImageView(device, offScreenFrameBuf.position.view, nullptr); + vkDestroyImage(device, offScreenFrameBuf.position.image, nullptr); + vkFreeMemory(device, offScreenFrameBuf.position.mem, nullptr); + + vkDestroyImageView(device, offScreenFrameBuf.normal.view, nullptr); + vkDestroyImage(device, offScreenFrameBuf.normal.image, nullptr); + vkFreeMemory(device, offScreenFrameBuf.normal.mem, nullptr); + + vkDestroyImageView(device, offScreenFrameBuf.albedo.view, nullptr); + vkDestroyImage(device, offScreenFrameBuf.albedo.image, nullptr); + vkFreeMemory(device, offScreenFrameBuf.albedo.mem, nullptr); + + // Depth attachment + vkDestroyImageView(device, offScreenFrameBuf.depth.view, nullptr); + vkDestroyImage(device, offScreenFrameBuf.depth.image, nullptr); + vkFreeMemory(device, offScreenFrameBuf.depth.mem, nullptr); + + vkDestroyFramebuffer(device, offScreenFrameBuf.frameBuffer, nullptr); + + vkDestroyPipeline(device, pipelines.deferred, nullptr); + vkDestroyPipeline(device, pipelines.deferredNoMSAA, nullptr); + vkDestroyPipeline(device, pipelines.offscreen, nullptr); + vkDestroyPipeline(device, pipelines.offscreenSampleShading, nullptr); + vkDestroyPipeline(device, pipelines.debug, nullptr); + + vkDestroyPipelineLayout(device, pipelineLayouts.deferred, nullptr); + vkDestroyPipelineLayout(device, pipelineLayouts.offscreen, nullptr); + + vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); + + // Meshes + vkMeshLoader::freeMeshBufferResources(device, &meshes.model); + vkMeshLoader::freeMeshBufferResources(device, &meshes.floor); + //vkMeshLoader::freeMeshBufferResources(device, &meshes.quad); + + // Uniform buffers + vkTools::destroyUniformData(device, &uniformData.vsOffscreen); + vkTools::destroyUniformData(device, &uniformData.vsFullScreen); + vkTools::destroyUniformData(device, &uniformData.fsLights); + + vkFreeCommandBuffers(device, cmdPool, 1, &offScreenCmdBuffer); + + vkDestroyRenderPass(device, offScreenFrameBuf.renderPass, nullptr); + + textureLoader->destroyTexture(textures.model.colorMap); + textureLoader->destroyTexture(textures.model.normalMap); + textureLoader->destroyTexture(textures.floor.colorMap); + textureLoader->destroyTexture(textures.floor.normalMap); + + vkDestroySemaphore(device, offscreenSemaphore, nullptr); + } + + // Create a frame buffer attachment + void createAttachment( + VkFormat format, + VkImageUsageFlagBits usage, + FrameBufferAttachment *attachment, + VkCommandBuffer layoutCmd) + { + VkImageAspectFlags aspectMask = 0; + VkImageLayout imageLayout; + + attachment->format = format; + + if (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) + { + aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + imageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + } + if (usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) + { + aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; + imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + } + + assert(aspectMask > 0); + + VkImageCreateInfo image = vkTools::initializers::imageCreateInfo(); + image.imageType = VK_IMAGE_TYPE_2D; + image.format = format; + image.extent.width = offScreenFrameBuf.width; + image.extent.height = offScreenFrameBuf.height; + image.extent.depth = 1; + image.mipLevels = 1; + image.arrayLayers = 1; + image.samples = SAMPLE_COUNT; + image.tiling = VK_IMAGE_TILING_OPTIMAL; + image.usage = usage | VK_IMAGE_USAGE_SAMPLED_BIT; + + VkMemoryAllocateInfo memAlloc = vkTools::initializers::memoryAllocateInfo(); + VkMemoryRequirements memReqs; + + VK_CHECK_RESULT(vkCreateImage(device, &image, nullptr, &attachment->image)); + vkGetImageMemoryRequirements(device, attachment->image, &memReqs); + memAlloc.allocationSize = memReqs.size; + memAlloc.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VK_CHECK_RESULT(vkAllocateMemory(device, &memAlloc, nullptr, &attachment->mem)); + VK_CHECK_RESULT(vkBindImageMemory(device, attachment->image, attachment->mem, 0)); + + VkImageViewCreateInfo imageView = vkTools::initializers::imageViewCreateInfo(); + imageView.viewType = VK_IMAGE_VIEW_TYPE_2D; + imageView.format = format; + imageView.subresourceRange = {}; + imageView.subresourceRange.aspectMask = aspectMask; + imageView.subresourceRange.baseMipLevel = 0; + imageView.subresourceRange.levelCount = 1; + imageView.subresourceRange.baseArrayLayer = 0; + imageView.subresourceRange.layerCount = 1; + imageView.image = attachment->image; + VK_CHECK_RESULT(vkCreateImageView(device, &imageView, nullptr, &attachment->view)); + } + + // Prepare a new framebuffer for offscreen rendering + // The contents of this framebuffer are then + // blitted to our render target + void prepareOffscreenFramebuffer() + { + VkCommandBuffer layoutCmd = VulkanExampleBase::createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true); + + offScreenFrameBuf.width = this->width; + offScreenFrameBuf.height = this->height; + + //offScreenFrameBuf.width = FB_DIM; + //offScreenFrameBuf.height = FB_DIM; + + // Color attachments + + // (World space) Positions + createAttachment( + VK_FORMAT_R16G16B16A16_SFLOAT, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, + &offScreenFrameBuf.position, + layoutCmd); + + // (World space) Normals + createAttachment( + VK_FORMAT_R16G16B16A16_SFLOAT, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, + &offScreenFrameBuf.normal, + layoutCmd); + + // Albedo (color) + createAttachment( + VK_FORMAT_R8G8B8A8_UNORM, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, + &offScreenFrameBuf.albedo, + layoutCmd); + + // Depth attachment + + // Find a suitable depth format + VkFormat attDepthFormat; + VkBool32 validDepthFormat = vkTools::getSupportedDepthFormat(physicalDevice, &attDepthFormat); + assert(validDepthFormat); + + createAttachment( + attDepthFormat, + VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, + &offScreenFrameBuf.depth, + layoutCmd); + + VulkanExampleBase::flushCommandBuffer(layoutCmd, queue, true); + + // Set up separate renderpass with references + // to the color and depth attachments + + std::array attachmentDescs = {}; + + // Init attachment properties + for (uint32_t i = 0; i < 4; ++i) + { + attachmentDescs[i].samples = SAMPLE_COUNT; + attachmentDescs[i].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + attachmentDescs[i].storeOp = VK_ATTACHMENT_STORE_OP_STORE; + attachmentDescs[i].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + attachmentDescs[i].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + if (i == 3) + { + attachmentDescs[i].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachmentDescs[i].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + } + else + { + attachmentDescs[i].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + attachmentDescs[i].finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + } + } + + // Formats + attachmentDescs[0].format = offScreenFrameBuf.position.format; + attachmentDescs[1].format = offScreenFrameBuf.normal.format; + attachmentDescs[2].format = offScreenFrameBuf.albedo.format; + attachmentDescs[3].format = offScreenFrameBuf.depth.format; + + std::vector colorReferences; + colorReferences.push_back({ 0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }); + colorReferences.push_back({ 1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }); + colorReferences.push_back({ 2, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL }); + + VkAttachmentReference depthReference = {}; + depthReference.attachment = 3; + depthReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; + + VkSubpassDescription subpass = {}; + subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + subpass.pColorAttachments = colorReferences.data(); + subpass.colorAttachmentCount = static_cast(colorReferences.size()); + subpass.pDepthStencilAttachment = &depthReference; + + // Use subpass dependencies for attachment layput transitions + std::array dependencies; + + dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL; + dependencies[0].dstSubpass = 0; + dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT; + dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; + + dependencies[1].srcSubpass = 0; + dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL; + dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; + dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; + dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; + dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT; + + VkRenderPassCreateInfo renderPassInfo = {}; + renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO; + renderPassInfo.pAttachments = attachmentDescs.data(); + renderPassInfo.attachmentCount = static_cast(attachmentDescs.size()); + renderPassInfo.subpassCount = 1; + renderPassInfo.pSubpasses = &subpass; + renderPassInfo.dependencyCount = 2; + renderPassInfo.pDependencies = dependencies.data(); + + VK_CHECK_RESULT(vkCreateRenderPass(device, &renderPassInfo, nullptr, &offScreenFrameBuf.renderPass)); + + std::array attachments; + attachments[0] = offScreenFrameBuf.position.view; + attachments[1] = offScreenFrameBuf.normal.view; + attachments[2] = offScreenFrameBuf.albedo.view; + attachments[3] = offScreenFrameBuf.depth.view; + + VkFramebufferCreateInfo fbufCreateInfo = {}; + fbufCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; + fbufCreateInfo.pNext = NULL; + fbufCreateInfo.renderPass = offScreenFrameBuf.renderPass; + fbufCreateInfo.pAttachments = attachments.data(); + fbufCreateInfo.attachmentCount = static_cast(attachments.size()); + fbufCreateInfo.width = offScreenFrameBuf.width; + fbufCreateInfo.height = offScreenFrameBuf.height; + fbufCreateInfo.layers = 1; + VK_CHECK_RESULT(vkCreateFramebuffer(device, &fbufCreateInfo, nullptr, &offScreenFrameBuf.frameBuffer)); + + // Create sampler to sample from the color attachments + VkSamplerCreateInfo sampler = vkTools::initializers::samplerCreateInfo(); + sampler.magFilter = VK_FILTER_NEAREST; + sampler.minFilter = VK_FILTER_NEAREST; + sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; + sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + sampler.addressModeV = sampler.addressModeU; + sampler.addressModeW = sampler.addressModeU; + sampler.mipLodBias = 0.0f; + sampler.maxAnisotropy = 0; + sampler.minLod = 0.0f; + sampler.maxLod = 1.0f; + sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; + VK_CHECK_RESULT(vkCreateSampler(device, &sampler, nullptr, &colorSampler)); + } + + // Build command buffer for rendering the scene to the offscreen frame buffer attachments + void buildDeferredCommandBuffer() + { + if (offScreenCmdBuffer == VK_NULL_HANDLE) + { + offScreenCmdBuffer = VulkanExampleBase::createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, false); + } + + // Create a semaphore used to synchronize offscreen rendering and usage + VkSemaphoreCreateInfo semaphoreCreateInfo = vkTools::initializers::semaphoreCreateInfo(); + VK_CHECK_RESULT(vkCreateSemaphore(device, &semaphoreCreateInfo, nullptr, &offscreenSemaphore)); + + VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo(); + + // Clear values for all attachments written in the fragment sahder + std::array clearValues; + clearValues[0].color = clearValues[1].color = { { 0.0f, 0.0f, 0.0f, 0.0f } }; + clearValues[2].color = { { 0.0f, 0.0f, 0.0f, 0.0f } }; + clearValues[3].depthStencil = { 1.0f, 0 }; + + VkRenderPassBeginInfo renderPassBeginInfo = vkTools::initializers::renderPassBeginInfo(); + renderPassBeginInfo.renderPass = offScreenFrameBuf.renderPass; + renderPassBeginInfo.framebuffer = offScreenFrameBuf.frameBuffer; + renderPassBeginInfo.renderArea.extent.width = offScreenFrameBuf.width; + renderPassBeginInfo.renderArea.extent.height = offScreenFrameBuf.height; + renderPassBeginInfo.clearValueCount = static_cast(clearValues.size()); + renderPassBeginInfo.pClearValues = clearValues.data(); + + VK_CHECK_RESULT(vkBeginCommandBuffer(offScreenCmdBuffer, &cmdBufInfo)); + + vkCmdBeginRenderPass(offScreenCmdBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + VkViewport viewport = vkTools::initializers::viewport((float)offScreenFrameBuf.width, (float)offScreenFrameBuf.height, 0.0f, 1.0f); + vkCmdSetViewport(offScreenCmdBuffer, 0, 1, &viewport); + + VkRect2D scissor = vkTools::initializers::rect2D(offScreenFrameBuf.width, offScreenFrameBuf.height, 0, 0); + vkCmdSetScissor(offScreenCmdBuffer, 0, 1, &scissor); + + vkCmdBindPipeline(offScreenCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, useSampleShading ? pipelines.offscreenSampleShading : pipelines.offscreen); + + VkDeviceSize offsets[1] = { 0 }; + + // Background + vkCmdBindDescriptorSets(offScreenCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayouts.offscreen, 0, 1, &descriptorSets.floor, 0, NULL); + vkCmdBindVertexBuffers(offScreenCmdBuffer, VERTEX_BUFFER_BIND_ID, 1, &meshes.floor.vertices.buf, offsets); + vkCmdBindIndexBuffer(offScreenCmdBuffer, meshes.floor.indices.buf, 0, VK_INDEX_TYPE_UINT32); + vkCmdDrawIndexed(offScreenCmdBuffer, meshes.floor.indexCount, 1, 0, 0, 0); + + // Object + vkCmdBindDescriptorSets(offScreenCmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayouts.offscreen, 0, 1, &descriptorSets.model, 0, NULL); + vkCmdBindVertexBuffers(offScreenCmdBuffer, VERTEX_BUFFER_BIND_ID, 1, &meshes.model.vertices.buf, offsets); + vkCmdBindIndexBuffer(offScreenCmdBuffer, meshes.model.indices.buf, 0, VK_INDEX_TYPE_UINT32); + vkCmdDrawIndexed(offScreenCmdBuffer, meshes.model.indexCount, 3, 0, 0, 0); + + vkCmdEndRenderPass(offScreenCmdBuffer); + + VK_CHECK_RESULT(vkEndCommandBuffer(offScreenCmdBuffer)); + } + + void reBuildCommandBuffers() + { + if (!checkCommandBuffers()) + { + destroyCommandBuffers(); + createCommandBuffers(); + } + buildCommandBuffers(); + buildDeferredCommandBuffer(); + } + + void buildCommandBuffers() + { + VkCommandBufferBeginInfo cmdBufInfo = vkTools::initializers::commandBufferBeginInfo(); + + VkClearValue clearValues[2]; + clearValues[0].color = { { 1.0f, 1.0f, 1.0f, 0.0f } }; + clearValues[1].depthStencil = { 1.0f, 0 }; + + VkRenderPassBeginInfo renderPassBeginInfo = vkTools::initializers::renderPassBeginInfo(); + renderPassBeginInfo.renderPass = renderPass; + renderPassBeginInfo.renderArea.offset.x = 0; + renderPassBeginInfo.renderArea.offset.y = 0; + renderPassBeginInfo.renderArea.extent.width = width; + renderPassBeginInfo.renderArea.extent.height = height; + renderPassBeginInfo.clearValueCount = 2; + renderPassBeginInfo.pClearValues = clearValues; + + for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) + { + // Set target frame buffer + renderPassBeginInfo.framebuffer = frameBuffers[i]; + + VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo)); + + vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); + + VkViewport viewport = vkTools::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); + vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); + + VkRect2D scissor = vkTools::initializers::rect2D(width, height, 0, 0); + vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); + + VkDeviceSize offsets[1] = { 0 }; + vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayouts.deferred, 0, 1, &descriptorSet, 0, NULL); + + if (debugDisplay) + { + vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.debug); + vkCmdDraw(drawCmdBuffers[i], 3, 1, 0, 0); + // Move viewport to display final composition in lower right corner + viewport.x = viewport.width * 0.5f; + viewport.y = viewport.height * 0.5f; + viewport.width = (float)width * 0.5f; + viewport.height = (float)height * 0.5f; + vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); + } + + camera.updateAspectRatio((float)viewport.width / (float)viewport.height); + + // Final composition as full screen quad + vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, useMSAA ? pipelines.deferred : pipelines.deferredNoMSAA); + vkCmdDraw(drawCmdBuffers[i], 3, 1, 0, 0); + + vkCmdEndRenderPass(drawCmdBuffers[i]); + + VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i])); + } + } + + void loadAssets() + { + textureLoader->loadTexture(getAssetPath() + "models/armor/colormap.ktx", VK_FORMAT_BC3_UNORM_BLOCK, &textures.model.colorMap); + textureLoader->loadTexture(getAssetPath() + "models/armor/normalmap.ktx", VK_FORMAT_BC3_UNORM_BLOCK, &textures.model.normalMap); + + textureLoader->loadTexture(getAssetPath() + "textures/pattern_57_diffuse_bc3.ktx", VK_FORMAT_BC3_UNORM_BLOCK, &textures.floor.colorMap); + textureLoader->loadTexture(getAssetPath() + "textures/pattern_57_normal_bc3.ktx", VK_FORMAT_BC3_UNORM_BLOCK, &textures.floor.normalMap); + + loadMesh(getAssetPath() + "models/armor/armor.dae", &meshes.model, vertexLayout, 1.0f); + + vkMeshLoader::MeshCreateInfo meshCreateInfo; + meshCreateInfo.scale = glm::vec3(15.0f); + meshCreateInfo.uvscale = glm::vec2(8.0f, 8.0f); + meshCreateInfo.center = glm::vec3(0.0f, 2.3f, 0.0f); + loadMesh(getAssetPath() + "models/openbox.dae", &meshes.floor, vertexLayout, &meshCreateInfo); + } + + void setupVertexDescriptions() + { + // Binding description + vertices.bindingDescriptions.resize(1); + vertices.bindingDescriptions[0] = + vkTools::initializers::vertexInputBindingDescription( + VERTEX_BUFFER_BIND_ID, + vkMeshLoader::vertexSize(vertexLayout), + VK_VERTEX_INPUT_RATE_VERTEX); + + // Attribute descriptions + vertices.attributeDescriptions.resize(5); + // Location 0: Position + vertices.attributeDescriptions[0] = + vkTools::initializers::vertexInputAttributeDescription( + VERTEX_BUFFER_BIND_ID, + 0, + VK_FORMAT_R32G32B32_SFLOAT, + 0); + // Location 1: Texture coordinates + vertices.attributeDescriptions[1] = + vkTools::initializers::vertexInputAttributeDescription( + VERTEX_BUFFER_BIND_ID, + 1, + VK_FORMAT_R32G32_SFLOAT, + sizeof(float) * 3); + // Location 2: Color + vertices.attributeDescriptions[2] = + vkTools::initializers::vertexInputAttributeDescription( + VERTEX_BUFFER_BIND_ID, + 2, + VK_FORMAT_R32G32B32_SFLOAT, + sizeof(float) * 5); + // Location 3: Normal + vertices.attributeDescriptions[3] = + vkTools::initializers::vertexInputAttributeDescription( + VERTEX_BUFFER_BIND_ID, + 3, + VK_FORMAT_R32G32B32_SFLOAT, + sizeof(float) * 8); + // Location 4: Tangent + vertices.attributeDescriptions[4] = + vkTools::initializers::vertexInputAttributeDescription( + VERTEX_BUFFER_BIND_ID, + 4, + VK_FORMAT_R32G32B32_SFLOAT, + sizeof(float) * 11); + + vertices.inputState = vkTools::initializers::pipelineVertexInputStateCreateInfo(); + vertices.inputState.vertexBindingDescriptionCount = static_cast(vertices.bindingDescriptions.size()); + vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data(); + vertices.inputState.vertexAttributeDescriptionCount = static_cast(vertices.attributeDescriptions.size()); + vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data(); + } + + void setupDescriptorPool() + { + std::vector poolSizes = + { + vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 8), + vkTools::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 9) + }; + + VkDescriptorPoolCreateInfo descriptorPoolInfo = + vkTools::initializers::descriptorPoolCreateInfo( + static_cast(poolSizes.size()), + poolSizes.data(), + 3); + + VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); + } + + void setupDescriptorSetLayout() + { + // Deferred shading layout + std::vector setLayoutBindings = + { + // Binding 0 : Vertex shader uniform buffer + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + VK_SHADER_STAGE_VERTEX_BIT, + 0), + // Binding 1 : Position texture target / Scene colormap + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + VK_SHADER_STAGE_FRAGMENT_BIT, + 1), + // Binding 2 : Normals texture target + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + VK_SHADER_STAGE_FRAGMENT_BIT, + 2), + // Binding 3 : Albedo texture target + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + VK_SHADER_STAGE_FRAGMENT_BIT, + 3), + // Binding 4 : Fragment shader uniform buffer + vkTools::initializers::descriptorSetLayoutBinding( + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + VK_SHADER_STAGE_FRAGMENT_BIT, + 4), + }; + + VkDescriptorSetLayoutCreateInfo descriptorLayout = + vkTools::initializers::descriptorSetLayoutCreateInfo( + setLayoutBindings.data(), + static_cast(setLayoutBindings.size())); + + VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); + + VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = + vkTools::initializers::pipelineLayoutCreateInfo( + &descriptorSetLayout, + 1); + + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayouts.deferred)); + + // Offscreen (scene) rendering pipeline layout + VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayouts.offscreen)); + } + + void setupDescriptorSet() + { + std::vector writeDescriptorSets; + + // Textured quad descriptor set + VkDescriptorSetAllocateInfo allocInfo = + vkTools::initializers::descriptorSetAllocateInfo( + descriptorPool, + &descriptorSetLayout, + 1); + + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); + + // Image descriptors for the offscreen color attachments + VkDescriptorImageInfo texDescriptorPosition = + vkTools::initializers::descriptorImageInfo( + colorSampler, + offScreenFrameBuf.position.view, + VK_IMAGE_LAYOUT_GENERAL); + + VkDescriptorImageInfo texDescriptorNormal = + vkTools::initializers::descriptorImageInfo( + colorSampler, + offScreenFrameBuf.normal.view, + VK_IMAGE_LAYOUT_GENERAL); + + VkDescriptorImageInfo texDescriptorAlbedo = + vkTools::initializers::descriptorImageInfo( + colorSampler, + offScreenFrameBuf.albedo.view, + VK_IMAGE_LAYOUT_GENERAL); + + writeDescriptorSets = { + // Binding 0 : Vertex shader uniform buffer + vkTools::initializers::writeDescriptorSet( + descriptorSet, + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 0, + &uniformData.vsFullScreen.descriptor), + // Binding 1 : Position texture target + vkTools::initializers::writeDescriptorSet( + descriptorSet, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 1, + &texDescriptorPosition), + // Binding 2 : Normals texture target + vkTools::initializers::writeDescriptorSet( + descriptorSet, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 2, + &texDescriptorNormal), + // Binding 3 : Albedo texture target + vkTools::initializers::writeDescriptorSet( + descriptorSet, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 3, + &texDescriptorAlbedo), + // Binding 4 : Fragment shader uniform buffer + vkTools::initializers::writeDescriptorSet( + descriptorSet, + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 4, + &uniformData.fsLights.descriptor), + }; + + vkUpdateDescriptorSets(device, static_cast(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL); + + // Offscreen (scene) + + // Model + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.model)); + writeDescriptorSets = + { + // Binding 0: Vertex shader uniform buffer + vkTools::initializers::writeDescriptorSet( + descriptorSets.model, + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 0, + &uniformData.vsOffscreen.descriptor), + // Binding 1: Color map + vkTools::initializers::writeDescriptorSet( + descriptorSets.model, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 1, + &textures.model.colorMap.descriptor), + // Binding 2: Normal map + vkTools::initializers::writeDescriptorSet( + descriptorSets.model, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 2, + &textures.model.normalMap.descriptor) + }; + vkUpdateDescriptorSets(device, static_cast(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL); + + // Backbround + VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.floor)); + writeDescriptorSets = + { + // Binding 0: Vertex shader uniform buffer + vkTools::initializers::writeDescriptorSet( + descriptorSets.floor, + VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, + 0, + &uniformData.vsOffscreen.descriptor), + // Binding 1: Color map + vkTools::initializers::writeDescriptorSet( + descriptorSets.floor, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 1, + &textures.floor.colorMap.descriptor), + // Binding 2: Normal map + vkTools::initializers::writeDescriptorSet( + descriptorSets.floor, + VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + 2, + &textures.floor.normalMap.descriptor) + }; + vkUpdateDescriptorSets(device, static_cast(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL); + } + + void preparePipelines() + { + VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = + vkTools::initializers::pipelineInputAssemblyStateCreateInfo( + VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, + 0, + VK_FALSE); + + VkPipelineRasterizationStateCreateInfo rasterizationState = + vkTools::initializers::pipelineRasterizationStateCreateInfo( + VK_POLYGON_MODE_FILL, + VK_CULL_MODE_BACK_BIT, + VK_FRONT_FACE_CLOCKWISE, + 0); + + VkPipelineColorBlendAttachmentState blendAttachmentState = + vkTools::initializers::pipelineColorBlendAttachmentState( + 0xf, + VK_FALSE); + + VkPipelineColorBlendStateCreateInfo colorBlendState = + vkTools::initializers::pipelineColorBlendStateCreateInfo( + 1, + &blendAttachmentState); + + VkPipelineDepthStencilStateCreateInfo depthStencilState = + vkTools::initializers::pipelineDepthStencilStateCreateInfo( + VK_TRUE, + VK_TRUE, + VK_COMPARE_OP_LESS_OR_EQUAL); + + VkPipelineViewportStateCreateInfo viewportState = + vkTools::initializers::pipelineViewportStateCreateInfo(1, 1, 0); + + VkPipelineMultisampleStateCreateInfo multisampleState = + vkTools::initializers::pipelineMultisampleStateCreateInfo( + VK_SAMPLE_COUNT_1_BIT, + 0); + + std::vector dynamicStateEnables = { + VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR + }; + VkPipelineDynamicStateCreateInfo dynamicState = + vkTools::initializers::pipelineDynamicStateCreateInfo( + dynamicStateEnables.data(), + static_cast(dynamicStateEnables.size()), + 0); + + // Final fullscreen pass pipeline + std::array shaderStages; + + VkGraphicsPipelineCreateInfo pipelineCreateInfo = + vkTools::initializers::pipelineCreateInfo( + pipelineLayouts.deferred, + renderPass, + 0); + + pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; + pipelineCreateInfo.pRasterizationState = &rasterizationState; + pipelineCreateInfo.pColorBlendState = &colorBlendState; + pipelineCreateInfo.pMultisampleState = &multisampleState; + pipelineCreateInfo.pViewportState = &viewportState; + pipelineCreateInfo.pDepthStencilState = &depthStencilState; + pipelineCreateInfo.pDynamicState = &dynamicState; + pipelineCreateInfo.stageCount = static_cast(shaderStages.size()); + pipelineCreateInfo.pStages = shaderStages.data(); + + // Deferred + + // Empty vertex input state, quads are generated by the vertex shader + VkPipelineVertexInputStateCreateInfo emptyInputState = vkTools::initializers::pipelineVertexInputStateCreateInfo(); + pipelineCreateInfo.pVertexInputState = &emptyInputState; + pipelineCreateInfo.layout = pipelineLayouts.deferred; + + // Use specialization constants to pass number of samples to the shader (used for MSAA resolve) + VkSpecializationMapEntry specializationEntry{}; + specializationEntry.constantID = 0; + specializationEntry.offset = 0; + specializationEntry.size = sizeof(uint32_t); + + uint32_t specializationData = SAMPLE_COUNT; + + VkSpecializationInfo specializationInfo; + specializationInfo.mapEntryCount = 1; + specializationInfo.pMapEntries = &specializationEntry; + specializationInfo.dataSize = sizeof(specializationData); + specializationInfo.pData = &specializationData; + + // With MSAA + shaderStages[0] = loadShader(getAssetPath() + "shaders/deferredmultisampling/deferred.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); + shaderStages[1] = loadShader(getAssetPath() + "shaders/deferredmultisampling/deferred.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + shaderStages[1].pSpecializationInfo = &specializationInfo; + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.deferred)); + + // No MSAA (1 sample) + specializationData = 1; + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.deferredNoMSAA)); + + // Debug display pipeline + shaderStages[0] = loadShader(getAssetPath() + "shaders/deferredmultisampling/debug.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); + shaderStages[1] = loadShader(getAssetPath() + "shaders/deferredmultisampling/debug.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.debug)); + + // Offscreen scene rendering pipeline + pipelineCreateInfo.pVertexInputState = &vertices.inputState; + + shaderStages[0] = loadShader(getAssetPath() + "shaders/deferredmultisampling/mrt.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); + shaderStages[1] = loadShader(getAssetPath() + "shaders/deferredmultisampling/mrt.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); + + //rasterizationState.polygonMode = VK_POLYGON_MODE_LINE; + //rasterizationState.lineWidth = 2.0f; + multisampleState.rasterizationSamples = SAMPLE_COUNT; + multisampleState.alphaToCoverageEnable = VK_TRUE; + + // Separate render pass + pipelineCreateInfo.renderPass = offScreenFrameBuf.renderPass; + + // Separate layout + pipelineCreateInfo.layout = pipelineLayouts.offscreen; + + // Blend attachment states required for all color attachments + // This is important, as color write mask will otherwise be 0x0 and you + // won't see anything rendered to the attachment + std::array blendAttachmentStates = { + vkTools::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE), + vkTools::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE), + vkTools::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE) + }; + + colorBlendState.attachmentCount = static_cast(blendAttachmentStates.size()); + colorBlendState.pAttachments = blendAttachmentStates.data(); + + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.offscreen)); + + multisampleState.sampleShadingEnable = VK_TRUE; + multisampleState.minSampleShading = 0.25f; + VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.offscreenSampleShading)); + } + + // Prepare and initialize uniform buffer containing shader uniforms + void prepareUniformBuffers() + { + // Fullscreen vertex shader + createBuffer( + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + sizeof(uboVS), + nullptr, + &uniformData.vsFullScreen.buffer, + &uniformData.vsFullScreen.memory, + &uniformData.vsFullScreen.descriptor); + + // Deferred vertex shader + createBuffer( + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + sizeof(uboOffscreenVS), + nullptr, + &uniformData.vsOffscreen.buffer, + &uniformData.vsOffscreen.memory, + &uniformData.vsOffscreen.descriptor); + + // Deferred fragment shader + createBuffer( + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + sizeof(uboFragmentLights), + nullptr, + &uniformData.fsLights.buffer, + &uniformData.fsLights.memory, + &uniformData.fsLights.descriptor); + + // Init some values + uboOffscreenVS.instancePos[0] = glm::vec4(0.0f); + uboOffscreenVS.instancePos[1] = glm::vec4(-4.0f, 0.0, -4.0f, 0.0f); + uboOffscreenVS.instancePos[2] = glm::vec4(4.0f, 0.0, -4.0f, 0.0f); + + // Update + updateUniformBuffersScreen(); + updateUniformBufferDeferredMatrices(); + updateUniformBufferDeferredLights(); + } + + void updateUniformBuffersScreen() + { + if (debugDisplay) + { + uboVS.projection = glm::ortho(0.0f, 2.0f, 0.0f, 2.0f, -1.0f, 1.0f); + } + else + { + uboVS.projection = glm::ortho(0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f); + } + uboVS.model = glm::mat4(); + + uint8_t *pData; + VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsFullScreen.memory, 0, sizeof(uboVS), 0, (void **)&pData)); + memcpy(pData, &uboVS, sizeof(uboVS)); + vkUnmapMemory(device, uniformData.vsFullScreen.memory); + } + + void updateUniformBufferDeferredMatrices() + { + uboOffscreenVS.projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 256.0f); + uboOffscreenVS.view = glm::translate(glm::mat4(), glm::vec3(0.0f, 0.0f, zoom)); + + uboOffscreenVS.model = glm::mat4(); + uboOffscreenVS.model = glm::translate(glm::mat4(), glm::vec3(0.0f, 0.25f, 0.0f) + cameraPos); + uboOffscreenVS.model = glm::rotate(uboOffscreenVS.model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); + uboOffscreenVS.model = glm::rotate(uboOffscreenVS.model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); + uboOffscreenVS.model = glm::rotate(uboOffscreenVS.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); + + uboOffscreenVS.projection = camera.matrices.perspective; + uboOffscreenVS.view = camera.matrices.view; + uboOffscreenVS.model = glm::mat4(); + + uint8_t *pData; + VK_CHECK_RESULT(vkMapMemory(device, uniformData.vsOffscreen.memory, 0, sizeof(uboOffscreenVS), 0, (void **)&pData)); + memcpy(pData, &uboOffscreenVS, sizeof(uboOffscreenVS)); + vkUnmapMemory(device, uniformData.vsOffscreen.memory); + } + + // Update fragment shader light position uniform block + void updateUniformBufferDeferredLights() + { + // White + uboFragmentLights.lights[0].position = glm::vec4(0.0f, 0.0f, 1.0f, 0.0f); + uboFragmentLights.lights[0].color = glm::vec3(1.5f); + uboFragmentLights.lights[0].radius = 15.0f * 0.25f; + // Red + uboFragmentLights.lights[1].position = glm::vec4(-2.0f, 0.0f, 0.0f, 0.0f); + uboFragmentLights.lights[1].color = glm::vec3(1.0f, 0.0f, 0.0f); + uboFragmentLights.lights[1].radius = 15.0f; + // Blue + uboFragmentLights.lights[2].position = glm::vec4(2.0f, 1.0f, 0.0f, 0.0f); + uboFragmentLights.lights[2].color = glm::vec3(0.0f, 0.0f, 2.5f); + uboFragmentLights.lights[2].radius = 5.0f; + // Yellow + uboFragmentLights.lights[3].position = glm::vec4(0.0f, 0.9f, 0.5f, 0.0f); + uboFragmentLights.lights[3].color = glm::vec3(1.0f, 1.0f, 0.0f); + uboFragmentLights.lights[3].radius = 2.0f; + // Green + uboFragmentLights.lights[4].position = glm::vec4(0.0f, 0.5f, 0.0f, 0.0f); + uboFragmentLights.lights[4].color = glm::vec3(0.0f, 1.0f, 0.2f); + uboFragmentLights.lights[4].radius = 5.0f; + // Yellow + uboFragmentLights.lights[5].position = glm::vec4(0.0f, 1.0f, 0.0f, 0.0f); + uboFragmentLights.lights[5].color = glm::vec3(1.0f, 0.7f, 0.3f); + uboFragmentLights.lights[5].radius = 25.0f; + + uboFragmentLights.lights[0].position.x = sin(glm::radians(360.0f * timer)) * 5.0f; + uboFragmentLights.lights[0].position.z = cos(glm::radians(360.0f * timer)) * 5.0f; + + uboFragmentLights.lights[1].position.x = -4.0f + sin(glm::radians(360.0f * timer) + 45.0f) * 2.0f; + uboFragmentLights.lights[1].position.z = 0.0f + cos(glm::radians(360.0f * timer) + 45.0f) * 2.0f; + + uboFragmentLights.lights[2].position.x = 4.0f + sin(glm::radians(360.0f * timer)) * 2.0f; + uboFragmentLights.lights[2].position.z = 0.0f + cos(glm::radians(360.0f * timer)) * 2.0f; + + uboFragmentLights.lights[4].position.x = 0.0f + sin(glm::radians(360.0f * timer + 90.0f)) * 5.0f; + uboFragmentLights.lights[4].position.z = 0.0f - cos(glm::radians(360.0f * timer + 45.0f)) * 5.0f; + + uboFragmentLights.lights[5].position.x = 0.0f + sin(glm::radians(-360.0f * timer + 135.0f)) * 10.0f; + uboFragmentLights.lights[5].position.z = 0.0f - cos(glm::radians(-360.0f * timer - 45.0f)) * 10.0f; + + // Current view position + uboFragmentLights.viewPos = glm::vec4(camera.position, 0.0f) * glm::vec4(-1.0f, 1.0f, -1.0f, 1.0f); + + uint8_t *pData; + VK_CHECK_RESULT(vkMapMemory(device, uniformData.fsLights.memory, 0, sizeof(uboFragmentLights), 0, (void **)&pData)); + memcpy(pData, &uboFragmentLights, sizeof(uboFragmentLights)); + vkUnmapMemory(device, uniformData.fsLights.memory); + } + + void draw() + { + VulkanExampleBase::prepareFrame(); + + // Offscreen rendering + + // Wait for swap chain presentation to finish + submitInfo.pWaitSemaphores = &semaphores.presentComplete; + // Signal ready with offscreen semaphore + submitInfo.pSignalSemaphores = &offscreenSemaphore; + + // Submit work + submitInfo.commandBufferCount = 1; + submitInfo.pCommandBuffers = &offScreenCmdBuffer; + VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); + + // Scene rendering + + // Wait for offscreen semaphore + submitInfo.pWaitSemaphores = &offscreenSemaphore; + // Signal ready with render complete semaphpre + submitInfo.pSignalSemaphores = &semaphores.renderComplete; + + // Submit work + submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer]; + VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); + + VulkanExampleBase::submitFrame(); + } + + void prepare() + { + VulkanExampleBase::prepare(); + loadAssets(); + setupVertexDescriptions(); + prepareOffscreenFramebuffer(); + prepareUniformBuffers(); + setupDescriptorSetLayout(); + preparePipelines(); + setupDescriptorPool(); + setupDescriptorSet(); + buildCommandBuffers(); + buildDeferredCommandBuffer(); + prepared = true; + } + + virtual void render() + { + if (!prepared) + return; + draw(); + updateUniformBufferDeferredLights(); + } + + virtual void viewChanged() + { + updateUniformBufferDeferredMatrices(); + uboFragmentLights.windowSize = glm::ivec2(width, height); + } + + void toggleDebugDisplay() + { + debugDisplay = !debugDisplay; + reBuildCommandBuffers(); + updateUniformBuffersScreen(); + } + + virtual void keyPressed(uint32_t keyCode) + { + switch (keyCode) + { + case KEY_F2: + useMSAA = !useMSAA; + reBuildCommandBuffers(); + break; + case KEY_F3: + useSampleShading = !useSampleShading; + reBuildCommandBuffers(); + break; + case KEY_F4: + case GAMEPAD_BUTTON_A: + toggleDebugDisplay(); + updateTextOverlay(); + break; + } + } + + virtual void getOverlayText(VulkanTextOverlay *textOverlay) + { +#if defined(__ANDROID__) + textOverlay->addText("Press \"Button A\" to toggle debug display", 5.0f, 85.0f, VulkanTextOverlay::alignLeft); +#else + textOverlay->addText("MSAA (\"F2\"): " + std::to_string(useMSAA), 5.0f, 85.0f, VulkanTextOverlay::alignLeft); + textOverlay->addText("Sample Shading (\"F3\"): " + std::to_string(useSampleShading), 5.0f, 105.0f, VulkanTextOverlay::alignLeft); + textOverlay->addText("G-Buffers (\"F4\")", 5.0f, 125.0f, VulkanTextOverlay::alignLeft); +#endif + // Render targets + if (debugDisplay) + { + textOverlay->addText("World space position", (float)width * 0.25f, (float)height * 0.5f - 25.0f, VulkanTextOverlay::alignCenter); + textOverlay->addText("World space normals", (float)width * 0.75f, (float)height * 0.5f - 25.0f, VulkanTextOverlay::alignCenter); + textOverlay->addText("Albedo", (float)width * 0.25f, (float)height - 25.0f, VulkanTextOverlay::alignCenter); + textOverlay->addText("Final image", (float)width * 0.75f, (float)height - 25.0f, VulkanTextOverlay::alignCenter); + } + } +}; + +VULKAN_EXAMPLE_MAIN() diff --git a/deferredmultisampling/deferredmultisampling.vcxproj b/deferredmultisampling/deferredmultisampling.vcxproj new file mode 100644 index 00000000..936a9e8d --- /dev/null +++ b/deferredmultisampling/deferredmultisampling.vcxproj @@ -0,0 +1,103 @@ + + + + + Debug + x64 + + + Release + x64 + + + + {0CB44B34-A81F-4002-9AC7-E0EEA55D8A60} + Win32Proj + 8.1 + + + + Application + true + v140 + + + Application + false + v140 + + + + + + + + + + + + + true + $(SolutionDir)\bin\ + $(SolutionDir)\bin\intermediate\$(ProjectName)\$(ConfigurationName) + + + true + $(SolutionDir)\bin\ + $(SolutionDir)\bin\intermediate\$(ProjectName)\$(ConfigurationName) + + + + WIN32;_DEBUG;_WINDOWS;VK_USE_PLATFORM_WIN32_KHR;_USE_MATH_DEFINES;NOMINMAX;%(PreprocessorDefinitions) + MultiThreadedDebugDLL + Level3 + ProgramDatabase + Disabled + ..\base;..\external\glm;..\external\gli;..\external\assimp;..\external;%(AdditionalIncludeDirectories) + /FS %(AdditionalOptions) + + + true + Windows + ..\libs\vulkan\vulkan-1.lib;..\libs\assimp\assimp.lib;%(AdditionalDependencies) + + + + + WIN32;NDEBUG;_WINDOWS;VK_USE_PLATFORM_WIN32_KHR;_USE_MATH_DEFINES;NOMINMAX;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) + MultiThreadedDLL + Level3 + ProgramDatabase + ..\base;..\external\glm;..\external\gli;..\external\assimp;..\external;%(AdditionalIncludeDirectories) + + + true + Windows + true + true + ..\libs\vulkan\vulkan-1.lib;..\libs\assimp\assimp.lib;%(AdditionalDependencies) + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/deferredmultisampling/deferredmultisampling.vcxproj.filters b/deferredmultisampling/deferredmultisampling.vcxproj.filters new file mode 100644 index 00000000..13af3e24 --- /dev/null +++ b/deferredmultisampling/deferredmultisampling.vcxproj.filters @@ -0,0 +1,65 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {210c4466-75e2-4230-9332-1ac69de9dcec} + + + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + + + Header Files + + + + + Shaders + + + Shaders + + + Shaders + + + Shaders + + + Shaders + + + Shaders + + + \ No newline at end of file diff --git a/vulkanExamples.sln b/vulkanExamples.sln index 0167ca84..68ed7a20 100644 --- a/vulkanExamples.sln +++ b/vulkanExamples.sln @@ -109,6 +109,10 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "texture3d", "texture3d\text EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "texturesparseresidency", "texturesparseresidency\texturesparseresidency.vcxproj", "{1FA0178C-F5E9-4B2E-A488-14F310F8DBD9}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "deferred", "deferred", "{460EE42F-4178-49EF-9AC0-415599B80303}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "deferredmultisampling", "deferredmultisampling\deferredmultisampling.vcxproj", "{0CB44B34-A81F-4002-9AC7-E0EEA55D8A60}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -271,6 +275,10 @@ Global {1FA0178C-F5E9-4B2E-A488-14F310F8DBD9}.Debug|x64.Build.0 = Debug|x64 {1FA0178C-F5E9-4B2E-A488-14F310F8DBD9}.Release|x64.ActiveCfg = Release|x64 {1FA0178C-F5E9-4B2E-A488-14F310F8DBD9}.Release|x64.Build.0 = Release|x64 + {0CB44B34-A81F-4002-9AC7-E0EEA55D8A60}.Debug|x64.ActiveCfg = Debug|x64 + {0CB44B34-A81F-4002-9AC7-E0EEA55D8A60}.Debug|x64.Build.0 = Debug|x64 + {0CB44B34-A81F-4002-9AC7-E0EEA55D8A60}.Release|x64.ActiveCfg = Release|x64 + {0CB44B34-A81F-4002-9AC7-E0EEA55D8A60}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -283,10 +291,13 @@ Global {5A049556-EA1E-4985-8D0B-3748E5D56F68} = {6B47BC47-0394-429E-9441-867EC23DFCD4} {0D4DE16B-71FE-4B17-8310-3FFFB9E873B7} = {A8492D6D-5243-456E-8173-39B99F1FEA9C} {5E512F97-14DB-4CEE-A495-BD8AED789521} = {A8492D6D-5243-456E-8173-39B99F1FEA9C} + {AF2911F4-33BF-465E-9298-E46D58B929EF} = {460EE42F-4178-49EF-9AC0-415599B80303} {8B1C24E5-CC00-484C-9F6F-8FFCBDA3AA30} = {6B47BC47-0394-429E-9441-867EC23DFCD4} {6C6E48B1-5946-4754-9E31-E1C989EC25FE} = {C93DE675-A816-4412-8E9F-1EFE9AC07750} + {BFEB15A3-D252-4AF7-8CA8-B9396F374DDB} = {460EE42F-4178-49EF-9AC0-415599B80303} {24AD09B4-6ABE-4A82-83E7-6A7799A88762} = {A8492D6D-5243-456E-8173-39B99F1FEA9C} {D36B82DD-9114-44D2-A9C9-8DF0F8544BD5} = {A8492D6D-5243-456E-8173-39B99F1FEA9C} {1FA0178C-F5E9-4B2E-A488-14F310F8DBD9} = {A8492D6D-5243-456E-8173-39B99F1FEA9C} + {0CB44B34-A81F-4002-9AC7-E0EEA55D8A60} = {460EE42F-4178-49EF-9AC0-415599B80303} EndGlobalSection EndGlobal