#pragma once #include #include #include "../datatypes.cpp" #include "../helpers.cpp" #include "../buffer.cpp" #include "../mappers/mappers.h" #include "../textures/textures.h" namespace UwU { class Triangle { private: public: Triangle(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2) { this->x0 = x0; this->y0 = y0; this->x1 = x1; this->y1 = y1; this->x2 = x2; this->y2 = y2; } Triangle() {} uint16_t x0; uint16_t y0; uint16_t x1; uint16_t y1; uint16_t x2; uint16_t y2; // Draw a triangle template void draw (Buffer buffer, MapperBase& mapper, TextureBase& texture) { uint16_t topX, topY, midX, midY, btmX, btmY; // Find top, middle and bottom points of triangle if (y0 <= y1 && y0 <= y2) { topX = x0; topY = y0; if (y1 < y2) { midX = x1; midY = y1; btmX = x2; btmY = y2; } else { midX = x2; midY = y2; btmX = x1; btmY = y1; } } else if (y1 <= y0 && y1 <= y2) { topX = x1; topY = y1; if (y0 < y2) { midX = x0; midY = y0; btmX = x2; btmY = y2; } else { midX = x2; midY = y2; btmX = x0; btmY = y0; } } else { topX = x2; topY = y2; if (y0 < y1) { midY = y0; midX = x0; btmX = x1; btmY = y1; } else { midX = x1; midY = y1; btmX = x0; btmY = y0; } } uint16_t height = 1 + btmY - topY; int16_t longBound[height]; int16_t splitBound[height]; // Calculate LUT for longest vertical line (from top to bottom) Helpers::bresenham(0, topX, height - 1, btmX, longBound); // Calculate LUT for short two lines Helpers::bresenham(0, topX, midY - topY, midX, splitBound); Helpers::bresenham(midY - topY, midX, height - 1, btmX, splitBound); Coord2 uv; uint16_t leftX = std::min(topX, std::min(midX, btmX)); // Left-handed triangle case (midpoint is left of triangle) if ((int16_t)midX < longBound[midY - topY]) { for (uint16_t i = 0; i < height; i++) { for (uint16_t x = (uint16_t)splitBound[i]; x <= (uint16_t)longBound[i]; x++) { uv = mapper.map(leftX, topY, x, i + (uint16_t)topY); buffer.drawPixel(x, i + (uint16_t)topY, texture.texel(uv.x, uv.y)); } } // Right-handed triangle case (midpoint is right of triangle) } else { for (uint16_t i = 0; i < height; i++) { for (uint16_t x = (uint16_t)longBound[i]; x <= (uint16_t)splitBound[i]; x++) { uv = mapper.map(leftX, topY, x, i + (uint16_t)topY); buffer.drawPixel(x, i + (uint16_t)topY, texture.texel(uv.x, uv.y)); } } } return; } }; }