Blob Blame History Raw
#include <math.h>
#include <gtk/gtk.h>


const double pi = 3.141592653589793;

void line(cairo_t *cr, double x1, double y1, double x2, double y2) {
  cairo_move_to(cr, x1, y1);
  cairo_line_to(cr, x2, y2);
  cairo_set_source_rgba(cr, 0, 0, 0, 1);
  cairo_stroke(cr);
}

void figure(cairo_t *cr, double x1, double y1, double x2, double y2, int level) {
  if (level < 5) {
    double ax = (x2 - x1)/3 + x1;
    double ay = (y2 - y1)/3 + y1;

    double cx = (x1 - x2)/3 + x2;
    double cy = (y1 - y2)/3 + y2;

    double bx = (ax + cx)/2 + (cy - ay)*sin(60.0/180.0*pi);
    double by = (ay + cy)/2 - (cx - ax)*sin(60.0/180.0*pi);

    figure(cr, x1, y1, ax, ay, level+1);
    figure(cr, ax, ay, bx, by, level+1);
    figure(cr, bx, by, cx, cy, level+1);
    figure(cr, cx, cy, x2, y2, level+1);
  } else {
    line(cr, x1, y1, x2, y2);
  }
}

gboolean draw(GtkWidget *widget, cairo_t *cr, gpointer data) {
  cairo_set_source_rgba(cr, 0.9, 0.9, 0.9, 1);
  cairo_paint(cr);
  figure(cr, 100, 400, 500, 400, 0);
  return TRUE;
}

void activate(GtkApplication* app, gpointer data) {
  GtkWidget *window = gtk_application_window_new (app);
  g_signal_connect(window, "draw", G_CALLBACK(draw), NULL);
  gtk_window_set_default_size(GTK_WINDOW(window), 600, 600);
  gtk_widget_show_all(window);
}

int main(int argc, char **argv) {
  GtkApplication *application = gtk_application_new(NULL, 0);
  g_signal_connect(application, "activate", G_CALLBACK(activate), NULL);
  int status = g_application_run(G_APPLICATION(application), argc, argv);
  g_object_unref(application);
  return status;
}