render_opengl.cpp
上传用户:gzqinmao
上传日期:2022-07-13
资源大小:472k
文件大小:3k
源码类别:

OpenGL

开发平台:

Visual C++

  1. #include <windows.h>
  2. // Standard OpenGL header
  3. #include <GL/gl.h>
  4. #include "Gut.h"
  5. #include "render_data.h"
  6. static Matrix4x4 g_view_matrix;
  7. bool InitResourceOpenGL(void)
  8. {
  9. // 计算出一个可以转换到镜头坐标系的矩阵
  10. g_view_matrix = GutMatrixLookAtRH(g_eye, g_lookat, g_up);
  11. // 投影矩阵
  12. Matrix4x4 projection_matrix = GutMatrixPerspectiveRH_OpenGL(90.0f, 1.0f, 0.1f, 100.0f);
  13. // 设置视角转换矩阵
  14. glMatrixMode(GL_PROJECTION);
  15. glLoadMatrixf( (float *) &projection_matrix);
  16. glMatrixMode(GL_MODELVIEW);
  17. glEnable(GL_CULL_FACE);
  18. return true;
  19. }
  20. bool ReleaseResourceOpenGL(void)
  21. {
  22. // 没做任何事
  23. return true;
  24. }
  25. // callback function. 窗口大小改变时会被调用, 并传入新的窗口大小.
  26. void ResizeWindowOpenGL(int width, int height)
  27. {
  28. // 使用新的窗口大小做为新的绘图分辨率
  29. glViewport(0, 0, width, height);
  30. // 投影矩阵, 重设水平和垂直方向的视角.
  31. float aspect = (float) height / (float) width;
  32. Matrix4x4 projection_matrix = GutMatrixPerspectiveRH_OpenGL(60.0f, aspect, 0.1f, 100.0f);
  33. // 设置视角转换矩阵
  34. glMatrixMode(GL_PROJECTION);
  35. glLoadMatrixf( (float *) &projection_matrix);
  36. }
  37. // `使用OpenGL来绘图`
  38. void RenderFrameOpenGL(void)
  39. {
  40. // `清除画面`
  41. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  42. glEnable(GL_DEPTH_TEST);
  43. // `设置要用数组的方式传入顶点位置和颜色`
  44. glEnableClientState(GL_VERTEX_ARRAY);
  45. glEnableClientState(GL_COLOR_ARRAY);
  46. // `计算出一个可以转换到镜头坐标系的矩阵`
  47. Matrix4x4 view_matrix = GutMatrixLookAtRH(g_eye, g_lookat, g_up);
  48. Matrix4x4 world_view_matrix;
  49. glMatrixMode(GL_MODELVIEW);
  50. // `太阳`
  51. world_view_matrix = g_sun_matrix * view_matrix;
  52. glLoadMatrixf( (float *) &world_view_matrix);
  53. glVertexPointer(3, GL_FLOAT, sizeof(Vertex_VC), g_pSunVertices);
  54. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex_VC), g_pSunVertices[0].m_RGBA);
  55. glDrawElements(GL_TRIANGLES, g_iNumSphereIndices, GL_UNSIGNED_SHORT, g_pSphereIndices);
  56. // `地球`
  57. world_view_matrix = g_earth_matrix * view_matrix;
  58. glLoadMatrixf( (float *) &world_view_matrix);
  59. glVertexPointer(3, GL_FLOAT, sizeof(Vertex_VC), g_pEarthVertices);
  60. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex_VC), g_pEarthVertices[0].m_RGBA);
  61. glDrawElements(GL_TRIANGLES, g_iNumSphereIndices, GL_UNSIGNED_SHORT, g_pSphereIndices);
  62. // `月球`
  63. world_view_matrix = g_moon_matrix * view_matrix;
  64. glLoadMatrixf( (float *) &world_view_matrix);
  65. glVertexPointer(3, GL_FLOAT, sizeof(Vertex_VC), g_pMoonVertices);
  66. glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex_VC), g_pMoonVertices[0].m_RGBA);
  67. glDrawElements(GL_TRIANGLES, g_iNumSphereIndices, GL_UNSIGNED_SHORT, g_pSphereIndices);
  68. // `把背景backbuffer的画面显示出来`
  69. GutSwapBuffersOpenGL();
  70. }