summaryrefslogtreecommitdiffstats
path: root/sdl/pyramid.c
blob: 50b18334c5f5ee644ae8800f2a3f404647af0277 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/* pyramid.c
 *
 * @2011 Kamil Kaminski
 *
 * notes: since lighting is enabled, we need to specify normals for
 * each polygon face so the OpenGL can calculate e.g. how light reflects
 *
 * drawing a shadow for the pyramid would require drawing things twice, so on 2nd
 * pass we would draw with black color and multiply by squished matrix, we should
 * get to this later with better approach
 *
 * so far we have been using immediate mode rendering, we should begin using
 * display lists / batch processing to reduce overhead, aka compiling commands
 *
 * it might be time to split the code, and make a shader version...
 *
 */
 
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
/* for some reason order of the headers matters */
#include "math3d.h"
#include "gltools.h"
#include "glframe.h"
#include <sys/time.h>
#define FRAMES_PER_SECOND 60

/* function prototypes */
static void resize(int, int);
static void setup_opengl(void);
static void keys(SDL_keysym *, unsigned int *, int);
static void process_events(void);
static void render(void);

/* global */
int program_running = 1;
GLFrame camera;

/* display lists identifiers */
GLuint ground_list;
GLuint triangle_list;

static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;

/* few arrays, they could make into the header at some point */
GLfloat fNoLight[]     = { 0.0f, 0.0f, 0.0f, 0.0f };
GLfloat fLowLight[]    = { 0.25f, 0.25f, 0.25f, 1.0f };
GLfloat fBrightLight[] = { 1.0f, 1.0f, 1.0f, 1.0f };

static void resize(int w, int h)
{
    printf("window: resizing to %dx%d\n", w, h);
    GLfloat fAspect = (GLfloat) w / (GLfloat) h;
    if (h == 0)
        h = 1;
    glViewport(0, 0, w, h);

    /* reset coordinate system */
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    /* produce the perspective projection */
    /* void gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) */
    gluPerspective(40.0f, fAspect, 1.0, 40.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    
    /* this needs to be ran again, glut does it for you I suppose */
    SDL_SetVideoMode(w, h, 32, SDL_OPENGL | SDL_RESIZABLE);
}

static void setup_opengl(void)
{
    GLbyte *pBytes;
    GLint iWidth, iHeight, iComponents;
    GLenum eFormat;
    
    /* light values and coordinates */
    GLfloat whiteLight[]  = { 0.05f, 0.05f, 0.05f, 1.0f };
    GLfloat sourceLight[] = { 0.75f, 0.75f, 0.75f, 1.0f };
    GLfloat lightPos[]    = { -10.f, 5.0f, 5.0f, 1.0f };

    /* setup fog */
    glEnable(GL_FOG);
    glFogfv(GL_FOG_COLOR, fLowLight); /* set fog color to match background */
    glFogf(GL_FOG_START, 4.0f);
    glFogf(GL_FOG_END, 20.0f);
    glFogi(GL_FOG_MODE, GL_LINEAR);   /* fog equation */

    glEnable(GL_DEPTH_TEST);          /* hidden surface removal */
    glFrontFace(GL_CCW);              /* counter clock-wise polygons face out */
    glEnable(GL_CULL_FACE);           /* do not calculate inside of a pyramid */

    /* setup and enable light 0 */
    /* ambient RGBA intensity of the entire scene */
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, whiteLight);
    glLightfv(GL_LIGHT0, GL_AMBIENT, sourceLight);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, fBrightLight);
    glLightfv(GL_LIGHT0, GL_SPECULAR, fBrightLight);
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
    
    /* enable lighting */    
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    
    /* enable color tracking */
    glEnable(GL_COLOR_MATERIAL);
    
    /* set Material properties to follow glColor values */
    glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
    glMaterialfv(GL_FRONT, GL_SPECULAR, fBrightLight);
    glMateriali(GL_FRONT, GL_SHININESS, 128);

    /* turn on anti aliasing for points, lines, and polygons */
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);
    glEnable(GL_POINT_SMOOTH);
    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
    glEnable(GL_LINE_SMOOTH);
    glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
    /* screws up snowman */
    //glEnable(GL_POLYGON_SMOOTH);
    //glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);

    /* gray background */
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    
    /* load texture */
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    pBytes = gltLoadTGA("stone.tga", &iWidth, &iHeight, &iComponents, &eFormat);
    if (!pBytes)
        fprintf(stderr, "gltLoadTGA: failed to load texture!\n");

    /* load texture image */
    glTexImage2D(GL_TEXTURE_2D, 0, iComponents, iWidth, iHeight, 0, eFormat,
                 GL_UNSIGNED_BYTE, pBytes);
    free(pBytes);
    
    /* texture filtering, we modify deafult values since we don't have mipmaps */
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    
    /* how OpenGL combines the colors from texels with the color of the underlying
     * geometry is controlled by the texture environment mode */
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    
    /* once texture is loaded and enabled, it will applied to every primitive
     * that specifies coordinates */
    glEnable(GL_TEXTURE_2D);
    
    /* set the camera to <0,0,0> */
    glframe_reset(&camera);
    
    /* multisampling for polygons, conflicts with anti-aliasing */
    //glEnable(GL_MULTISAMPLE);
    
    /* don't know about this, but why not */
    glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
    
    /* display list, precompile commands */
    ground_list = glGenLists(2);
    triangle_list = ground_list + 1;
    
    glNewList(ground_list, GL_COMPILE);
       gltDrawGround();
    glEndList();
    
    glNewList(triangle_list, GL_COMPILE);
       gltDrawTriangle();
    glEndList();
}

static void keys(SDL_keysym *keysym, unsigned int *keys_held, int flag)
{
    if (!flag)
    {
        switch (keysym->sym)
        {
        case SDLK_ESCAPE: program_running = 0; break;
        case SDLK_w: xRot -= 5.0f; break;
        case SDLK_s: xRot += 5.0f; break;
        case SDLK_a: yRot -= 5.0f; break;
        case SDLK_d: yRot += 5.0f; break;
        case SDLK_UP: glframe_move_forward(&camera, 0.5f); break;
        case SDLK_DOWN: glframe_move_forward(&camera, -0.5f); break;
        case SDLK_LEFT: glframe_rotate_local_y(&camera, 0.1f); break;
        case SDLK_RIGHT: glframe_rotate_local_y(&camera, -0.1f); break;
        default: break;
        }
    }
    else
    {
        if (keys_held[SDLK_w])
            xRot -= 5.0f;
        if (keys_held[SDLK_s])
            xRot += 5.0f;
        if (keys_held[SDLK_a])
            yRot -= 5.0f;
        if (keys_held[SDLK_d])
            yRot += 5.0f;
            
        if (keys_held[SDLK_UP])
            glframe_move_forward(&camera, 0.05f);
        if (keys_held[SDLK_DOWN])
            glframe_move_forward(&camera, -0.05f);
        if (keys_held[SDLK_LEFT])
            glframe_rotate_local_y(&camera, 0.02f);
        if (keys_held[SDLK_RIGHT])
            glframe_rotate_local_y(&camera, -0.02f);
    }
                
    xRot = (GLfloat) ((const int) xRot % 360);
    yRot = (GLfloat) ((const int) yRot % 360);
}

/* process SDL events */
static void process_events(void)
{
    SDL_Event event;
    unsigned static int keys_held[323];
    SDLKey sym;
    /* helper flag for keys() */
    int flag = 0;
    
    while (SDL_PollEvent(&event))
    {
        sym = event.key.keysym.sym;
    
        switch (event.type)
        {
        case SDL_KEYUP:
        {
            /* reset the key to 0 */
            keys_held[sym] = 0;
            break;
        }
        case SDL_KEYDOWN:
        {
            keys_held[sym] = 1;
            keys(&event.key.keysym, keys_held, flag);
            break;
        }
        case SDL_VIDEORESIZE: { resize(event.resize.w, event.resize.h); break; }
        case SDL_QUIT: { program_running = 0; break; }
        default: break;
        }
    }
    
    /* below code has to be placed here, check for keys that are being constantly held */
    if (keys_held[SDLK_w] || keys_held[SDLK_s] || keys_held[SDLK_a] || keys_held[SDLK_d] ||
        keys_held[SDLK_UP] || keys_held[SDLK_DOWN] || keys_held[SDLK_LEFT] || keys_held[SDLK_RIGHT])
    {
        flag = !flag;
        keys(NULL, keys_held, flag);
    }
    else
        flag = !flag;
}

static void render(void)
{                              
    /* clear the window with current clearing color */
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    /* save the matrix state and do the rotations */
    glPushMatrix();
        /* apply camera transform, and draw the ground */
        glframe_apply_camera_transform(&camera);
        glColor3ub(255, 0, 255);
        glCallList(ground_list);

        glPushMatrix();
        /* move object back and do in place rotation */
        glTranslatef(0.0f, 0.2f, -3.5f);
        glRotatef(xRot, 1.0f, 0.0f, 0.0f);
        glRotatef(yRot, 0.0f, 1.0f, 0.0f);

        /* draw the pyramid */
        glColor3f(1.0f, 1.0f, 1.0f);
        glCallList(triangle_list);
        glPopMatrix();

        /* draw a snowman */
        glTranslatef(0.0f, 0.0f, -7.0f);
        gltDrawSnowman();
    
    /* restore the matrix state */
    glPopMatrix();

    /* buffer swap */
    SDL_GL_SwapBuffers();
}

int main(int argc, char **argv)
{
    SDL_Surface *screen;

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0 )
    {
        fprintf(stderr, "unable to init SDL: %s\n", SDL_GetError());
        exit(-1);
    }
    atexit(SDL_Quit);
    SDL_WM_SetCaption("Textured Pyramid", NULL);
    SDL_WM_SetIcon(IMG_Load("tux.png"), NULL);
    
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	
    if ((screen = SDL_SetVideoMode(640, 480, 32, SDL_OPENGL | SDL_RESIZABLE)) == NULL)
    {
        fprintf(stderr, "unable to set video mode: %s\n", SDL_GetError());
        exit(-1);
    }
    
    SDL_EnableUNICODE(1);
    /* SDL doesn't trigger off a ResizeEvent at startup, but as we need this 
     * for OpenGL, we do this ourselves */
    SDL_Event resizeEvent;
    resizeEvent.type = SDL_VIDEORESIZE;
    resizeEvent.resize.w = 640;
    resizeEvent.resize.h = 480;
    SDL_PushEvent(&resizeEvent);
    
    /* initalize glew */
    GLenum glewerr = glewInit();
    if (GLEW_OK != glewerr)
    {
        fprintf(stderr, "error: %s\n", glewGetErrorString(glewerr));
        return -1;
    }
    else
        fprintf(stdout, "status: using GLEW %s\n", glewGetString(GLEW_VERSION));
        
    /* display OpenGL version */
    GLint major;
    GLint minor;
    glGetIntegerv(GL_MAJOR_VERSION, &major);
    glGetIntegerv(GL_MINOR_VERSION, &minor);
    fprintf(stdout, "version: OpenGL %d.%d\n", major, minor);

    setup_opengl();
    
#ifdef STAT_FPS
    /* fps counter */
    Uint32 startclock = 0;
    Uint32 deltaclock = 0;
    Uint32 current_fps = 0;
#endif
    struct timeval m_LastCount;
    struct timeval lcurrent;
    while (program_running)
    {
        gettimeofday(&m_LastCount, 0);
#ifdef STAT_FPS
        startclock = SDL_GetTicks();
#endif
        process_events();
        render();
        
        gettimeofday(&lcurrent, 0);
        float fSeconds = (float) (lcurrent.tv_sec - m_LastCount.tv_sec);
        float fFraction = (float) (lcurrent.tv_usec - m_LastCount.tv_usec) * 0.000001f;
        float delta = fSeconds + fFraction;
        
        if (delta < 1000 / FRAMES_PER_SECOND)
            SDL_Delay((1000 / FRAMES_PER_SECOND) - delta);
        
#ifdef STAT_FPS
        deltaclock = SDL_GetTicks() - startclock;
        if (deltaclock != 0 )
            current_fps = 1000 / deltaclock;

        static char buffer[30] = { 0 };
        sprintf(buffer, "Textured Pyramid: %4d fps", current_fps);
        SDL_WM_SetCaption(buffer, NULL);
#endif
    }
    
    glDeleteLists(ground_list, 2);
    puts("bye!");
    
    return 0;
}