Skip to content
doubtly

1 answer

Best answer

Answer: DDA (Digital Differential Analyzer) takes steps = max(|dx|, |dy|), increments x by dx/steps and y by dy/steps at each step, and plots the rounded point.

Algorithm

  1. Read end points \((x_a, y_a)\) and \((x_b, y_b)\); \(dx = x_b - x_a\), \(dy = y_b - y_a\).
  2. steps = |dx| if |dx| > |dy|, else |dy|.
  3. \(x_{inc} = dx/steps\), \(y_{inc} = dy/steps\).
  4. Start at \((x_a, y_a)\), plot it; repeat steps times: x = x + x_inc, y = y + y_inc, plot (round(x), round(y)).

Program (Turbo C)

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <graphics.h>

#define ROUND(a) ((int)((a) + 0.5))

void lineDDA(int xa, int ya, int xb, int yb)
{
    int dx = xb - xa, dy = yb - ya, steps, k;
    float xInc, yInc, x = xa, y = ya;

    if (abs(dx) > abs(dy))
        steps = abs(dx);
    else
        steps = abs(dy);

    if (steps == 0) {                 /* both end points are the same */
        putpixel(xa, ya, RED);
        return;
    }

    xInc = dx / (float)steps;
    yInc = dy / (float)steps;

    putpixel(ROUND(x), ROUND(y), RED);
    for (k = 0; k < steps; k++) {
        x += xInc;
        y += yInc;
        putpixel(ROUND(x), ROUND(y), RED);
    }
}

int main()
{
    int xa, ya, xb, yb;
    int gd = DETECT, gm, gerr;

    printf("Enter the two end points (xa ya xb yb): ");
    scanf("%d %d %d %d", &xa, &ya, &xb, &yb);

    initgraph(&gd, &gm, "C:\\TC\\BGI");
    gerr = graphresult();
    if (gerr != grOk) {
        printf("Graphics error: %s\n", grapherrormsg(gerr));
        getch();
        return 1;
    }

    lineDDA(xa, ya, xb, yb);
    getch();
    closegraph();
    return 0;
}

Sample run for the line (2, 3) to (10, 8): dx = 8, dy = 5, steps = 8, x_inc = 1, y_inc = 0.625. Pixels plotted:

(2,3) (3,4) (4,4) (5,5) (6,6) (7,6) (8,7) (9,7) (10,8)

Note: graphics.h is the Turbo C / BGI library (Turbo C++ or DOSBox; on Linux use the libgraph package). The program was compile-checked with gcc against a small stand-in graphics.h that prints each plotted pixel instead of drawing it, which is how the pixel list above was produced.

Points to note: DDA is simple but uses floating-point addition and rounding at every step, so it is slower than Bresenham, and round-off error can build up on long lines.

Doubtly · 30 Apr 2023 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.