models_skybox_rendering.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /*******************************************************************************************
  2. *
  3. * raylib [models] example - skybox rendering
  4. *
  5. * Example complexity rating: [★★☆☆] 2/4
  6. *
  7. * Example originally created with raylib 1.8, last time updated with raylib 4.0
  8. *
  9. * Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
  10. * BSD-like license that allows static linking with closed source software
  11. *
  12. * Copyright (c) 2017-2025 Ramon Santamaria (@raysan5)
  13. *
  14. ********************************************************************************************/
  15. #include "raylib.h"
  16. #include "rlgl.h"
  17. #include "raymath.h" // Required for: MatrixPerspective(), MatrixLookAt()
  18. #if defined(PLATFORM_DESKTOP)
  19. #define GLSL_VERSION 330
  20. #else // PLATFORM_ANDROID, PLATFORM_WEB
  21. #define GLSL_VERSION 100
  22. #endif
  23. //------------------------------------------------------------------------------------
  24. // Module Functions Declaration
  25. //------------------------------------------------------------------------------------
  26. // Generate cubemap (6 faces) from equirectangular (panorama) texture
  27. static TextureCubemap GenTextureCubemap(Shader shader, Texture2D panorama, int size, int format);
  28. //------------------------------------------------------------------------------------
  29. // Program main entry point
  30. //------------------------------------------------------------------------------------
  31. int main(void)
  32. {
  33. // Initialization
  34. //--------------------------------------------------------------------------------------
  35. const int screenWidth = 800;
  36. const int screenHeight = 450;
  37. InitWindow(screenWidth, screenHeight, "raylib [models] example - skybox rendering");
  38. // Define the camera to look into our 3d world
  39. Camera camera = { 0 };
  40. camera.position = (Vector3){ 1.0f, 1.0f, 1.0f }; // Camera position
  41. camera.target = (Vector3){ 4.0f, 1.0f, 4.0f }; // Camera looking at point
  42. camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
  43. camera.fovy = 45.0f; // Camera field-of-view Y
  44. camera.projection = CAMERA_PERSPECTIVE; // Camera projection type
  45. // Load skybox model
  46. Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
  47. Model skybox = LoadModelFromMesh(cube);
  48. // Set this to true to use an HDR Texture
  49. // NOTE: raylib must be built with HDR Support for this to work: SUPPORT_FILEFORMAT_HDR
  50. bool useHDR = false;
  51. // Load skybox shader and set required locations
  52. // NOTE: Some locations are automatically set at shader loading
  53. skybox.materials[0].shader = LoadShader(TextFormat("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION),
  54. TextFormat("resources/shaders/glsl%i/skybox.fs", GLSL_VERSION));
  55. SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "environmentMap"), (int[1]){ MATERIAL_MAP_CUBEMAP }, SHADER_UNIFORM_INT);
  56. SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "doGamma"), (int[1]){ useHDR? 1 : 0 }, SHADER_UNIFORM_INT);
  57. SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "vflipped"), (int[1]){ useHDR? 1 : 0 }, SHADER_UNIFORM_INT);
  58. // Load cubemap shader and setup required shader locations
  59. Shader shdrCubemap = LoadShader(TextFormat("resources/shaders/glsl%i/cubemap.vs", GLSL_VERSION),
  60. TextFormat("resources/shaders/glsl%i/cubemap.fs", GLSL_VERSION));
  61. SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT);
  62. char skyboxFileName[256] = { 0 };
  63. if (useHDR)
  64. {
  65. TextCopy(skyboxFileName, "resources/dresden_square_2k.hdr");
  66. // Load HDR panorama (sphere) texture
  67. Texture2D panorama = LoadTexture(skyboxFileName);
  68. // Generate cubemap (texture with 6 quads-cube-mapping) from panorama HDR texture
  69. // NOTE 1: New texture is generated rendering to texture, shader calculates the sphere->cube coordinates mapping
  70. // NOTE 2: It seems on some Android devices WebGL, fbo does not properly support a FLOAT-based attachment,
  71. // despite texture can be successfully created.. so using PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 instead of PIXELFORMAT_UNCOMPRESSED_R32G32B32A32
  72. skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, panorama, 1024, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8);
  73. UnloadTexture(panorama); // Texture not required anymore, cubemap already generated
  74. }
  75. else
  76. {
  77. // TODO: WARNING: On PLATFORM_WEB it requires a big amount of memory to process input image
  78. // and generate the required cubemap image to be passed to rlLoadTextureCubemap()
  79. Image image = LoadImage("resources/skybox.png");
  80. skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = LoadTextureCubemap(image, CUBEMAP_LAYOUT_AUTO_DETECT);
  81. UnloadImage(image);
  82. }
  83. DisableCursor(); // Limit cursor to relative movement inside the window
  84. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  85. //--------------------------------------------------------------------------------------
  86. // Main game loop
  87. while (!WindowShouldClose()) // Detect window close button or ESC key
  88. {
  89. // Update
  90. //----------------------------------------------------------------------------------
  91. UpdateCamera(&camera, CAMERA_FIRST_PERSON);
  92. // Load new cubemap texture on drag&drop
  93. if (IsFileDropped())
  94. {
  95. FilePathList droppedFiles = LoadDroppedFiles();
  96. if (droppedFiles.count == 1) // Only support one file dropped
  97. {
  98. if (IsFileExtension(droppedFiles.paths[0], ".png;.jpg;.hdr;.bmp;.tga"))
  99. {
  100. // Unload current cubemap texture to load new one
  101. UnloadTexture(skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture);
  102. if (useHDR)
  103. {
  104. // Load HDR panorama (sphere) texture
  105. Texture2D panorama = LoadTexture(droppedFiles.paths[0]);
  106. // Generate cubemap from panorama texture
  107. skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, panorama, 1024, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8);
  108. UnloadTexture(panorama); // Texture not required anymore, cubemap already generated
  109. }
  110. else
  111. {
  112. Image image = LoadImage(droppedFiles.paths[0]);
  113. skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = LoadTextureCubemap(image, CUBEMAP_LAYOUT_AUTO_DETECT);
  114. UnloadImage(image);
  115. }
  116. TextCopy(skyboxFileName, droppedFiles.paths[0]);
  117. }
  118. }
  119. UnloadDroppedFiles(droppedFiles); // Unload filepaths from memory
  120. }
  121. //----------------------------------------------------------------------------------
  122. // Draw
  123. //----------------------------------------------------------------------------------
  124. BeginDrawing();
  125. ClearBackground(RAYWHITE);
  126. BeginMode3D(camera);
  127. // We are inside the cube, we need to disable backface culling!
  128. rlDisableBackfaceCulling();
  129. rlDisableDepthMask();
  130. DrawModel(skybox, (Vector3){0, 0, 0}, 1.0f, WHITE);
  131. rlEnableBackfaceCulling();
  132. rlEnableDepthMask();
  133. DrawGrid(10, 1.0f);
  134. EndMode3D();
  135. if (useHDR) DrawText(TextFormat("Panorama image from hdrihaven.com: %s", GetFileName(skyboxFileName)), 10, GetScreenHeight() - 20, 10, BLACK);
  136. else DrawText(TextFormat(": %s", GetFileName(skyboxFileName)), 10, GetScreenHeight() - 20, 10, BLACK);
  137. DrawFPS(10, 10);
  138. EndDrawing();
  139. //----------------------------------------------------------------------------------
  140. }
  141. // De-Initialization
  142. //--------------------------------------------------------------------------------------
  143. UnloadShader(skybox.materials[0].shader);
  144. UnloadTexture(skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture);
  145. UnloadModel(skybox); // Unload skybox model
  146. CloseWindow(); // Close window and OpenGL context
  147. //--------------------------------------------------------------------------------------
  148. return 0;
  149. }
  150. //------------------------------------------------------------------------------------
  151. // Module Functions Definition
  152. //------------------------------------------------------------------------------------
  153. // Generate cubemap texture from HDR texture
  154. static TextureCubemap GenTextureCubemap(Shader shader, Texture2D panorama, int size, int format)
  155. {
  156. TextureCubemap cubemap = { 0 };
  157. rlDisableBackfaceCulling(); // Disable backface culling to render inside the cube
  158. // STEP 1: Setup framebuffer
  159. //------------------------------------------------------------------------------------------
  160. unsigned int rbo = rlLoadTextureDepth(size, size, true);
  161. cubemap.id = rlLoadTextureCubemap(0, size, format, 1);
  162. unsigned int fbo = rlLoadFramebuffer();
  163. rlFramebufferAttach(fbo, rbo, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_RENDERBUFFER, 0);
  164. rlFramebufferAttach(fbo, cubemap.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_CUBEMAP_POSITIVE_X, 0);
  165. // Check if framebuffer is complete with attachments (valid)
  166. if (rlFramebufferComplete(fbo)) TraceLog(LOG_INFO, "FBO: [ID %i] Framebuffer object created successfully", fbo);
  167. //------------------------------------------------------------------------------------------
  168. // STEP 2: Draw to framebuffer
  169. //------------------------------------------------------------------------------------------
  170. // NOTE: Shader is used to convert HDR equirectangular environment map to cubemap equivalent (6 faces)
  171. rlEnableShader(shader.id);
  172. // Define projection matrix and send it to shader
  173. Matrix matFboProjection = MatrixPerspective(90.0*DEG2RAD, 1.0, rlGetCullDistanceNear(), rlGetCullDistanceFar());
  174. rlSetUniformMatrix(shader.locs[SHADER_LOC_MATRIX_PROJECTION], matFboProjection);
  175. // Define view matrix for every side of the cubemap
  176. Matrix fboViews[6] = {
  177. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }),
  178. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ -1.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }),
  179. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }),
  180. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }),
  181. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, 1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f }),
  182. MatrixLookAt((Vector3){ 0.0f, 0.0f, 0.0f }, (Vector3){ 0.0f, 0.0f, -1.0f }, (Vector3){ 0.0f, -1.0f, 0.0f })
  183. };
  184. rlViewport(0, 0, size, size); // Set viewport to current fbo dimensions
  185. // Activate and enable texture for drawing to cubemap faces
  186. rlActiveTextureSlot(0);
  187. rlEnableTexture(panorama.id);
  188. for (int i = 0; i < 6; i++)
  189. {
  190. // Set the view matrix for the current cube face
  191. rlSetUniformMatrix(shader.locs[SHADER_LOC_MATRIX_VIEW], fboViews[i]);
  192. // Select the current cubemap face attachment for the fbo
  193. // WARNING: This function by default enables->attach->disables fbo!!!
  194. rlFramebufferAttach(fbo, cubemap.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_CUBEMAP_POSITIVE_X + i, 0);
  195. rlEnableFramebuffer(fbo);
  196. // Load and draw a cube, it uses the current enabled texture
  197. rlClearScreenBuffers();
  198. rlLoadDrawCube();
  199. // ALTERNATIVE: Try to use internal batch system to draw the cube instead of rlLoadDrawCube
  200. // for some reason this method does not work, maybe due to cube triangles definition? normals pointing out?
  201. // TODO: Investigate this issue...
  202. //rlSetTexture(panorama.id); // WARNING: It must be called after enabling current framebuffer if using internal batch system!
  203. //rlClearScreenBuffers();
  204. //DrawCubeV(Vector3Zero(), Vector3One(), WHITE);
  205. //rlDrawRenderBatchActive();
  206. }
  207. //------------------------------------------------------------------------------------------
  208. // STEP 3: Unload framebuffer and reset state
  209. //------------------------------------------------------------------------------------------
  210. rlDisableShader(); // Unbind shader
  211. rlDisableTexture(); // Unbind texture
  212. rlDisableFramebuffer(); // Unbind framebuffer
  213. rlUnloadFramebuffer(fbo); // Unload framebuffer (and automatically attached depth texture/renderbuffer)
  214. // Reset viewport dimensions to default
  215. rlViewport(0, 0, rlGetFramebufferWidth(), rlGetFramebufferHeight());
  216. rlEnableBackfaceCulling();
  217. //------------------------------------------------------------------------------------------
  218. cubemap.width = size;
  219. cubemap.height = size;
  220. cubemap.mipmaps = 1;
  221. cubemap.format = format;
  222. return cubemap;
  223. }