main.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /*
  2. * 3D Engine
  3. * main.c:
  4. * Based on pikuma.com 3D software renderer in C
  5. * Copyright (c) 2021 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 01/03/2021.
  8. */
  9. #include <stdio.h>
  10. #include <stdint.h>
  11. #include <stdbool.h>
  12. #include <libc.h>
  13. #include <SDL.h>
  14. #include <log.h>
  15. #include <array.h>
  16. #include <matrix.h>
  17. #include <triangle.h>
  18. #include <display.h>
  19. #include <vector.h>
  20. #include <mesh.h>
  21. #include <light.h>
  22. bool isRunning = true;
  23. int previousFrameTime = 0;
  24. typedef enum displayMode_t
  25. {
  26. DISPLAY_MODE_WIREFRAME,
  27. DISPLAY_MODE_SOLID,
  28. DISPLAY_MODE_SOLID_WIRE,
  29. DISPLAY_MODE_TEXTURED,
  30. DISPLAY_MODE_TEXTURED_WIRE,
  31. } displayMode_t;
  32. bool displayVertex = false;
  33. bool doNotCull = false;
  34. enum displayMode_t currentDisplayMode = DISPLAY_MODE_SOLID;
  35. matrix4_t projectionMatrix;
  36. light_t globalLight;
  37. double updateTime, renderTime, waitTime;
  38. vec3_t cameraPosition =
  39. {
  40. .x = 0,
  41. .y = 0,
  42. .z = 0,
  43. };
  44. triangle_t *projectedTriangles = NULL;
  45. void setup()
  46. {
  47. frameBuffer = (uint32_t *)calloc(windowWidth * windowHeight, sizeof(uint32_t));
  48. if (!frameBuffer)
  49. {
  50. Log(TLOG_PANIC, NULL, "Memory allocation error.");
  51. goto exit;
  52. }
  53. frameBufferTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, windowWidth,
  54. windowHeight);
  55. if (frameBufferTexture == NULL)
  56. {
  57. Log(TLOG_PANIC, NULL, "SDL Texture creation error: %s", SDL_GetError());
  58. goto exit;
  59. }
  60. projectionMatrix = mat4Perspective((double)windowHeight / windowWidth, 90, 0.1, 100);
  61. globalLight.direction.x = 0;
  62. globalLight.direction.y = 0;
  63. globalLight.direction.z = 1;
  64. vec3Normalize(&globalLight.direction);
  65. meshTexture = (colour_t *)REDBRICK_TEXTURE;
  66. //loadOBJFile("assets/f22.obj");
  67. loadCubeMeshData();
  68. exit:
  69. return;
  70. }
  71. void processInput()
  72. {
  73. SDL_Event event;
  74. SDL_PollEvent(&event);
  75. switch (event.type)
  76. {
  77. case SDL_QUIT:isRunning = false;
  78. break;
  79. case SDL_KEYDOWN:
  80. switch(event.key.keysym.sym)
  81. {
  82. case SDLK_ESCAPE:
  83. isRunning = false;
  84. break;
  85. case SDLK_1:
  86. displayVertex = true;
  87. currentDisplayMode = DISPLAY_MODE_WIREFRAME;
  88. break;
  89. case SDLK_2:
  90. displayVertex = false;
  91. currentDisplayMode = DISPLAY_MODE_WIREFRAME;
  92. break;
  93. case SDLK_3:
  94. displayVertex = false;
  95. currentDisplayMode = DISPLAY_MODE_SOLID;
  96. break;
  97. case SDLK_4:
  98. displayVertex = false;
  99. currentDisplayMode = DISPLAY_MODE_SOLID_WIRE;
  100. break;
  101. case SDLK_5:
  102. displayVertex = false;
  103. currentDisplayMode = DISPLAY_MODE_TEXTURED;
  104. break;
  105. case SDLK_6:
  106. displayVertex = false;
  107. currentDisplayMode = DISPLAY_MODE_TEXTURED_WIRE;
  108. break;
  109. case SDLK_c:
  110. doNotCull = false;
  111. break;
  112. case SDLK_d:
  113. doNotCull = true;
  114. break;
  115. }
  116. break;
  117. default:
  118. break;
  119. }
  120. }
  121. uint32_t getMicroSecTime()
  122. {
  123. struct timeval curTime;
  124. gettimeofday(&curTime, NULL);
  125. return ((curTime.tv_sec) * 1000 * 1000) + (curTime.tv_usec);
  126. }
  127. void update()
  128. {
  129. uint32_t i, j;
  130. uint32_t faceCount;
  131. uint32_t timeToWait = FRAME_TARGET_TIME - (SDL_GetTicks() - previousFrameTime);
  132. matrix4_t worldMatrix;
  133. uint32_t ticks = getMicroSecTime();
  134. if (timeToWait <= FRAME_TARGET_TIME)
  135. {
  136. SDL_Delay(timeToWait);
  137. }
  138. previousFrameTime = SDL_GetTicks();
  139. waitTime = (waitTime + (getMicroSecTime() - ticks) / 1000.) / 2.0;
  140. ticks = getMicroSecTime();
  141. mesh.rotation.x += 0.01;
  142. mesh.translation.z = 5;
  143. worldMatrix = mat4Identity;
  144. worldMatrix = mat4ProdMat4(mat4Scale(mesh.scale.x, mesh.scale.y, mesh.scale.z), worldMatrix);
  145. worldMatrix = mat4ProdMat4(mat4RotationZ(mesh.rotation.z), worldMatrix);
  146. worldMatrix = mat4ProdMat4(mat4RotationY(mesh.rotation.y), worldMatrix);
  147. worldMatrix = mat4ProdMat4(mat4RotationX(mesh.rotation.x), worldMatrix);
  148. worldMatrix = mat4ProdMat4(mat4Translate(mesh.translation.x, mesh.translation.y, mesh.translation.z), worldMatrix);
  149. arrayEmpty(projectedTriangles);
  150. faceCount = arrayGetSize(mesh.faces);
  151. for(i = 0; i < faceCount; i++)
  152. {
  153. triangle_t currentTriangle =
  154. {
  155. .textureCoordinates =
  156. {
  157. [0] = { mesh.faces[i].a_uv.u, mesh.faces[i].a_uv.v },
  158. [1] = { mesh.faces[i].b_uv.u, mesh.faces[i].b_uv.v },
  159. [2] = { mesh.faces[i].c_uv.u, mesh.faces[i].c_uv.v }
  160. }
  161. };
  162. vec4_t transformedVertices[3];
  163. vec3_t triangleNormal;
  164. vec3_t vertices[3] =
  165. {
  166. mesh.vertices[mesh.faces[i].a - 1],
  167. mesh.vertices[mesh.faces[i].b - 1],
  168. mesh.vertices[mesh.faces[i].c - 1],
  169. };
  170. for(j = 0; j < 3; j++)
  171. {
  172. transformedVertices[j] = vec4FromVec3(vertices[j]);
  173. transformedVertices[j] = mat4ProdVec4(worldMatrix, transformedVertices[j]);
  174. }
  175. vec3_t vectorBA = vec3SubVectors(vec3FromVec4(transformedVertices[1]), vec3FromVec4(transformedVertices[0]));
  176. vec3_t vectorCA = vec3SubVectors(vec3FromVec4(transformedVertices[2]), vec3FromVec4(transformedVertices[0]));
  177. vec3Normalize(&vectorBA);
  178. vec3Normalize(&vectorCA);
  179. triangleNormal = vec3Cross(vectorBA, vectorCA);
  180. vec3Normalize(&triangleNormal);
  181. if (!doNotCull)
  182. {
  183. vec3_t cameraRay = vec3SubVectors(cameraPosition, vec3FromVec4(transformedVertices[0]));
  184. vec3Normalize(&cameraRay);
  185. double cameraDotTriangle = vec3Dot(triangleNormal, cameraRay);
  186. if (cameraDotTriangle < 0)
  187. {
  188. continue;
  189. }
  190. }
  191. for (j = 0 ; j < 3 ; j++)
  192. {
  193. vec4_t projected = mat4ProdVec4Project(projectionMatrix, transformedVertices[j]);
  194. projected.x *= windowWidth / 2.;
  195. projected.y *= windowHeight / 2.;
  196. /* Screen Y axis increase down, 3D world Y grows up, so we need to invert. */
  197. projected.y *= -1.0;
  198. projected.x += (windowWidth / 2.);
  199. projected.y += (windowHeight / 2.);
  200. currentTriangle.points[j].x = projected.x;
  201. currentTriangle.points[j].y = projected.y;
  202. }
  203. double lightLevel = -vec3Dot(triangleNormal, globalLight.direction);
  204. currentTriangle.colour = applyLight(mesh.faces[i].colour, lightLevel);
  205. currentTriangle.averageDepth = (transformedVertices[0].z +
  206. transformedVertices[1].z +
  207. transformedVertices[2].z) / 3.0;
  208. currentTriangle.texture = meshTexture;
  209. arrayAdd(projectedTriangles, currentTriangle);
  210. }
  211. qsort(projectedTriangles,
  212. arrayGetSize(projectedTriangles),
  213. sizeof(triangle_t),
  214. compareTrianglesZOrder);
  215. updateTime = (updateTime + (getMicroSecTime() - ticks) / 1000.) / 2.0;
  216. }
  217. void render()
  218. {
  219. int i;
  220. uint32_t ticks = getMicroSecTime();
  221. SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
  222. SDL_RenderClear(renderer);
  223. int triangleCount = arrayGetSize(projectedTriangles);
  224. for(i = 0; i < triangleCount; i++)
  225. {
  226. switch(currentDisplayMode)
  227. {
  228. case DISPLAY_MODE_SOLID:
  229. case DISPLAY_MODE_SOLID_WIRE:
  230. drawFilledTriangle(projectedTriangles[i].points[0].x, projectedTriangles[i].points[0].y,
  231. projectedTriangles[i].points[1].x, projectedTriangles[i].points[1].y,
  232. projectedTriangles[i].points[2].x, projectedTriangles[i].points[2].y,
  233. projectedTriangles[i].colour);
  234. break;
  235. case DISPLAY_MODE_TEXTURED:
  236. case DISPLAY_MODE_TEXTURED_WIRE:
  237. drawTextureTriangle(&projectedTriangles[i]);
  238. break;
  239. default:
  240. break;
  241. }
  242. switch (currentDisplayMode)
  243. {
  244. case DISPLAY_MODE_SOLID_WIRE:
  245. case DISPLAY_MODE_TEXTURED_WIRE:
  246. case DISPLAY_MODE_WIREFRAME:
  247. drawTriangle(projectedTriangles[i].points[0].x, projectedTriangles[i].points[0].y,
  248. projectedTriangles[i].points[1].x, projectedTriangles[i].points[1].y,
  249. projectedTriangles[i].points[2].x, projectedTriangles[i].points[2].y,
  250. projectedTriangles[i].colour);
  251. break;
  252. default:
  253. break;
  254. }
  255. if (displayVertex)
  256. {
  257. int j;
  258. for(j = 0; j < 3; j++)
  259. {
  260. drawRectangle(projectedTriangles[i].points[j].x - 1,
  261. projectedTriangles[i].points[j].y - 1,
  262. 3, 3,
  263. 0xFFFF0000);
  264. }
  265. }
  266. }
  267. renderFrameBuffer();
  268. clearFrameBuffer(0xFF000000);
  269. renderTime = (renderTime + (getMicroSecTime() - ticks) / 1000.) / 2.0;
  270. drawText(5, 5, 0x11FF22, "Wait time: %02.2f ms", waitTime);
  271. drawText(5, 17, 0x11FF22, "Update time: %02.2f ms", updateTime);
  272. drawText(5, 29, 0x11FF22, "Render time: %02.2f ms", renderTime);
  273. drawText(5, 41, 0x11FF22, "FPS: %.2f", 1000 / (waitTime + updateTime + renderTime));
  274. SDL_RenderPresent(renderer);
  275. }
  276. int main(int argc, char *argv[])
  277. {
  278. int param_i;
  279. bool fullScreen = false;
  280. MAX_DEBUG_LEVEL = TLOG_DEBUG;
  281. Log(TLOG_ALWAYS, NULL, "Booting 3D Engine (version %s)!", VERSION);
  282. for (param_i = 1 ; (param_i < argc) && (argv[param_i][0] == '-') ; param_i++)
  283. {
  284. switch (argv[param_i][1])
  285. {
  286. default: exit(-1); /* Option not recognized */
  287. case 'f': fullScreen = true; break;
  288. case 'w': windowWidth = atoi(argv[++param_i]);
  289. case 'h': windowHeight = atoi(argv[++param_i]); break;
  290. #ifdef DYNA_LOG_LEVEL
  291. case 'l': MAX_DEBUG_LEVEL = atoi(argv[++param_i]); break;
  292. #endif
  293. case '-': goto no_more_params; /* Could use break, but this is more clear */
  294. }
  295. }
  296. no_more_params:
  297. isRunning = initialiseWindow(fullScreen);
  298. setup();
  299. while (isRunning)
  300. {
  301. processInput();
  302. update();
  303. render();
  304. }
  305. arrayFree(projectedTriangles);
  306. meshFree();
  307. destroyWindow();
  308. return 0;
  309. }