Tuesday, December 26, 2017

DDA Algorithm

The Digital Differential Algorithm (DDA) is a scan-conversion line drawing algorithm. A line is sampled at unit intervals in one coordinate and the corresponding integer values nearest the line path are determined for the other coordinate.

Algorithm

 1. Get the end points (x1, y1) and (x2, y2) of a line.
 2. Set x = x1, y = y1.
 3. Plot (x, y).
 4. Compute dx = x2-x1 and dy = y2-y1.
 5. If |dy| < |dx|
       steps = |dx|
    else
       steps = |dy|
 6. Compute delX = dx/steps
            delY = dy/steps
 7. Repeat following for <strong>steps</strong> times
       a. x = x + delX
       b. y = y + delY
       c. Plot (x, y) 

This program takes x-coordinate and y-coordinate of endpoints of line to be drawn. Also color of the line is passed.

     // DDA(Digital Differential Analyzer) Algorithm...
    #include <iostream>
    #include <conio.h>
    #include <graphics.h>
    #include <cmath>
    #define R(z) int(z+0.5)   // Macro to round floating numbers to integer

    using namespace std;

    void lineDDA(int x1, int y1, int x2, int y2, int col)
    {
        float x,y,delX,delY;
        int steps, dx, dy, k;

        x=x1;
        y=y1;
        putpixel(x, y, col);

        dx = x2-x1;
        dy = y2-y1;

        if(abs(dy)<abs(dx))
            steps = abs(dx);
        else
            steps = abs(dy);
        delX = (float)dx/steps;
        delY = (float)dy/steps;
        for(k=0; k<steps; k++)
        {
            x = x+delX;
            y = y+delY;
            putpixel(R(x), R(y), col);
        }
    }


    int main()
    {
        int gd = DETECT, gm;
        initgraph(&gd, &gm, "C:\\tc\\BGI");
        int x=getmaxx(), y=getmaxy();
        cout<<x<<y;
        lineDDA(0, 0, 630, 466, 1);
        lineDDA(0, 466, 630, 0, 2);
        lineDDA(630/2, 0, 630/2, 466, 3);
        lineDDA(0, 466/2, 630, 466/2, 4);

        getch();
        return 0;
    }

     

        Output:

       
          

1 comment:

Addition of two Binary numbers using C

Addition of two Binary numbers using C  The operation of adding two binary numbers is one of the fundamental tasks performed by a digita...