Implement simple line drawing

This commit is contained in:
2025-10-18 17:43:22 +01:00
parent fad9a8935f
commit 0deaf4435c
6 changed files with 98 additions and 16 deletions

View File

@@ -4,10 +4,14 @@
#include <assert.h>
#include <fcntl.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <xf86drm.h>
#define MAX_VERTS_PER_DRAW 8U
static int drm_fd;
static drmModeConnector *conn;
static drmModeCrtc *crtc;
@@ -17,18 +21,35 @@ static fb_info_t fbs[2];
static int front, back;
static uint32_t width, height;
static mat3_t view;
static vec3_t vert_buf[MAX_VERTS_PER_DRAW];
static void page_flip_handler(int, unsigned, unsigned, unsigned, void *)
{
}
static void
set_pixel(uint32_t x, uint32_t y, uint8_t r, uint8_t g, uint8_t b)
static void set_pixel(uint32_t x, uint32_t y)
{
/* x %= width; */
/* y %= height; */
x %= width;
y %= height;
const uint32_t offset = y * (fbs[back].pitch / 4) + x;
assert(offset < fbs[back].size);
fbs[back].buf[offset] = (r << 16) | (g << 8) | b;
fbs[back].buf[offset] = 0xff'ff'ff;
}
static void draw_line(vec3_t v1, vec3_t v2)
{
const float delta_x = v2.x - v1.x;
const float delta_y = v2.y - v1.y;
const float step = fmaxf(fabsf(delta_x), fabsf(delta_y));
if (step != 0.0) {
const float step_x = delta_x / step;
const float step_y = delta_y / step;
for (unsigned i = 0; i <= step; ++i)
set_pixel(roundf(v1.x + i * step_x), roundf(v1.y + i * step_y));
} else {
set_pixel(roundf(v1.x), roundf(v1.y));
}
}
renderer_params_t renderer_init()
@@ -59,9 +80,17 @@ renderer_params_t renderer_init()
width = mode.hdisplay;
height = mode.vdisplay;
const float aspect = (float)width / (float)height;
const float scale = (float)height / 2.0f;
view = (mat3_t) {
{ scale, 0, 0 },
{ 0, -scale, 0 },
{ aspect * scale, scale, 1 },
};
return (renderer_params_t) {
.drm_fd = drm_fd,
.aspect = (float)mode.hdisplay / (float)mode.vdisplay,
.aspect = aspect,
};
}
@@ -103,10 +132,12 @@ void renderer_swap()
back = (back + 1) & 1;
}
void renderer_draw()
void renderer_draw(const vec2_t *vs, unsigned count)
{
for (unsigned y = 0; y < height; ++y) {
for (unsigned x = 0; x < width; ++x)
set_pixel(x, y, (x * 255) / width, (y * 255) / height, 128);
}
assert(count < MAX_VERTS_PER_DRAW);
for (unsigned i = 0; i < count; ++i)
vert_buf[i] = mat3_mul_vec3(view, vec2_extend(vs[i]));
for (unsigned i = 1; i < count; ++i)
draw_line(vert_buf[i - 1], vert_buf[i]);
draw_line(vert_buf[count - 1], vert_buf[0]);
}