main.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. #include <camera.h>
  23. #include <clipping.h>
  24. bool isRunning = true;
  25. int previousFrameTime = 0;
  26. double deltaTime = 0;
  27. typedef enum displayMode_t
  28. {
  29. DISPLAY_MODE_WIREFRAME,
  30. DISPLAY_MODE_SOLID,
  31. DISPLAY_MODE_SOLID_WIRE,
  32. DISPLAY_MODE_TEXTURED,
  33. DISPLAY_MODE_TEXTURED_WIRE,
  34. } displayMode_t;
  35. bool displayVertex = false;
  36. bool doNotCull = false;
  37. bool doZBuffer = true;
  38. bool doClipping = true;
  39. enum displayMode_t currentDisplayMode = DISPLAY_MODE_WIREFRAME;
  40. matrix4_t projectionMatrix;
  41. matrix4_t viewMatrix;
  42. light_t globalLight;
  43. double updateTime, renderTime, waitTime;
  44. int trianglesCount, trianglesTotal;
  45. triangle_t *projectedTriangles = NULL;
  46. static const vec3_t origin = {0, 0, 0 };
  47. void setup()
  48. {
  49. double FOV = 60;
  50. double aspectRatio = (double)windowHeight / windowWidth;
  51. double zNear = 1;
  52. double zFar = 20;
  53. frameBuffer = (uint32_t *)calloc(windowWidth * windowHeight, sizeof(uint32_t));
  54. if (!frameBuffer)
  55. {
  56. Log(TLOG_PANIC, NULL, "Memory allocation error.");
  57. goto exit;
  58. }
  59. zBuffer = (double *)calloc(windowWidth * windowHeight, sizeof(double));
  60. if (!frameBuffer)
  61. {
  62. Log(TLOG_PANIC, NULL, "Memory allocation error.");
  63. goto exit;
  64. }
  65. frameBufferTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STREAMING, windowWidth,
  66. windowHeight);
  67. if (frameBufferTexture == NULL)
  68. {
  69. Log(TLOG_PANIC, NULL, "SDL Texture creation error: %s", SDL_GetError());
  70. goto exit;
  71. }
  72. projectionMatrix = mat4Perspective(aspectRatio, FOV, zNear, zFar);
  73. initFrustumPlanes(FOV, aspectRatio, zNear, zFar);
  74. globalLight.direction.x = 0;
  75. globalLight.direction.y = 0;
  76. globalLight.direction.z = 1;
  77. vec3Normalize(&globalLight.direction);
  78. /* Load texture */
  79. //meshTexture = (colour_t *)REDBRICK_TEXTURE;
  80. loadTextureDateFromPng("assets/cube.png");
  81. /* Load object */
  82. loadOBJFile("assets/cube.obj");
  83. //loadCubeMeshData();
  84. trianglesTotal = arrayGetSize(mesh.faces);
  85. exit:
  86. return;
  87. }
  88. void processInput()
  89. {
  90. SDL_Event event;
  91. SDL_PollEvent(&event);
  92. switch (event.type)
  93. {
  94. case SDL_QUIT:isRunning = false;
  95. break;
  96. case SDL_KEYDOWN:
  97. switch(event.key.keysym.sym)
  98. {
  99. case SDLK_ESCAPE:
  100. isRunning = false;
  101. break;
  102. case SDLK_1:
  103. displayVertex = true;
  104. currentDisplayMode = DISPLAY_MODE_WIREFRAME;
  105. break;
  106. case SDLK_2:
  107. displayVertex = false;
  108. currentDisplayMode = DISPLAY_MODE_WIREFRAME;
  109. break;
  110. case SDLK_3:
  111. displayVertex = false;
  112. currentDisplayMode = DISPLAY_MODE_SOLID;
  113. break;
  114. case SDLK_4:
  115. displayVertex = false;
  116. currentDisplayMode = DISPLAY_MODE_SOLID_WIRE;
  117. break;
  118. case SDLK_5:
  119. displayVertex = false;
  120. currentDisplayMode = DISPLAY_MODE_TEXTURED;
  121. break;
  122. case SDLK_6:
  123. displayVertex = false;
  124. currentDisplayMode = DISPLAY_MODE_TEXTURED_WIRE;
  125. break;
  126. case SDLK_u:
  127. doNotCull = false;
  128. break;
  129. case SDLK_j:
  130. doNotCull = true;
  131. break;
  132. case SDLK_i:
  133. doPerpectiveCorrection = false;
  134. break;
  135. case SDLK_k:
  136. doPerpectiveCorrection = true;
  137. break;
  138. case SDLK_o:
  139. doZBuffer = true;
  140. break;
  141. case SDLK_l:
  142. doZBuffer = false;
  143. break;
  144. case SDLK_y:
  145. doClipping = true;
  146. break;
  147. case SDLK_h:
  148. doClipping = false;
  149. break;
  150. case SDLK_w:
  151. camera.forwardVelocity = vec3ScalarMult(camera.direction, 5 * deltaTime);
  152. camera.position = vec3AddVectors(camera.position, camera.forwardVelocity);
  153. break;
  154. case SDLK_d:
  155. camera.yawAngle += 1.0 * deltaTime;
  156. break;
  157. case SDLK_s:
  158. camera.forwardVelocity = vec3ScalarMult(camera.direction, 5 * deltaTime);
  159. camera.position = vec3SubVectors(camera.position, camera.forwardVelocity);
  160. break;
  161. case SDLK_a:
  162. camera.yawAngle -= 1.0 * deltaTime;
  163. break;
  164. case SDLK_UP:
  165. camera.position.y += 3.0 * deltaTime;
  166. break;
  167. case SDLK_DOWN:
  168. camera.position.y -= 3.0 * deltaTime;
  169. break;
  170. }
  171. break;
  172. default:
  173. break;
  174. }
  175. }
  176. uint32_t getMicroSecTime()
  177. {
  178. struct timeval curTime;
  179. gettimeofday(&curTime, NULL);
  180. return ((curTime.tv_sec) * 1000 * 1000) + (curTime.tv_usec);
  181. }
  182. static void projectTriangle(triangle_t *baseTriangle, triangle_t *workTriangle, vec3_t *triangleNormal, colour_t colour)
  183. {
  184. int j;
  185. struct triangle_t currentTriangle = *baseTriangle;
  186. for (j = 0 ; j < 3 ; j++)
  187. {
  188. vec4_t projected = mat4ProdVec4Project(projectionMatrix, workTriangle->points[j]);
  189. projected.x *= windowWidth / 2.;
  190. projected.y *= windowHeight / 2.;
  191. /* Screen Y axis increase down, 3D world Y grows up, so we need to invert. */
  192. projected.y *= -1.0;
  193. projected.x += (windowWidth / 2.);
  194. projected.y += (windowHeight / 2.);
  195. currentTriangle.points[j].x = projected.x;
  196. currentTriangle.points[j].y = projected.y;
  197. currentTriangle.points[j].w = projected.w;
  198. currentTriangle.points[j].z = projected.z;
  199. }
  200. if (doNotCull)
  201. {
  202. currentTriangle.colour = colour;
  203. }
  204. else
  205. {
  206. double lightLevel = -vec3Dot(*triangleNormal, globalLight.direction);
  207. currentTriangle.colour = applyLight(colour, lightLevel);
  208. }
  209. currentTriangle.averageDepth = (workTriangle->points[0].z +
  210. workTriangle->points[1].z +
  211. workTriangle->points[2].z) / 3.0;
  212. currentTriangle.texture = meshTexture;
  213. arrayAdd(projectedTriangles, currentTriangle);
  214. }
  215. void update()
  216. {
  217. uint32_t i, j;
  218. uint32_t faceCount;
  219. uint32_t numberOfClippedTriangles;
  220. uint32_t timeToWait = FRAME_TARGET_TIME - (SDL_GetTicks() - previousFrameTime);
  221. matrix4_t worldMatrix;
  222. uint32_t ticks = getMicroSecTime();
  223. triangle_t trianglesAfterClipping[MAX_NUM_POLYGON_TRIANGLES];
  224. if (timeToWait <= FRAME_TARGET_TIME)
  225. {
  226. SDL_Delay(timeToWait);
  227. }
  228. deltaTime = (SDL_GetTicks() - previousFrameTime) / 1000.0;
  229. previousFrameTime = SDL_GetTicks();
  230. waitTime = (waitTime + (getMicroSecTime() - ticks) / 1000.) / 2.0;
  231. ticks = getMicroSecTime();
  232. mesh.translation.z = 5;
  233. vec3_t upDirection = { 0, 1, 0 };
  234. vec3_t lookAtTarget = { 0, 0, 1 };
  235. camera.direction = vec3FromVec4(mat4ProdVec4(mat4RotationY(camera.yawAngle), vec4FromVec3(lookAtTarget)));
  236. lookAtTarget = vec3AddVectors(camera.position, camera.direction);
  237. viewMatrix = mat4LookAt(camera.position, lookAtTarget, upDirection);
  238. worldMatrix = mat4Identity;
  239. worldMatrix = mat4ProdMat4(mat4Scale(mesh.scale.x, mesh.scale.y, mesh.scale.z), worldMatrix);
  240. worldMatrix = mat4ProdMat4(mat4RotationZ(mesh.rotation.z), worldMatrix);
  241. worldMatrix = mat4ProdMat4(mat4RotationY(mesh.rotation.y), worldMatrix);
  242. worldMatrix = mat4ProdMat4(mat4RotationX(mesh.rotation.x), worldMatrix);
  243. worldMatrix = mat4ProdMat4(mat4Translate(mesh.translation.x, mesh.translation.y, mesh.translation.z), worldMatrix);
  244. /* Not sure for now */
  245. worldMatrix = mat4ProdMat4(viewMatrix, worldMatrix);
  246. arrayEmpty(projectedTriangles);
  247. faceCount = arrayGetSize(mesh.faces);
  248. for(i = 0; i < faceCount; i++)
  249. {
  250. polygon_t polygon;
  251. triangle_t baseTriangle =
  252. {
  253. .textureCoordinates =
  254. {
  255. [0] = { mesh.faces[i].a_uv.u, mesh.faces[i].a_uv.v },
  256. [1] = { mesh.faces[i].b_uv.u, mesh.faces[i].b_uv.v },
  257. [2] = { mesh.faces[i].c_uv.u, mesh.faces[i].c_uv.v }
  258. }
  259. };
  260. vec4_t transformedVertices[3];
  261. vec3_t triangleNormal;
  262. vec3_t vertices[3] =
  263. {
  264. mesh.vertices[mesh.faces[i].a],
  265. mesh.vertices[mesh.faces[i].b],
  266. mesh.vertices[mesh.faces[i].c],
  267. };
  268. for(j = 0; j < 3; j++)
  269. {
  270. transformedVertices[j] = vec4FromVec3(vertices[j]);
  271. transformedVertices[j] = mat4ProdVec4(worldMatrix, transformedVertices[j]);
  272. //transformedVertices[j] = mat4ProdVec4(viewMatrix, transformedVertices[j]);
  273. }
  274. vec3_t vectorBA = vec3SubVectors(vec3FromVec4(transformedVertices[1]), vec3FromVec4(transformedVertices[0]));
  275. vec3_t vectorCA = vec3SubVectors(vec3FromVec4(transformedVertices[2]), vec3FromVec4(transformedVertices[0]));
  276. vec3Normalize(&vectorBA);
  277. vec3Normalize(&vectorCA);
  278. triangleNormal = vec3Cross(vectorBA, vectorCA);
  279. vec3Normalize(&triangleNormal);
  280. if (!doNotCull)
  281. {
  282. vec3_t cameraRay = vec3SubVectors(origin, vec3FromVec4(transformedVertices[0]));
  283. vec3Normalize(&cameraRay);
  284. double cameraDotTriangle = vec3Dot(triangleNormal, cameraRay);
  285. if (cameraDotTriangle < 0)
  286. {
  287. continue;
  288. }
  289. }
  290. if (doClipping)
  291. {
  292. polygon = createPolygonFromTriangle(vec3FromVec4(transformedVertices[0]),
  293. vec3FromVec4(transformedVertices[1]),
  294. vec3FromVec4(transformedVertices[2]));
  295. clipPolygon(&polygon);
  296. createTriangleFromPolygon(&polygon, trianglesAfterClipping, &numberOfClippedTriangles);
  297. for(j = 0; j < numberOfClippedTriangles; j++)
  298. {
  299. projectTriangle(&baseTriangle, &trianglesAfterClipping[j], &triangleNormal, mesh.faces[i].colour);
  300. }
  301. }
  302. else
  303. {
  304. triangle_t workTriangle =
  305. {
  306. .points =
  307. {
  308. [0] = transformedVertices[0],
  309. [1] = transformedVertices[1],
  310. [2] = transformedVertices[2]
  311. }
  312. };
  313. projectTriangle(&baseTriangle, &workTriangle, &triangleNormal, mesh.faces[i].colour);
  314. };
  315. }
  316. if (!doZBuffer)
  317. {
  318. trianglesCount = arrayGetSize(projectedTriangles);
  319. qsort(projectedTriangles, trianglesCount, sizeof(triangle_t), compareTrianglesZOrder);
  320. }
  321. updateTime = (updateTime + (getMicroSecTime() - ticks) / 1000.) / 2.0;
  322. }
  323. void render()
  324. {
  325. int i;
  326. uint32_t ticks = getMicroSecTime();
  327. SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
  328. SDL_RenderClear(renderer);
  329. int triangleCount = arrayGetSize(projectedTriangles);
  330. for(i = 0; i < triangleCount; i++)
  331. {
  332. switch(currentDisplayMode)
  333. {
  334. case DISPLAY_MODE_SOLID:
  335. case DISPLAY_MODE_SOLID_WIRE:
  336. drawFilledTriangle(&projectedTriangles[i]);
  337. break;
  338. case DISPLAY_MODE_TEXTURED:
  339. case DISPLAY_MODE_TEXTURED_WIRE:
  340. drawTextureTriangle(&projectedTriangles[i]);
  341. break;
  342. default:
  343. break;
  344. }
  345. switch (currentDisplayMode)
  346. {
  347. case DISPLAY_MODE_SOLID_WIRE:
  348. case DISPLAY_MODE_TEXTURED_WIRE:
  349. case DISPLAY_MODE_WIREFRAME:
  350. drawTriangle(projectedTriangles[i].points[0].x, projectedTriangles[i].points[0].y,
  351. projectedTriangles[i].points[1].x, projectedTriangles[i].points[1].y,
  352. projectedTriangles[i].points[2].x, projectedTriangles[i].points[2].y,
  353. projectedTriangles[i].colour);
  354. break;
  355. default:
  356. break;
  357. }
  358. if (displayVertex)
  359. {
  360. int j;
  361. for(j = 0; j < 3; j++)
  362. {
  363. drawRectangle(projectedTriangles[i].points[j].x - 1,
  364. projectedTriangles[i].points[j].y - 1,
  365. 3, 3,
  366. MAKE_RGB(255, 0, 0));
  367. }
  368. }
  369. }
  370. renderFrameBuffer();
  371. clearFrameBuffer(MAKE_RGB(0, 0, 0));
  372. clearZBuffer();
  373. renderTime = (renderTime + (getMicroSecTime() - ticks) / 1000.) / 2.0;
  374. drawText(5, 5, 0x11FF22, "Wait time: %02.2f ms", waitTime);
  375. drawText(5, 17, 0x11FF22, "Update time: %02.2f ms", updateTime);
  376. drawText(5, 29, 0x11FF22, "Render time: %02.2f ms", renderTime);
  377. drawText(5, 41, 0x11FF22, "FPS: %.1f | dT: %.3f", 1000 / (waitTime + updateTime + renderTime), deltaTime);
  378. drawText(5, 53, 0x11FF22, "Triangles: %d / %d", triangleCount, trianglesTotal);
  379. drawText(5, 65, 0x11FF22, "Cull: %c | PeCo: %c | ZB: %c, | CP: %c",
  380. doNotCull?'N':'Y', doPerpectiveCorrection?'Y':'N', doZBuffer?'Y':'N', doClipping?'Y':'N');
  381. SDL_RenderPresent(renderer);
  382. }
  383. int main(int argc, char *argv[])
  384. {
  385. int param_i;
  386. bool fullScreen = false;
  387. MAX_DEBUG_LEVEL = TLOG_DEBUG;
  388. Log(TLOG_ALWAYS, NULL, "Booting 3D Engine (version %s)!", VERSION);
  389. for (param_i = 1 ; (param_i < argc) && (argv[param_i][0] == '-') ; param_i++)
  390. {
  391. switch (argv[param_i][1])
  392. {
  393. default: exit(-1); /* Option not recognized */
  394. case 'f': fullScreen = true; break;
  395. case 'w': windowWidth = atoi(argv[++param_i]);
  396. case 'h': windowHeight = atoi(argv[++param_i]); break;
  397. #ifdef DYNA_LOG_LEVEL
  398. case 'l': MAX_DEBUG_LEVEL = atoi(argv[++param_i]); break;
  399. #endif
  400. case '-': goto no_more_params; /* Could use break, but this is more clear */
  401. }
  402. }
  403. no_more_params:
  404. isRunning = initialiseWindow(fullScreen);
  405. setup();
  406. while (isRunning)
  407. {
  408. processInput();
  409. update();
  410. render();
  411. }
  412. arrayFree(projectedTriangles);
  413. textureCleanup();
  414. meshFree();
  415. destroyWindow();
  416. return 0;
  417. }