/* DDA line drawing - SDL2 version (modern replacement for graphics.h). * Draws into an off-screen 64x40 pixel surface (each cell shown 10x10) and saves dda.bmp, * so it also runs on a machine with no display (SDL_VIDEODRIVER=dummy). * Build: gcc -std=c11 -Wall -Wextra -o dda_sdl src/dda_sdl.c $(sdl2-config --cflags --libs) -lm * Run: ./dda_sdl x1 y1 x2 y2 [out.bmp] (default 2 3 10 8 dda.bmp) * add --window to open a real window and wait for a key/close instead of saving. */ #include #include #include #include #include #define GW 64 #define GH 40 #define CELL 10 static void cell(SDL_Surface *s, int px, int py, Uint32 col) { SDL_Rect r = { px * CELL, py * CELL, CELL - 1, CELL - 1 }; SDL_FillRect(s, &r, col); } int main(int argc, char **argv) { int window = 0; int a[4] = { 2, 3, 10, 8 }; const char *out = "dda.bmp"; int n = 0; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "--window")) window = 1; else if (n < 4) a[n++] = atoi(argv[i]); else out = argv[i]; } int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3]; if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "SDL_Init: %s\n", SDL_GetError()); return 1; } SDL_Surface *s = SDL_CreateRGBSurfaceWithFormat(0, GW * CELL, GH * CELL, 32, SDL_PIXELFORMAT_RGBA32); if (!s) { fprintf(stderr, "surface: %s\n", SDL_GetError()); return 1; } SDL_FillRect(s, NULL, SDL_MapRGB(s->format, 255, 255, 255)); Uint32 grid = SDL_MapRGB(s->format, 235, 238, 243); Uint32 ink = SDL_MapRGB(s->format, 74, 124, 199); for (int gy = 0; gy < GH; gy++) for (int gx = 0; gx < GW; gx++) cell(s, gx, gy, grid); int dx = x2 - x1, dy = y2 - y1; int steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy); if (steps == 0) steps = 1; float xinc = (float)dx / steps, yinc = (float)dy / steps; float x = (float)x1, y = (float)y1; int plotted = 0; for (int i = 0; i <= steps; i++) { int px = (int)lroundf(x), py = (int)lroundf(y); if (px >= 0 && px < GW && py >= 0 && py < GH) { cell(s, px, py, ink); plotted++; } x += xinc; y += yinc; } printf("DDA (%d,%d)->(%d,%d): steps=%d, pixels plotted=%d\n", x1, y1, x2, y2, steps, plotted); if (!window) { if (SDL_SaveBMP(s, out) != 0) { fprintf(stderr, "save: %s\n", SDL_GetError()); return 1; } printf("saved %s (%dx%d)\n", out, s->w, s->h); } else { SDL_Window *w = SDL_CreateWindow("DDA", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, s->w, s->h, 0); SDL_Surface *ws = SDL_GetWindowSurface(w); SDL_BlitSurface(s, NULL, ws, NULL); SDL_UpdateWindowSurface(w); SDL_Event e; while (SDL_WaitEvent(&e) && e.type != SDL_QUIT && e.type != SDL_KEYDOWN) {} SDL_DestroyWindow(w); } SDL_FreeSurface(s); SDL_Quit(); return 0; }