SimpleGFX  1.0
Simple Graphics Library for C Programming Education
m-triangle.c File Reference

Drawing triangles using linear interpolation between vertices. More...

#include "gfx/simplegfx.h"

Functions

int main ()
 

Detailed Description

Drawing triangles using linear interpolation between vertices.

Author
Sukesh Ashok Kumar

This example demonstrates how to draw a triangle by connecting three points (vertices) with straight lines. It introduces polygon concepts and shows how to calculate points along a line using linear interpolation.

Mathematical Concepts:

  • Triangle: polygon with 3 vertices and 3 sides
  • Vertices: corner points that define the triangle
  • Linear interpolation: finding intermediate points between two endpoints
  • Point-slope form: (y - y1) / (y2 - y1) = (x - x1) / (x2 - x1)
  • Rearranged: y = y1 + (y2 - y1) × (x - x1) / (x2 - x1)

Triangle Properties:

  • Sum of interior angles = 180°
  • 3 sides, 3 vertices, 3 angles
  • Simplest polygon
  • This example creates an isosceles triangle (two equal sides)

Programming Concepts:

  • Linear interpolation (lerp) for line drawing
  • Connecting points to form polygons
  • Forward and backward iteration (x++ vs x–)
  • Integer division for coordinate calculation
  • Breaking complex shapes into simple lines

What you'll learn:

  • How to define a triangle using three vertices
  • Drawing lines by interpolating between endpoints
  • The mathematical formula for points on a line segment
  • Why we need different loop directions for different lines
  • Basic polygon construction
  • Converting mathematical concepts to pixel coordinates

Line Drawing Algorithm: For a line from (x1,y1) to (x2,y2):

  • Iterate x from x1 to x2
  • For each x, calculate y using linear interpolation
  • Formula: y = y1 + (y2-y1) × (x-x1) / (x2-x1)
  • This creates a straight line between the two points

Why Different Loop Directions?

  • Line 1 (top to bottom-left): x decreases (x–)
  • Line 2 (bottom-left to bottom-right): x increases (x++)
  • Line 3 (bottom-right to top): x decreases (x–) We loop in the direction where x changes monotonically.

Compile:

gcc m-triangle.c gfx/simplegfx.c -o output/m-triangle -lX11

Run:

./output/m-triangle

Function Documentation

◆ main()

int main ( )