Skip to content

Instantly share code, notes, and snippets.

@tuttlem
Created February 8, 2015 13:45
Show Gist options
  • Save tuttlem/99f563e8f5b7cb04cf3d to your computer and use it in GitHub Desktop.
Save tuttlem/99f563e8f5b7cb04cf3d to your computer and use it in GitHub Desktop.
Mystify
#include <stdlib.h>
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#define N_VERTS 5
#define WIN_WIDTH 1024
#define WIN_HEIGHT 768
struct tag_mystify_vert {
int x, y; /* x and y positions */
int vx, vy; /* x and y velocities */
double r, g, b; /* colour components */
};
typedef struct tag_mystify_vert mystify_vert;
mystify_vert verts[N_VERTS];
GtkWidget *darea;
void init_verts() {
int n;
for (n = 0; n < N_VERTS; n ++) {
verts[n].x = rand() % WIN_WIDTH;
verts[n].y = rand() % WIN_HEIGHT;
verts[n].vx = 0;
verts[n].vy = 0;
while (verts[n].vx == 0) {
verts[n].vx = 5 - rand() % 10;
}
while (verts[n].vy == 0) {
verts[n].vy = 5 - rand() % 10;
}
verts[n].r = (rand() % 255) / 255.0;
verts[n].g = (rand() % 255) / 255.0;
verts[n].b = (rand() % 255) / 255.0;
}
}
void animate_verts() {
int n;
for (n = 0; n < N_VERTS; n ++) {
verts[n].x += verts[n].vx;
if (verts[n].x < 0 || verts[n].x > WIN_WIDTH) {
verts[n].vx *= -1;
verts[n].x += (verts[n].vx * 2);
}
verts[n].y += verts[n].vy;
if (verts[n].y < 0 || verts[n].y > WIN_HEIGHT) {
verts[n].vy *= -1;
verts[n].y += (verts[n].vy * 2);
}
}
}
gboolean mystify_animate(GtkWidget *window) {
animate_verts();
gtk_widget_queue_draw_area(window, 0, 0, WIN_WIDTH, WIN_HEIGHT);
return TRUE;
}
static gboolean on_draw_event(GtkWidget *widget, cairo_t *cr, gpointer user_data) {
int n;
/* clear the background to black */
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_paint(cr);
for (n = 0; n < (N_VERTS - 1); n ++) {
cairo_set_source_rgb(cr, verts[n].r, verts[n].g, verts[n].b);
cairo_move_to (cr, verts[n].x, verts[n].y);
cairo_line_to (cr, verts[n + 1].x, verts[n + 1].y);
cairo_set_line_width (cr, 1);
cairo_stroke (cr);
}
n = N_VERTS - 1;
cairo_set_source_rgb(cr, verts[n].r, verts[n].g, verts[n].b);
cairo_move_to (cr, verts[n].x, verts[n].y);
cairo_line_to (cr, verts[0].x, verts[0].y);
cairo_set_line_width (cr, 1);
cairo_stroke (cr);
return FALSE;
}
int main(int argc, char *argv[]) {
GtkWidget *window;
gtk_init(&argc, &argv);
init_verts();
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
darea = gtk_drawing_area_new();
gtk_container_add(GTK_CONTAINER(window), darea);
g_signal_connect(G_OBJECT(darea), "draw", G_CALLBACK(on_draw_event), NULL);
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
gtk_window_set_default_size(GTK_WINDOW(window), WIN_WIDTH, WIN_HEIGHT);
gtk_window_set_title(GTK_WINDOW(window), "Lines");
gtk_widget_show_all(window);
(void)g_timeout_add(33, (GSourceFunc)mystify_animate, window);
gtk_main();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment