Initial commit.
[grGL.git] / src / graph.c
1 #include <stdlib.h>
2 #include <GL/gl.h>
3
4 #include "graph.h"
5
6 /****************************
7  * Graph memory
8  ***************************/
9
10 // Free the memory for a graph and substructures
11 void grFree(grGraph *g)
12 {
13   if (g)
14   {
15     if (g->nodes)
16       free(g->nodes);
17     if (g->edges)
18       free(g->edges);
19     free(g);
20   }
21 }
22
23
24 // Allocate memory for a new graph, return NULL on any error
25 grGraph* grAlloc(int numnodes, int numedges)
26 {
27   grGraph *g;
28
29   g = malloc(sizeof(grGraph));
30   if (!g)
31     return NULL;
32
33   g->nodes = malloc(sizeof(grNode[numnodes]));
34   g->edges = malloc(sizeof(grEdge[numedges]));
35   if (!g->nodes || !g->edges)
36     goto ERR;
37
38   g->numnodes = numnodes;
39   g->numedges = numedges;
40
41   return g;
42
43   ERR:
44   grFree(g);
45   return NULL;
46 }
47
48
49
50 /****************************
51  * Graph generation
52  ***************************/
53
54 // Randomize a graph
55 void grGenRandom(grGraph *g)
56 {
57   int i;
58   int ns = g->numnodes;
59   int es = g->numedges;
60
61   for (i = 0; i < ns; i++)
62   {
63     grNode *n = &g->nodes[i];
64
65     n->x = (float)rand() / (RAND_MAX/4);
66     n->y = (float)rand() / (RAND_MAX/4);
67     n->z = (float)rand() / (RAND_MAX/4);
68     n->colour = 0.0;
69   }
70
71   for (i = 0; i < es; i++)
72   {
73     grEdge *e = &g->edges[i];
74
75     e->n1 = rand() / (RAND_MAX/ns);
76     e->n2 = rand() / (RAND_MAX/ns);
77   }
78 }
79
80
81
82 /****************************
83  * Graph drawing functions
84  ***************************/
85
86 // Draw the graph on the current OpenGL context
87 void graphDrawGL(grGraph *g)
88 {
89   int i;
90   int ns = g->numnodes;
91   int es = g->numedges;
92
93   // Draw edges
94   glColor4f(0.0, 0.0, 1.0, 0.5);
95   for (i = 0; i < es; i++)
96   {
97     grNode *n1 = &g->nodes[g->edges[i].n1];
98     grNode *n2 = &g->nodes[g->edges[i].n2];
99
100     glBegin(GL_LINE_STRIP);
101       glVertex3f(n1->x, n1->y, n1->z);
102       glVertex3f(n2->x, n2->y, n2->z);
103     glEnd();
104   }
105
106   // Draw nodes
107   glPointSize(5.0);
108   glBegin(GL_POINTS);
109     for (i = 0; i < ns; i++)
110     {
111       grNode *n = &g->nodes[i];
112       //glLoadName(i);    // Load point number into depth buffer for selection
113       glColor4f(n->colour, 1.0, 0.3, 0.7);
114       glVertex3f(n->x, n->y, n->z);
115     }
116   glEnd();
117 }