f61f3f6a36e4c42d00d0fbf6bf2158108a4706fd
[vrlugburz] / tools / dunger / src / level.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <GL/gl.h>
5 #include "level.h"
6
7 extern int view_width, view_height;
8
9 struct level *create_level(int xsz, int ysz)
10 {
11         struct level *lvl;
12
13         if(!(lvl = malloc(sizeof *lvl))) {
14                 return 0;
15         }
16         if(!(lvl->cells = calloc(xsz * ysz, sizeof *lvl->cells))) {
17                 free(lvl);
18                 return 0;
19         }
20         lvl->width = xsz;
21         lvl->height = ysz;
22         return lvl;
23 }
24
25 void free_level(struct level *lvl)
26 {
27         if(!lvl) return;
28         free(lvl->cells);
29         free(lvl);
30 }
31
32 static void draw_cell(float x, float y, float sz, struct cell *cell)
33 {
34         static const float colors[][3] = {{0, 0, 0}, {0.6, 0.6, 0.6}, {0.4, 0.2, 0.1}};
35
36         if(cell) {
37                 glColor3fv(colors[cell->type]);
38         } else {
39                 glColor3f(1, 1, 1);
40         }
41         glVertex2f(x, y);
42         glVertex2f(x + sz, y);
43         glVertex2f(x + sz, y + sz);
44         glVertex2f(x, y + sz);
45 }
46
47 void draw_level(struct level *lvl)
48 {
49         int i, j;
50         float x, y, dx, dy, cellsz;
51         struct cell *cell;
52
53         dx = view_width / lvl->width;
54         dy = view_height / lvl->height;
55         cellsz = dx > dy ? dy : dx;
56
57         glBegin(GL_QUADS);
58         cell = lvl->cells;
59         y = 0;
60         for(i=0; i<lvl->height; i++) {
61                 x = 0;
62                 for(j=0; j<lvl->width; j++) {
63                         draw_cell(x, y, cellsz, cell++);
64                         x += cellsz;
65                 }
66                 y += cellsz;
67         }
68         glEnd();
69
70         glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
71         glBegin(GL_QUADS);
72         y = 0;
73         for(i=0; i<lvl->height; i++) {
74                 x = 0;
75                 for(j=0; j<lvl->width; j++) {
76                         draw_cell(x, y, cellsz, 0);
77                         x += cellsz;
78                 }
79                 y += cellsz;
80         }
81         glEnd();
82         glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
83 }