shaders_deferred_render.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*******************************************************************************************
  2. *
  3. * raylib [shaders] example - deferred rendering
  4. *
  5. * NOTE: This example requires raylib OpenGL 3.3 or OpenGL ES 3.0
  6. *
  7. * Example originally created with raylib 4.5, last time updated with raylib 4.5
  8. *
  9. * Example contributed by Justin Andreas Lacoste (@27justin) and reviewed by Ramon Santamaria (@raysan5)
  10. *
  11. * Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
  12. * BSD-like license that allows static linking with closed source software
  13. *
  14. * Copyright (c) 2023 Justin Andreas Lacoste (@27justin)
  15. *
  16. ********************************************************************************************/
  17. #include "raylib.h"
  18. #include "rlgl.h"
  19. #include "raymath.h"
  20. #define RLIGHTS_IMPLEMENTATION
  21. #include "rlights.h"
  22. #if defined(PLATFORM_DESKTOP)
  23. #define GLSL_VERSION 330
  24. #else // PLATFORM_ANDROID, PLATFORM_WEB
  25. #define GLSL_VERSION 100
  26. #endif
  27. #include <stdlib.h> // Required for: NULL
  28. #define MAX_CUBES 30
  29. // GBuffer data
  30. typedef struct GBuffer {
  31. unsigned int framebuffer;
  32. unsigned int positionTexture;
  33. unsigned int normalTexture;
  34. unsigned int albedoSpecTexture;
  35. unsigned int depthRenderbuffer;
  36. } GBuffer;
  37. // Deferred mode passes
  38. typedef enum {
  39. DEFERRED_POSITION,
  40. DEFERRED_NORMAL,
  41. DEFERRED_ALBEDO,
  42. DEFERRED_SHADING
  43. } DeferredMode;
  44. //------------------------------------------------------------------------------------
  45. // Program main entry point
  46. //------------------------------------------------------------------------------------
  47. int main(void)
  48. {
  49. // Initialization
  50. // -------------------------------------------------------------------------------------
  51. const int screenWidth = 800;
  52. const int screenHeight = 450;
  53. InitWindow(screenWidth, screenHeight, "raylib [shaders] example - deferred render");
  54. Camera camera = { 0 };
  55. camera.position = (Vector3){ 5.0f, 4.0f, 5.0f }; // Camera position
  56. camera.target = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera looking at point
  57. camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
  58. camera.fovy = 60.0f; // Camera field-of-view Y
  59. camera.projection = CAMERA_PERSPECTIVE; // Camera projection type
  60. // Load plane model from a generated mesh
  61. Model model = LoadModelFromMesh(GenMeshPlane(10.0f, 10.0f, 3, 3));
  62. Model cube = LoadModelFromMesh(GenMeshCube(2.0f, 2.0f, 2.0f));
  63. // Load geometry buffer (G-buffer) shader and deferred shader
  64. Shader gbufferShader = LoadShader("resources/shaders/glsl330/gbuffer.vs",
  65. "resources/shaders/glsl330/gbuffer.fs");
  66. Shader deferredShader = LoadShader("resources/shaders/glsl330/deferred_shading.vs",
  67. "resources/shaders/glsl330/deferred_shading.fs");
  68. deferredShader.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(deferredShader, "viewPosition");
  69. // Initialize the G-buffer
  70. GBuffer gBuffer = { 0 };
  71. gBuffer.framebuffer = rlLoadFramebuffer();
  72. if (!gBuffer.framebuffer)
  73. {
  74. TraceLog(LOG_WARNING, "Failed to create framebuffer");
  75. exit(1);
  76. }
  77. rlEnableFramebuffer(gBuffer.framebuffer);
  78. // NOTE: Vertex positions are stored in a texture for simplicity. A better approach would use a depth texture
  79. // (instead of a detph renderbuffer) to reconstruct world positions in the final render shader via clip-space position,
  80. // depth, and the inverse view/projection matrices.
  81. // 16-bit precision ensures OpenGL ES 3 compatibility, though it may lack precision for real scenarios.
  82. // But as mentioned above, the positions could be reconstructed instead of stored. If not targeting OpenGL ES
  83. // and you wish to maintain this approach, consider using `RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32`.
  84. gBuffer.positionTexture = rlLoadTexture(NULL, screenWidth, screenHeight, RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16, 1);
  85. // Similarly, 16-bit precision is used for normals ensures OpenGL ES 3 compatibility.
  86. // This is generally sufficient, but a 16-bit fixed-point format offer a better uniform precision in all orientations.
  87. gBuffer.normalTexture = rlLoadTexture(NULL, screenWidth, screenHeight, RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16, 1);
  88. // Albedo (diffuse color) and specular strength can be combined into one texture.
  89. // The color in RGB, and the specular strength in the alpha channel.
  90. gBuffer.albedoSpecTexture = rlLoadTexture(NULL, screenWidth, screenHeight, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1);
  91. // Activate the draw buffers for our framebuffer
  92. rlActiveDrawBuffers(3);
  93. // Now we attach our textures to the framebuffer.
  94. rlFramebufferAttach(gBuffer.framebuffer, gBuffer.positionTexture, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_TEXTURE2D, 0);
  95. rlFramebufferAttach(gBuffer.framebuffer, gBuffer.normalTexture, RL_ATTACHMENT_COLOR_CHANNEL1, RL_ATTACHMENT_TEXTURE2D, 0);
  96. rlFramebufferAttach(gBuffer.framebuffer, gBuffer.albedoSpecTexture, RL_ATTACHMENT_COLOR_CHANNEL2, RL_ATTACHMENT_TEXTURE2D, 0);
  97. // Finally we attach the depth buffer.
  98. gBuffer.depthRenderbuffer = rlLoadTextureDepth(screenWidth, screenHeight, true);
  99. rlFramebufferAttach(gBuffer.framebuffer, gBuffer.depthRenderbuffer, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_RENDERBUFFER, 0);
  100. // Make sure our framebuffer is complete.
  101. // NOTE: rlFramebufferComplete() automatically unbinds the framebuffer, so we don't have
  102. // to rlDisableFramebuffer() here.
  103. if (!rlFramebufferComplete(gBuffer.framebuffer))
  104. {
  105. TraceLog(LOG_WARNING, "Framebuffer is not complete");
  106. exit(1);
  107. }
  108. // Now we initialize the sampler2D uniform's in the deferred shader.
  109. // We do this by setting the uniform's values to the texture units that
  110. // we later bind our g-buffer textures to.
  111. rlEnableShader(deferredShader.id);
  112. int texUnitPosition = 0;
  113. int texUnitNormal = 1;
  114. int texUnitAlbedoSpec = 2;
  115. SetShaderValue(deferredShader, rlGetLocationUniform(deferredShader.id, "gPosition"), &texUnitPosition, RL_SHADER_UNIFORM_SAMPLER2D);
  116. SetShaderValue(deferredShader, rlGetLocationUniform(deferredShader.id, "gNormal"), &texUnitNormal, RL_SHADER_UNIFORM_SAMPLER2D);
  117. SetShaderValue(deferredShader, rlGetLocationUniform(deferredShader.id, "gAlbedoSpec"), &texUnitAlbedoSpec, RL_SHADER_UNIFORM_SAMPLER2D);
  118. rlDisableShader();
  119. // Assign out lighting shader to model
  120. model.materials[0].shader = gbufferShader;
  121. cube.materials[0].shader = gbufferShader;
  122. // Create lights
  123. //--------------------------------------------------------------------------------------
  124. Light lights[MAX_LIGHTS] = { 0 };
  125. lights[0] = CreateLight(LIGHT_POINT, (Vector3){ -2, 1, -2 }, Vector3Zero(), YELLOW, deferredShader);
  126. lights[1] = CreateLight(LIGHT_POINT, (Vector3){ 2, 1, 2 }, Vector3Zero(), RED, deferredShader);
  127. lights[2] = CreateLight(LIGHT_POINT, (Vector3){ -2, 1, 2 }, Vector3Zero(), GREEN, deferredShader);
  128. lights[3] = CreateLight(LIGHT_POINT, (Vector3){ 2, 1, -2 }, Vector3Zero(), BLUE, deferredShader);
  129. const float CUBE_SCALE = 0.25;
  130. Vector3 cubePositions[MAX_CUBES] = { 0 };
  131. float cubeRotations[MAX_CUBES] = { 0 };
  132. for (int i = 0; i < MAX_CUBES; i++)
  133. {
  134. cubePositions[i] = (Vector3){
  135. .x = (float)(rand()%10) - 5,
  136. .y = (float)(rand()%5),
  137. .z = (float)(rand()%10) - 5,
  138. };
  139. cubeRotations[i] = (float)(rand()%360);
  140. }
  141. DeferredMode mode = DEFERRED_SHADING;
  142. rlEnableDepthTest();
  143. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  144. //---------------------------------------------------------------------------------------
  145. // Main game loop
  146. while (!WindowShouldClose())
  147. {
  148. // Update
  149. //----------------------------------------------------------------------------------
  150. UpdateCamera(&camera, CAMERA_ORBITAL);
  151. // Update the shader with the camera view vector (points towards { 0.0f, 0.0f, 0.0f })
  152. float cameraPos[3] = { camera.position.x, camera.position.y, camera.position.z };
  153. SetShaderValue(deferredShader, deferredShader.locs[SHADER_LOC_VECTOR_VIEW], cameraPos, SHADER_UNIFORM_VEC3);
  154. // Check key inputs to enable/disable lights
  155. if (IsKeyPressed(KEY_Y)) { lights[0].enabled = !lights[0].enabled; }
  156. if (IsKeyPressed(KEY_R)) { lights[1].enabled = !lights[1].enabled; }
  157. if (IsKeyPressed(KEY_G)) { lights[2].enabled = !lights[2].enabled; }
  158. if (IsKeyPressed(KEY_B)) { lights[3].enabled = !lights[3].enabled; }
  159. // Check key inputs to switch between G-buffer textures
  160. if (IsKeyPressed(KEY_ONE)) mode = DEFERRED_POSITION;
  161. if (IsKeyPressed(KEY_TWO)) mode = DEFERRED_NORMAL;
  162. if (IsKeyPressed(KEY_THREE)) mode = DEFERRED_ALBEDO;
  163. if (IsKeyPressed(KEY_FOUR)) mode = DEFERRED_SHADING;
  164. // Update light values (actually, only enable/disable them)
  165. for (int i = 0; i < MAX_LIGHTS; i++) UpdateLightValues(deferredShader, lights[i]);
  166. //----------------------------------------------------------------------------------
  167. // Draw
  168. // ---------------------------------------------------------------------------------
  169. BeginDrawing();
  170. // Draw to the geometry buffer by first activating it
  171. rlEnableFramebuffer(gBuffer.framebuffer);
  172. rlClearColor(0, 0, 0, 0);
  173. rlClearScreenBuffers(); // Clear color and depth buffer
  174. rlDisableColorBlend();
  175. BeginMode3D(camera);
  176. // NOTE: We have to use rlEnableShader here. `BeginShaderMode` or thus `rlSetShader`
  177. // will not work, as they won't immediately load the shader program.
  178. rlEnableShader(gbufferShader.id);
  179. // When drawing a model here, make sure that the material's shaders
  180. // are set to the gbuffer shader!
  181. DrawModel(model, Vector3Zero(), 1.0f, WHITE);
  182. DrawModel(cube, (Vector3) { 0.0, 1.0f, 0.0 }, 1.0f, WHITE);
  183. for (int i = 0; i < MAX_CUBES; i++)
  184. {
  185. Vector3 position = cubePositions[i];
  186. DrawModelEx(cube, position, (Vector3) { 1, 1, 1 }, cubeRotations[i], (Vector3) { CUBE_SCALE, CUBE_SCALE, CUBE_SCALE }, WHITE);
  187. }
  188. rlDisableShader();
  189. EndMode3D();
  190. rlEnableColorBlend();
  191. // Go back to the default framebuffer (0) and draw our deferred shading.
  192. rlDisableFramebuffer();
  193. rlClearScreenBuffers(); // Clear color & depth buffer
  194. switch (mode)
  195. {
  196. case DEFERRED_SHADING:
  197. {
  198. BeginMode3D(camera);
  199. rlDisableColorBlend();
  200. rlEnableShader(deferredShader.id);
  201. // Bind our g-buffer textures
  202. // We are binding them to locations that we earlier set in sampler2D uniforms `gPosition`, `gNormal`,
  203. // and `gAlbedoSpec`
  204. rlActiveTextureSlot(texUnitPosition);
  205. rlEnableTexture(gBuffer.positionTexture);
  206. rlActiveTextureSlot(texUnitNormal);
  207. rlEnableTexture(gBuffer.normalTexture);
  208. rlActiveTextureSlot(texUnitAlbedoSpec);
  209. rlEnableTexture(gBuffer.albedoSpecTexture);
  210. // Finally, we draw a fullscreen quad to our default framebuffer
  211. // This will now be shaded using our deferred shader
  212. rlLoadDrawQuad();
  213. rlDisableShader();
  214. rlEnableColorBlend();
  215. EndMode3D();
  216. // As a last step, we now copy over the depth buffer from our g-buffer to the default framebuffer.
  217. rlBindFramebuffer(RL_READ_FRAMEBUFFER, gBuffer.framebuffer);
  218. rlBindFramebuffer(RL_DRAW_FRAMEBUFFER, 0);
  219. rlBlitFramebuffer(0, 0, screenWidth, screenHeight, 0, 0, screenWidth, screenHeight, 0x00000100); // GL_DEPTH_BUFFER_BIT
  220. rlDisableFramebuffer();
  221. // Since our shader is now done and disabled, we can draw spheres
  222. // that represent light positions in default forward rendering
  223. BeginMode3D(camera);
  224. rlEnableShader(rlGetShaderIdDefault());
  225. for (int i = 0; i < MAX_LIGHTS; i++)
  226. {
  227. if (lights[i].enabled) DrawSphereEx(lights[i].position, 0.2f, 8, 8, lights[i].color);
  228. else DrawSphereWires(lights[i].position, 0.2f, 8, 8, ColorAlpha(lights[i].color, 0.3f));
  229. }
  230. rlDisableShader();
  231. EndMode3D();
  232. DrawText("FINAL RESULT", 10, screenHeight - 30, 20, DARKGREEN);
  233. } break;
  234. case DEFERRED_POSITION:
  235. {
  236. DrawTextureRec((Texture2D){
  237. .id = gBuffer.positionTexture,
  238. .width = screenWidth,
  239. .height = screenHeight,
  240. }, (Rectangle) { 0, 0, (float)screenWidth, (float)-screenHeight }, Vector2Zero(), RAYWHITE);
  241. DrawText("POSITION TEXTURE", 10, screenHeight - 30, 20, DARKGREEN);
  242. } break;
  243. case DEFERRED_NORMAL:
  244. {
  245. DrawTextureRec((Texture2D){
  246. .id = gBuffer.normalTexture,
  247. .width = screenWidth,
  248. .height = screenHeight,
  249. }, (Rectangle) { 0, 0, (float)screenWidth, (float)-screenHeight }, Vector2Zero(), RAYWHITE);
  250. DrawText("NORMAL TEXTURE", 10, screenHeight - 30, 20, DARKGREEN);
  251. } break;
  252. case DEFERRED_ALBEDO:
  253. {
  254. DrawTextureRec((Texture2D){
  255. .id = gBuffer.albedoSpecTexture,
  256. .width = screenWidth,
  257. .height = screenHeight,
  258. }, (Rectangle) { 0, 0, (float)screenWidth, (float)-screenHeight }, Vector2Zero(), RAYWHITE);
  259. DrawText("ALBEDO TEXTURE", 10, screenHeight - 30, 20, DARKGREEN);
  260. } break;
  261. default: break;
  262. }
  263. DrawText("Toggle lights keys: [Y][R][G][B]", 10, 40, 20, DARKGRAY);
  264. DrawText("Switch G-buffer textures: [1][2][3][4]", 10, 70, 20, DARKGRAY);
  265. DrawFPS(10, 10);
  266. EndDrawing();
  267. // -----------------------------------------------------------------------------
  268. }
  269. // De-Initialization
  270. //--------------------------------------------------------------------------------------
  271. UnloadModel(model); // Unload the models
  272. UnloadModel(cube);
  273. UnloadShader(deferredShader); // Unload shaders
  274. UnloadShader(gbufferShader);
  275. // Unload geometry buffer and all attached textures
  276. rlUnloadFramebuffer(gBuffer.framebuffer);
  277. rlUnloadTexture(gBuffer.positionTexture);
  278. rlUnloadTexture(gBuffer.normalTexture);
  279. rlUnloadTexture(gBuffer.albedoSpecTexture);
  280. rlUnloadTexture(gBuffer.depthRenderbuffer);
  281. CloseWindow(); // Close window and OpenGL context
  282. //--------------------------------------------------------------------------------------
  283. return 0;
  284. }