triangle.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * 3D Engine
  3. * triangle.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 04/03/2021.
  8. */
  9. #include <display.h>
  10. #include <triangle.h>
  11. void drawTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t colour)
  12. {
  13. drawLine(x0, y0, x1, y1, colour);
  14. drawLine(x1, y1, x2, y2, colour);
  15. drawLine(x2, y2, x0, y0, colour);
  16. }
  17. /* This function expect Point 0 to be the top, 1 to be the bottom left, 2 to be the bottom right */
  18. static void drawFillBottomFlatTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t colour)
  19. {
  20. int i;
  21. int32_t deltaXL = x1 - x0;
  22. int32_t deltaXR = x2 - x0;
  23. int32_t deltaY = y1 - y0;
  24. int32_t sideLength = abs(deltaY);
  25. double incrementXL = deltaXL / (double)sideLength;
  26. double incrementXR = deltaXR / (double)sideLength;
  27. double incrementY = deltaY / (double)sideLength;
  28. double currentXL = x0;
  29. double currentXR = x0;
  30. double currentY = y0;
  31. for(i = 0; i < sideLength; i++)
  32. {
  33. drawHLine(round(currentXL), round(currentY), round(currentXR), colour);
  34. currentXL += incrementXL;
  35. currentXR += incrementXR;
  36. currentY += incrementY;
  37. }
  38. }
  39. static void drawFillTopFlatTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t colour)
  40. {
  41. }
  42. void drawFilledTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t colour)
  43. {
  44. int32_t My, Mx;
  45. if (y0 > y1)
  46. {
  47. intSwap(&x0, &x1); intSwap(&y0, &y1);
  48. }
  49. if (y1 > y2)
  50. {
  51. intSwap(&x1, &x2); intSwap(&y1, &y2);
  52. }
  53. if (y0 > y1)
  54. {
  55. intSwap(&x0, &x1); intSwap(&y0, &y1);
  56. }
  57. /* Determine the mid intersection and point */
  58. My = y1;
  59. Mx = x0 + (double)((x2 - x0) * (y1 - y0)) / (double)(y2 - y0);
  60. /* Fill top */
  61. drawFillBottomFlatTriangle(x0, y0, x1, y1, Mx, My,colour);
  62. /* Fill bottom */
  63. drawFillTopFlatTriangle(x1, y1, Mx, My, x2, y2, colour);
  64. }