0% found this document useful (0 votes)
4 views

DDA Line SDL2 Program

The document provides a C program using the SDL2 library to implement both the Digital Differential Analyzer (DDA) and Bresenham's line drawing algorithms. It explains the setup of the SDL2 environment, the key concepts of each algorithm, and the differences between them, highlighting that Bresenham's algorithm is generally more efficient due to its use of integer arithmetic. Additionally, it outlines how to compile and run the program, along with the main flow of execution and event handling.

Uploaded by

acsample0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

DDA Line SDL2 Program

The document provides a C program using the SDL2 library to implement both the Digital Differential Analyzer (DDA) and Bresenham's line drawing algorithms. It explains the setup of the SDL2 environment, the key concepts of each algorithm, and the differences between them, highlighting that Bresenham's algorithm is generally more efficient due to its use of integer arithmetic. Additionally, it outlines how to compile and run the program, along with the main flow of execution and event handling.

Uploaded by

acsample0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

DDA Line SDL2 Program

create a program using sdl2 library in c of tracing line dda

Here's a C program using the SDL2 library to implement the Digital Differential Analyzer (DDA) algorithm
for line drawing.

Sdl2 Dda Line

Explanation:

1. Initializes SDL2 and creates a window.


2. Uses a renderer to draw a line using the DDA algorithm.
3. The algorithm calculates the number of steps needed to interpolate between two points.
4. Uses floating-point increments to smoothly transition from one point to another.
5. Keeps the window open until the user closes it.

Compilation:

Make sure you have SDL2 installed, then compile with:

sh

gcc -o dda_line dda_line.c -lSDL2

Run it with:

sh

./dda_line

Let me know if you need modifications! 🚀

explain me also each term

Sure! Let's break down the important terms used in the SDL2 DDA Line Drawing program.

1. SDL2 (Simple DirectMedia Layer)

SDL2 is a cross-platform library used for handling graphics, input, and audio in applications like games
or simulations. In this program, we use SDL2 to create a window and render graphics.

2. Window & Renderer


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/19
SDL_Window: Represents a window where graphics will be drawn.
SDL_Renderer: Used to render (draw) graphics inside the window.

3. DDA Algorithm (Digital Differential Analyzer)

DDA is a line-drawing algorithm that interpolates between two points by:

1. Calculating the difference in x (`dx`) and y (`dy`).


2. Determining the number of steps required (based on the greater absolute difference of `dx` or
`dy`).
3. Incrementing x and y in small steps to ensure a smooth transition from `x1, y1` to `x2, y2`.

4. Key Variables & Functions

Inside `drawLineDDA` function

`dx = x2 - x1;` → Calculates horizontal distance.


`dy = y2 - y1;` → Calculates vertical distance.
`steps = (abs(dx) > abs(dy)) ? abs(dx) : abs(dy);` → Determines the number of steps.
`xIncrement = dx / (float) steps;` → Determines how much to increase `x` per step.
`yIncrement = dy / (float) steps;` → Determines how much to increase `y` per step.
Loop to draw points: Moves pixel-by-pixel (`round(x), round(y)`) along the calculated increments.

SDL Functions Used

`SDL_Init(SDL_INIT_VIDEO);` → Initializes SDL2 for graphics.


`SDL_CreateWindow(...);` → Creates a window.
`SDL_CreateRenderer(...);` → Creates a rendering surface.
`SDL_SetRenderDrawColor(renderer, r, g, b, a);` → Sets drawing color (White for the line).
`SDL_RenderDrawPoint(renderer, x, y);` → Draws a pixel.
`SDL_RenderPresent(renderer);` → Displays the rendered graphics.
`SDL_PollEvent(&e);` → Checks for user events (like closing the window).
`SDL_Quit();` → Cleans up SDL resources.

5. Main Program Flow

1. Initialize SDL2
2. Create a window & renderer
3. Clear screen with black background
4. Use DDA to draw a white line
5. Display the result
6. Wait for user to close the window
7. Clean up and exit

6. How the DDA Algorithm Works (Example Calculation)

If we want to draw a line from (100,100) to (700,500):

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/19
1. `dx = 700 - 100 = 600`
2. `dy = 500 - 100 = 400`
3. `steps = max(600, 400) = 600`
4. `xIncrement = 600 / 600 = 1`
5. `yIncrement = 400 / 600 = 0.666`
6. Start at (100,100), increment step-by-step:
(101, 100.67) → (102, 101.33) → (103, 102) ... until (700, 500).

This smooth interpolation avoids gaps or jagged edges.

7. How to Compile & Run

Compile:

sh

gcc -o dda_line dda_line.c -lSDL2

Run:

sh

./dda_line

Final Thoughts

DDA is simple and efficient, but Bresenham’s Algorithm is often preferred for better
performance on integer-based systems.
SDL2 makes it easy to handle graphics without needing complex OpenGL or DirectX.
You can modify this program to allow user input for dynamic line drawing.

Would you like me to add interactive features, like drawing lines using mouse clicks? 🚀

using breshanman

Sdl2 Dda Line

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/19
#include <SDL2/SDL.h>
#include <stdio.h>
#include <math.h>

#define SCREEN_WIDTH 800


#define SCREEN_HEIGHT 600

void drawLineBresenham(SDL_Renderer *renderer, int x1, int y1, int x2, int y2) {
int dx = abs(x2 - x1);
int dy = abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy;

while (1) {
SDL_RenderDrawPoint(renderer, x1, y1);
if (x1 == x2 && y1 == y2) break;
int e2 = 2 * err;
if (e2 > -dy) { err -= dy; x1 += sx; }
if (e2 < dx) { err += dx; y1 += sy; }
}
}

int main(int argc, char *argv[]) {


if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
return 1;
}

SDL_Window *window = SDL_CreateWindow("Bresenham Line Drawing", SDL_WINDOWPOS_CENTERED, SDL_WI


if (!window) {
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}

SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);


if (!renderer) {
printf("Renderer could not be created! SDL_Error: %s\n", SDL_GetError());
SDL_DestroyWindow(window);
SDL_Quit();
return 1;
}

SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);

SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);


drawLineBresenham(renderer, 100, 100, 700, 500);

SDL_RenderPresent(renderer);

SDL_Event e;
int quit = 0;
while (!quit) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
quit = 1;
}
}
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/19
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}

I've updated your program to use Bresenham's line drawing algorithm instead of DDA. Let me know if
you need any further modifications or explanations! 🚀

explain

Explanation of Bresenham’s Line Drawing Algorithm in SDL2

The Bresenham’s Line Algorithm is an efficient way to draw lines using only integer arithmetic, which
makes it faster than the DDA algorithm that uses floating-point calculations.

1. Key Concepts of Bresenham’s Algorithm


1. Works with integer arithmetic → No need for division or floating-point calculations.
2. Only uses addition, subtraction, and bit-shifting → More efficient.
3. Uses an error term (`err`) to decide whether to increment `y` while moving in the `x` direction.
4. Handles all octants (line directions), making it robust.

2. Breakdown of `drawLineBresenham` Function


c

void drawLineBresenham(SDL_Renderer *renderer, int x1, int y1, int x2, int y2) {

This function takes starting point (x1, y1) and ending point (x2, y2) and draws a line between
them.

Step 1: Calculate Differences and Direction

int dx = abs(x2 - x1);


int dy = abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy;

`dx` → Absolute difference in the x-direction.


`dy` → Absolute difference in the y-direction.
`sx` → Determines whether x should increase (+1) or decrease (-1).
`sy` → Determines whether y should increase (+1) or decrease (-1).

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/19
`err` → The error term that helps decide whether to move `y` while moving `x`.

Step 2: Draw Pixels One by One

while (1) {
SDL_RenderDrawPoint(renderer, x1, y1);
if (x1 == x2 && y1 == y2) break;
int e2 = 2 * err;

Start at (x1, y1).


Keep drawing points until we reach (x2, y2).
`e2 = 2 * err` → Helps decide the next step.

Step 3: Update x and y Based on Error Term

if (e2 > -dy) { err -= dy; x1 += sx; }


if (e2 < dx) { err += dx; y1 += sy; }
}

If `e2 > -dy`, move right/left (`x1 += sx`).


If `e2 < dx`, move up/down (`y1 += sy`).
The error term adjusts dynamically, ensuring that the line is drawn smoothly.

3. Main Function (Creating SDL Window & Renderer)


Step 1: Initialize SDL

if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
return 1;
}

Initializes SDL2.
If it fails, prints an error message.

Step 2: Create Window

SDL_Window *window = SDL_CreateWindow("Bresenham Line Drawing", SDL_WINDOWPOS_CENTERED, SDL_WIND

Creates an SDL window titled "Bresenham Line Drawing".


Centered position, width 800px, height 600px.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/19
Step 3: Create Renderer

SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

Creates a renderer for drawing.


Uses hardware acceleration for better performance.

Step 4: Set Background & Line Colors

SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);

Sets background to black `(0, 0, 0)`.


Clears screen before drawing.

SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);


drawLineBresenham(renderer, 100, 100, 700, 500);

Sets line color to white `(255, 255, 255)`.


Calls `drawLineBresenham` to draw the line.

Step 5: Display Graphics

SDL_RenderPresent(renderer);

Updates the screen to show the drawn line.

Step 6: Event Loop (Wait for User to Close Window)

SDL_Event e;
int quit = 0;
while (!quit) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
quit = 1;
}
}
}

Listens for window close event (`SDL_QUIT`).

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/19
Keeps the window open until the user closes it.

Step 7: Cleanup

SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;

Frees memory and quits SDL properly.

4. Comparison: Bresenham vs. DDA


Feature Bresenham DDA

Uses integer arithmetic ✅ Yes ❌ No (uses floating-point)


Performance 🚀 Faster 🐢 Slower
Accuracy ✅ More accurate ⚠️ Rounding errors possible
Suitable for embedded systems ✅ Yes ❌ No
5. How to Compile & Run
Compile

sh

gcc -o bresenham_line bresenham_line.c -lSDL2

Run

sh

./bresenham_line

6. Summary
✅ Bresenham’s Algorithm is better than DDA because:
Uses only integer operations → Faster execution.
Avoids floating-point rounding errors.
Efficient for rasterized graphics (like games, simulations, and GUI elements).

Let me know if you want to add mouse input to draw lines dynamically! 🎨🚀

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/19
difference between breshman and dda

Difference Between Bresenham's Algorithm and DDA Algorithm

Both DDA (Digital Differential Analyzer) Algorithm and Bresenham's Algorithm are used for line
drawing in computer graphics. However, they differ in terms of efficiency, accuracy, and implementation.

1. Key Differences
Feature DDA (Digital Differential Analyzer) Bresenham’s Algorithm

Uses floating-point arithmetic (division, Uses only integer arithmetic (addition,


Arithmetic Used
multiplication) subtraction)

Performance Slower due to floating-point calculations Faster due to integer operations


More precise as it avoids floating-point
Accuracy May introduce rounding errors
rounding
Implementation
Simple but less efficient Slightly more complex but optimized
Complexity
Yes, but requires floating-point
Works for All Slopes Yes, efficiently handles all slopes
increments
Requires more storage for floating-point More memory-efficient due to integer-
Memory Efficiency
variables based operations

2. How Each Algorithm Works


DDA Algorithm (Digital Differential Analyzer)

Computes `dx = x2 - x1` and `dy = y2 - y1`.


Finds the number of steps = `max(|dx|, |dy|)`.
Uses floating-point increments:

xIncrement = dx / steps;
yIncrement = dy / steps;

Iterates `steps` times, adding `xIncrement` and `yIncrement` to `x` and `y` at each step.

Example Issue: Floating-point rounding can lead to inaccurate pixel placements.

Bresenham’s Algorithm

Uses integer-based arithmetic for better efficiency.


Maintains an error term (`err`) to decide when to increment `y` while moving `x`.
Works by checking the decision parameter `2 * err` and updating `x, y` accordingly.

Example Benefit: Since it avoids floating-point calculations, it is faster and more accurate.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/19
3. When to Use Which?
Use Case Recommended Algorithm

Performance is a priority (e.g., real-time rendering, games) ✅ Bresenham


Simple implementation with fewer constraints ✅ DDA
Embedded systems with limited computational power ✅ Bresenham
Applications requiring exact pixel alignment (e.g., rasterized images) ✅ Bresenham
4. Which One is Better?
✅ Bresenham’s Algorithm is generally better because:
It is faster (integer operations only).
It is more accurate (avoids floating-point rounding errors).
It is more efficient in memory usage.

However, DDA is easier to understand and implement for beginners.


Let me know if you want a DDA version in SDL2 for comparison! 🚀

now explain mid point circle

Mid-Point Circle Drawing Algorithm (Bresenham’s Circle Algorithm)

The Mid-Point Circle Algorithm (also known as Bresenham’s Circle Algorithm) is an efficient method
to draw a circle using only integer calculations. It is an optimized version of the traditional equation-
based approach, which avoids expensive multiplications and divisions.

1. Key Concepts
It is based on the symmetry of a circle, meaning we only calculate points for 1/8th of the circle
and reflect them to other parts.
Uses an error term (`p`) to determine whether the next pixel should move horizontally or
diagonally.

2. Steps of the Algorithm


1. Start at (0, R): Begin at the topmost point of the circle.
2. Calculate the initial decision parameter (`p`):

p=1−R

3. For each step:


Plot the 8 symmetric points using `(x, y)`.
If `p < 0`: Move right `(x+1)`, update `p = p + 2x + 1`.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/19
Else: Move diagonally `(x+1, y-1)`, update `p = p + 2x - 2y + 1`.
4. Repeat until `x >= y`.

3. SDL2 Implementation in C
Here’s how you can implement the Mid-Point Circle Algorithm using SDL2:

#include <SDL2/SDL.h>
#include <stdio.h>

#define SCREEN_WIDTH 800


#define SCREEN_HEIGHT 600

void drawCircle(SDL_Renderer *renderer, int xc, int yc, int r) {


int x = 0, y = r;
int p = 1 - r;

while (x <= y) {
// Draw 8 symmetrical points
SDL_RenderDrawPoint(renderer, xc + x, yc + y);
SDL_RenderDrawPoint(renderer, xc - x, yc + y);
SDL_RenderDrawPoint(renderer, xc + x, yc - y);
SDL_RenderDrawPoint(renderer, xc - x, yc - y);
SDL_RenderDrawPoint(renderer, xc + y, yc + x);
SDL_RenderDrawPoint(renderer, xc - y, yc + x);
SDL_RenderDrawPoint(renderer, xc + y, yc - x);
SDL_RenderDrawPoint(renderer, xc - y, yc - x);

// Update decision parameter


if (p < 0) {
p = p + 2 * x + 3;
} else {
p = p + 2 * (x - y) + 5;
y--;
}
x++;
}
}

int main(int argc, char *argv[]) {


SDL_Init(SDL_INIT_VIDEO);

SDL_Window *window = SDL_CreateWindow("Mid-Point Circle Algorithm", SDL_WINDOWPOS_CENTERED, SDL_


SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);

SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);


drawCircle(renderer, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 100); // Draw circle at center

SDL_RenderPresent(renderer);

SDL_Event e;
int quit = 0;
while (!quit) {
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
quit = 1;
}
}
}

SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/19
return 0;
}

4. Explanation of the Code


Function `drawCircle()`

Draws 8 symmetrical points using `SDL_RenderDrawPoint()`.


Uses a decision parameter (`p`) to decide whether to move right or diagonally.

Main Function

Initializes SDL2 window and renderer.


Clears the screen and draws a circle at the center.
Waits for the user to close the window.

5. Comparison: Mid-Point Circle vs. Traditional Method


Feature Mid-Point Circle Algorithm Traditional Equation-Based

Efficiency 🚀 Faster (integer-only calculations) 🐢 Slower (floating-point calculations)


Accuracy ✅ High ❌ Less accurate (rounding errors)
Complexity 🟢 Simple 🔴 More complex
6. Summary
✅ The Mid-Point Circle Algorithm is:
More efficient than using the equation x2 + y 2 = R2 .
Uses integer operations (addition, subtraction).
Plots only 1/8th of the circle, leveraging symmetry.

Let me know if you want to add user input to draw circles dynamically! 🚀🎨

what is this error and quit dont use this do it simply

Here's a simpler version of the Mid-Point Circle Algorithm in SDL2, without the event loop and error
handling. It will draw a circle and close immediately after displaying it.

Updated Simple Code

#include <SDL2/SDL.h>

#define SCREEN_WIDTH 800

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/19
#define SCREEN_HEIGHT 600

void drawCircle(SDL_Renderer *renderer, int xc, int yc, int r) {


int x = 0, y = r;
int p = 1 - r;

while (x <= y) {
SDL_RenderDrawPoint(renderer, xc + x, yc + y);
SDL_RenderDrawPoint(renderer, xc - x, yc + y);
SDL_RenderDrawPoint(renderer, xc + x, yc - y);
SDL_RenderDrawPoint(renderer, xc - x, yc - y);
SDL_RenderDrawPoint(renderer, xc + y, yc + x);
SDL_RenderDrawPoint(renderer, xc - y, yc + x);
SDL_RenderDrawPoint(renderer, xc + y, yc - x);
SDL_RenderDrawPoint(renderer, xc - y, yc - x);

if (p < 0) {
p += 2 * x + 3;
} else {
p += 2 * (x - y) + 5;
y--;
}
x++;
}
}

int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window = SDL_CreateWindow("Mid-Point Circle", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);

SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);


drawCircle(renderer, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 100);

SDL_RenderPresent(renderer);

SDL_Delay(2000); // Show the window for 2 seconds before closing

SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();

return 0;
}

Changes in this Version

✅ No error handling – Simplified initialization.


✅ No event loop – The program automatically closes after 2 seconds.
✅ Uses `SDL_Delay(2000)`– Keeps the window open briefly before closing.
Now, it just opens, displays a circle, and closes simply. Let me know if you need any modifications! 🚀
🎨

explain

Explanation of the Simple Mid-Point Circle Algorithm Code

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/19
This program draws a circle using SDL2 and the Mid-Point Circle Algorithm. It runs without any
event handling and closes automatically after 2 seconds.

1. Key Functions & Their Purpose


Function Purpose
`SDL_Init(SDL_INIT_VIDEO)` Initializes the SDL2 library.

`SDL_CreateWindow()` Creates a window to display graphics.


`SDL_CreateRenderer()` Creates a renderer to draw in the window.
Implements the Mid-Point Circle Algorithm to draw
`drawCircle(renderer, xc, yc, r)`
the circle.
`SDL_RenderPresent(renderer)` Updates the screen to show the circle.
`SDL_Delay(2000)` Keeps the window open for 2 seconds before closing.
`SDL_DestroyRenderer()` &
Cleans up resources before exiting.
`SDL_DestroyWindow()`
`SDL_Quit()` Shuts down SDL properly.

2. Understanding `drawCircle()`
Mid-Point Circle Algorithm Steps

1. Start at the top of the circle: `(x = 0, y = r)`.


2. Decision parameter `p` is initialized as:

p=1−r

3. Plot 8 symmetrical points using:


`(x+xc, y+yc)`, `(-x+xc, y+yc)`, etc.
4. Choose the next pixel based on `p`:
If `p < 0`, move right: `p = p + 2x + 3`
Else, move diagonally: `p = p + 2(x - y) + 5`
5. Repeat until `x >= y`, ensuring the full circle is drawn.

3. Key Optimizations
✅ Uses only integer calculations (faster, no floating-point errors).
✅ Only calculates 1/8th of the circle, using symmetry to plot the rest.
✅ No complex math (square roots, multiplications) needed.
4. What Happens When You Run It?
1. SDL initializes and a window appears.
2. A circle is drawn at the center (400, 300) with a radius of 100.
3. The program waits for 2 seconds (`SDL_Delay(2000)`).
4. Window closes automatically and SDL shuts down.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/19
5. Why This Version?
Simpler: No event handling, no complex loops.
Minimalistic: Focuses only on drawing the circle.
Automated Exit: No need to click anything—closes in 2 seconds.

Let me know if you want more modifications! 🚀🎨

Choose the next pixel based on p:


If p < 0, move right: p = p + 2x + 3
Else, move diagonally: p = p + 2(x - y) + 5
explain this

Explanation of Decision Parameter `p` in the Mid-Point Circle Algorithm

The Mid-Point Circle Algorithm determines the next pixel to plot based on a decision parameter `p`,
which helps decide whether to move right or diagonally.

1. How Does It Work?


The equation of a circle centered at (0, 0) with radius R is:

x2 + y 2 = R 2

In this algorithm, we only calculate points in the first octant (from 0∘ to 45∘ ), then reflect them across
the rest of the circle.

Step-by-Step Breakdown

1. Start at the top of the circle: (x


= 0, y = R).
2. Define the decision parameter p:
The mid-point between two possible pixels is at (x + 1, y − 0.5).
Check whether this point is inside or outside the circle:

p = f (x + 1, y − 0.5) = (x + 1)2 + (y − 0.5)2 − R2

The value of p helps determine which pixel to choose next:


If p < 0 → The mid-point is inside the circle, so move right.
If p ≥ 0 → The mid-point is outside the circle, so move diagonally down.

2. Decision Parameter Calculation


The initial decision parameter is:

p=1−R
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/19
Each step updates `p` as follows:

Condition Meaning Update Rule


If p <0 Mid-point is inside the circle → move right (x + 1, y) p = p + 2x + 3
If p ≥0 Mid-point is outside the circle → move diagonally (x + 1, y − 1) p = p + 2(x − y) + 5

Why These Formulas?

For moving right (x + 1, y), we add 2x + 3 because it accounts for the increase in x while y
remains the same.
For moving diagonally (x + 1, y − 1), we add 2(x − y) + 5 because both x and y change.

3. Example Calculation
Let’s assume R = 5, and start at (0, 5):
Step (x, y) Decision p Next Pixel Choice

1 (0,5) p = 1 − 5 = −4 p < 0 → Move right


2 (1,5) p = −4 + 2(1) + 3 = 1 p ≥ 0 → Move diagonally
3 (2,4) p = 1 + 2(2 − 4) + 5 = 2 p ≥ 0 → Move diagonally
4 (3,3) p = 2 + 2(3 − 3) + 5 = 7 p ≥ 0 → Move diagonally
This process continues until x ≥ y , at which point we stop and reflect the points across the rest of
the circle.

4. Summary
✅ Why Use `p`?

It avoids expensive operations like square roots or floating-point divisions.


Uses only integer additions and subtractions, making it fast and efficient.

✅ Why Use These Update Rules?


The formula ensures the closest pixel is chosen to approximate the circle.
It works efficiently by keeping computations minimal.

Let me know if you need further clarification! 🚀

mid point ellipse

Mid-Point Ellipse Algorithm Explanation

The Mid-Point Ellipse Algorithm is an efficient method for drawing an ellipse using integer
calculations, avoiding floating-point arithmetic. It extends the logic of the Mid-Point Circle Algorithm to

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/19
handle ellipses.

1. Equation of an Ellipse
An ellipse centered at (0, 0) with semi-major axis a (width) and semi-minor axis b (height) follows:

x2 y2
+ =1
a2 b2
​ ​

Instead of computing points directly, we use a decision parameter `p` to determine the next pixel.

2. Regions of the Ellipse


The algorithm divides the ellipse into two regions to decide the step increments:

Region 1 (First Half)

The slope is greater than -1 ( dx > −1).


dy

Move right or diagonally down-right.

Region 2 (Second Half)

The slope is less than -1 ( dx < −1).


dy

Move down or diagonally down-right.

3. Decision Parameters
Like the Mid-Point Circle Algorithm, we define two decision parameters:

For Region 1 (X-Incrementing)

The decision parameter is:

1
p 1 = b2 − a2 b + a2
4
​ ​

Update rule:

If p1 ​
< 0, move right (x + 1, y):

p1 = p1 + 2b2 x + 3b2
​ ​

If p1 ​ ≥ 0, move diagonally (x + 1, y − 1):

p1 = p1 + 2b2 x − 2a2 y + 2a2 + 3b2


​ ​

For Region 2 (Y-Decrementing)

The decision parameter is:


2 2 2 2 2 2
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/19
p2 = b2 (x + 0.5)2 + a2 (y − 1)2 − a2 b2

Update rule:

If p2 ​ > 0, move down (x, y − 1):

p2 = p2 − 2a2 y + 3a2
​ ​

If p2 ​
≤ 0, move diagonally (x + 1, y − 1):

p2 = p2 + 2b2 x − 2a2 y + 2a2 + 3b2


​ ​

4. SDL2 Code for Mid-Point Ellipse Algorithm


Here is a simple C program using SDL2 to draw an ellipse:

#include <SDL2/SDL.h>

#define SCREEN_WIDTH 800


#define SCREEN_HEIGHT 600

void drawEllipse(SDL_Renderer *renderer, int xc, int yc, int a, int b) {


int x = 0, y = b;
int a2 = a * a, b2 = b * b;
int p1 = b2 - a2 * b + (0.25 * a2);
int dx = 2 * b2 * x, dy = 2 * a2 * y;

// Region 1
while (dx < dy) {
SDL_RenderDrawPoint(renderer, xc + x, yc + y);
SDL_RenderDrawPoint(renderer, xc - x, yc + y);
SDL_RenderDrawPoint(renderer, xc + x, yc - y);
SDL_RenderDrawPoint(renderer, xc - x, yc - y);

x++;
dx += 2 * b2;
if (p1 < 0) {
p1 += dx + b2;
} else {
y--;
dy -= 2 * a2;
p1 += dx - dy + b2;
}
}

// Region 2
int p2 = b2 * (x + 0.5) * (x + 0.5) + a2 * (y - 1) * (y - 1) - a2 * b2;
while (y >= 0) {
SDL_RenderDrawPoint(renderer, xc + x, yc + y);
SDL_RenderDrawPoint(renderer, xc - x, yc + y);
SDL_RenderDrawPoint(renderer, xc + x, yc - y);
SDL_RenderDrawPoint(renderer, xc - x, yc - y);

y--;
dy -= 2 * a2;
if (p2 > 0) {
p2 += a2 - dy;
} else {
x++;
dx += 2 * b2;
p2 += dx - dy + a2;
}
}
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/19
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window = SDL_CreateWindow("Mid-Point Ellipse", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);

SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);


drawEllipse(renderer, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 200, 100);

SDL_RenderPresent(renderer);

SDL_Delay(3000); // Keep the window open for 3 seconds

SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();

return 0;
}

5. Summary of the Algorithm


✅ Divides the ellipse into two regions to determine movement.
✅ Uses integer-only calculations for efficiency.
✅ Uses symmetry to plot only 1/4th of the ellipse and mirror it.
✅ Faster than naive methods since it avoids floating-point operations.
Let me know if you need modifications or explanations! 🚀

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/19

You might also like