123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- /*
- * 3D Engine
- * triangle.c:
- * Based on pikuma.com 3D software renderer in C
- * Copyright (c) 2021 986-Studio. All rights reserved.
- *
- * Created by Manoël Trapier on 04/03/2021.
- */
- #include <display.h>
- #include <triangle.h>
- void drawTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t colour)
- {
- drawLine(x0, y0, x1, y1, colour);
- drawLine(x1, y1, x2, y2, colour);
- drawLine(x2, y2, x0, y0, colour);
- }
- /* This function expect Point 0 to be the top, 1 to be the bottom left, 2 to be the bottom right */
- static void drawFillBottomFlatTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t colour)
- {
- int i;
- int32_t deltaXL = x1 - x0;
- int32_t deltaXR = x2 - x0;
- int32_t deltaY = y1 - y0;
- int32_t sideLength = abs(deltaY);
- double incrementXL = deltaXL / (double)sideLength;
- double incrementXR = deltaXR / (double)sideLength;
- double incrementY = deltaY / (double)sideLength;
- double currentXL = x0;
- double currentXR = x0;
- double currentY = y0;
- for(i = 0; i < sideLength; i++)
- {
- drawHLine(round(currentXL), round(currentY), round(currentXR), colour);
- currentXL += incrementXL;
- currentXR += incrementXR;
- currentY += incrementY;
- }
- }
- /* This function expect Point 2 to be the bottom, 0 to be the top left, 1 to be the top right */
- static void drawFillTopFlatTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t colour)
- {
- int i;
- int32_t deltaXL = x0 - x2;
- int32_t deltaXR = x1 - x2;
- int32_t deltaY = y0 - y2;
- int32_t sideLength = abs(deltaY);
- if (sideLength == 0)
- {
- return;
- }
- double incrementXL = deltaXL / (double)sideLength;
- double incrementXR = deltaXR / (double)sideLength;
- double incrementY = deltaY / (double)sideLength;
- double currentXL = x2;
- double currentXR = x2;
- double currentY = y2;
- for(i = 0; i <= sideLength; i++)
- {
- drawHLine(round(currentXL), round(currentY), round(currentXR), colour);
- currentXL += incrementXL;
- currentXR += incrementXR;
- currentY += incrementY;
- }
- }
- void drawFilledTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t x2, int32_t y2, uint32_t colour)
- {
- int32_t My, Mx;
- if (y0 > y1)
- {
- intSwap(&x0, &x1); intSwap(&y0, &y1);
- }
- if (y1 > y2)
- {
- intSwap(&x1, &x2); intSwap(&y1, &y2);
- }
- if (y0 > y1)
- {
- intSwap(&x0, &x1); intSwap(&y0, &y1);
- }
- /* Determine the mid intersection and point */
- My = y1;
- Mx = x0 + (double)((x2 - x0) * (y1 - y0)) / (double)(y2 - y0);
- /* Fill top */
- drawFillBottomFlatTriangle(x0, y0, x1, y1, Mx, My,colour);
- /* Fill bottom */
- drawFillTopFlatTriangle(x1, y1, Mx, My, x2, y2, colour);
- }
|