summary refs log tree commit diff stats
path: root/src/renderer.cpp
blob: 2ee0642e7d06ff21f1774cad3141ac2f7ac7c7e2 (plain) (blame)
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
#include "renderer.h"
#include <string>
#include <fstream>
#include <vector>
#include <cstdio>
#include "mapview.h"

static bool rendererInitialized = false;

static GLFWwindow* window;

static GLuint FramebufferName; // The framebuffer
static GLuint ntscShader; // The NTSC shader
static GLuint finalShader; // The passthrough shader
static GLuint blitShader; // The blitting shader
static GLuint fillShader; // The fill shader
static GLuint bloom1Shader;
static GLuint bloom2Shader;

// The buffers for the NTSC rendering process
static GLuint renderedTex1;
static GLuint renderedTex2;
static GLuint renderedTexBufs[2];
static int curBuf;
static GLuint artifactsTex;
static GLuint scanlinesTex;
static GLuint preBloomTex;
static GLuint bloomPassTex;

// The VAO
static GLuint VertexArrayID;

// A plane that fills the renderbuffer
static GLuint quad_vertexbuffer;

GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path)
{ 
    // Create the shaders
    GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
    GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
 
    // Read the Vertex Shader code from the file
    std::string VertexShaderCode;
    std::ifstream VertexShaderStream(vertex_file_path, std::ios::in);
    if(VertexShaderStream.is_open())
    {
        std::string Line = "";
        while(getline(VertexShaderStream, Line))
            VertexShaderCode += "\n" + Line;
        VertexShaderStream.close();
    }
 
    // Read the Fragment Shader code from the file
    std::string FragmentShaderCode;
    std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in);
    if(FragmentShaderStream.is_open()){
        std::string Line = "";
        while(getline(FragmentShaderStream, Line))
            FragmentShaderCode += "\n" + Line;
        FragmentShaderStream.close();
    }
 
    GLint Result = GL_FALSE;
    int InfoLogLength;
 
    // Compile Vertex Shader
    printf("Compiling shader : %s\n", vertex_file_path);
    char const * VertexSourcePointer = VertexShaderCode.c_str();
    glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
    glCompileShader(VertexShaderID);
 
    // Check Vertex Shader
    glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result);
    glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    std::vector<char> VertexShaderErrorMessage(InfoLogLength);
    glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
    fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]);
 
    // Compile Fragment Shader
    printf("Compiling shader : %s\n", fragment_file_path);
    char const * FragmentSourcePointer = FragmentShaderCode.c_str();
    glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , NULL);
    glCompileShader(FragmentShaderID);
 
    // Check Fragment Shader
    glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result);
    glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    std::vector<char> FragmentShaderErrorMessage(InfoLogLength);
    glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]);
    fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]);
 
    // Link the program
    fprintf(stdout, "Linking program\n");
    GLuint ProgramID = glCreateProgram();
    glAttachShader(ProgramID, VertexShaderID);
    glAttachShader(ProgramID, FragmentShaderID);
    glLinkProgram(ProgramID);
 
    // Check the program
    glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result);
    glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength);
    std::vector<char> ProgramErrorMessage( glm::max(InfoLogLength, int(1)) );
    glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]);
    fprintf(stdout, "%s\n", &ProgramErrorMessage[0]);
 
    glDeleteShader(VertexShaderID);
    glDeleteShader(FragmentShaderID);
 
    return ProgramID;
}

GLuint loadBMP_custom(const char * imagepath){

	printf("Reading image %s\n", imagepath);

	// Data read from the header of the BMP file
	unsigned char header[54];
	unsigned int dataPos;
	unsigned int imageSize;
	unsigned int width, height;
	// Actual RGB data
	unsigned char * data;

	// Open the file
	FILE * file = fopen(imagepath,"rb");
	if (!file)							    {printf("%s could not be opened. Are you in the right directory ? Don't forget to read the FAQ !\n", imagepath); getchar(); return 0;}

	// Read the header, i.e. the 54 first bytes

	// If less than 54 bytes are read, problem
	if ( fread(header, 1, 54, file)!=54 ){ 
		printf("Not a correct BMP file\n");
		return 0;
	}
	// A BMP files always begins with "BM"
	if ( header[0]!='B' || header[1]!='M' ){
		printf("Not a correct BMP file\n");
		return 0;
	}
	// Make sure this is a 24bpp file
	if ( *(int*)&(header[0x1E])!=0  )         {printf("Not a correct BMP file\n");    return 0;}
	if ( *(int*)&(header[0x1C])!=24 )         {printf("Not a correct BMP file\n");    return 0;}

	// Read the information about the image
	dataPos    = *(int*)&(header[0x0A]);
	imageSize  = *(int*)&(header[0x22]);
	width      = *(int*)&(header[0x12]);
	height     = *(int*)&(header[0x16]);

	// Some BMP files are misformatted, guess missing information
	if (imageSize==0)    imageSize=width*height*3; // 3 : one byte for each Red, Green and Blue component
	if (dataPos==0)      dataPos=54; // The BMP header is done that way

	// Create a buffer
	data = new unsigned char [imageSize];

	// Read the actual data from the file into the buffer
	fread(data,1,imageSize,file);

	// Everything is in memory now, the file wan be closed
	fclose (file);

	// Create one OpenGL texture
	GLuint textureID;
	glGenTextures(1, &textureID);
	
	// "Bind" the newly created texture : all future texture functions will modify this texture
	glBindTexture(GL_TEXTURE_2D, textureID);

	// Give the image to OpenGL
	glTexImage2D(GL_TEXTURE_2D, 0,GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);

	// OpenGL has now copied the data. Free our own version
	delete [] data;

	// Poor filtering, or ...
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 

	// ... nice trilinear filtering.
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); 
	glGenerateMipmap(GL_TEXTURE_2D);

	// Return the ID of the texture we just created
	return textureID;
}

GLFWwindow* initRenderer()
{
  if (rendererInitialized)
  {
    fprintf(stderr, "Renderer already initialized\n");
    exit(-1);
  }
  
  // Initialize GLFW
  if (!glfwInit())
  {
    fprintf(stderr, "Failed to initialize GLFW\n");
    exit(-1);
  }
  
  glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want version 3.3
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Mac requires this
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  
  // Create a window
  window = glfwCreateWindow(1024, 768, "Aromatherapy", NULL, NULL);
  if (window == NULL)
  {
    fprintf(stderr, "Failed to open GLFW window\n");
    glfwTerminate();
    exit(-1);
  }
  
  glfwMakeContextCurrent(window);
  glewExperimental = true; // Needed in core profile
  if (glewInit() != GLEW_OK)
  {
    fprintf(stderr, "Failed to initialize GLEW\n");
    exit(-1);
  }
  
  // Set up vertex array object
  glGenVertexArrays(1, &VertexArrayID);
  glBindVertexArray(VertexArrayID);
  
  // Set up the framebuffer
  glGenFramebuffers(1, &FramebufferName);
  glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
  GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0};
  glDrawBuffers(1, DrawBuffers);
  
  // Set up the NTSC rendering buffers
  glGenTextures(1, &renderedTex1);
  glBindTexture(GL_TEXTURE_2D, renderedTex1);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, GAME_WIDTH, GAME_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  renderedTexBufs[0] = renderedTex1;
  
  glGenTextures(1, &renderedTex2);
  glBindTexture(GL_TEXTURE_2D, renderedTex2);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, GAME_WIDTH, GAME_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  renderedTexBufs[1] = renderedTex2;
  
  // Set up bloom rendering buffers
  glGenTextures(1, &preBloomTex);
  glBindTexture(GL_TEXTURE_2D, preBloomTex);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 768, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_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);
  
  glGenTextures(1, &bloomPassTex);
  glBindTexture(GL_TEXTURE_2D, bloomPassTex);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 64, 48, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_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);
  
  curBuf = 0;
  
  // Load the vertices of a flat surface
  GLfloat g_quad_vertex_buffer_data[] = { 
		-1.0f, -1.0f, 0.0f,
		 1.0f, -1.0f, 0.0f,
		-1.0f,  1.0f, 0.0f,
		-1.0f,  1.0f, 0.0f,
		 1.0f, -1.0f, 0.0f,
		 1.0f,  1.0f, 0.0f,
	};

  glGenBuffers(1, &quad_vertexbuffer);
  glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW);
  
  artifactsTex = loadBMP_custom("../res/artifacts.bmp");
  scanlinesTex = loadBMP_custom("../res/scanlines.bmp");
  
  // Load the shaders
  ntscShader = LoadShaders("../shaders/ntsc.vertex", "../shaders/ntsc.fragment");
  finalShader = LoadShaders("../shaders/final.vertex", "../shaders/final.fragment");
  blitShader = LoadShaders("../shaders/blit.vertex", "../shaders/blit.fragment");
  fillShader = LoadShaders("../shaders/fill.vertex", "../shaders/fill.fragment");
  bloom1Shader = LoadShaders("../shaders/bloom1.vertex", "../shaders/bloom1.fragment");
  bloom2Shader = LoadShaders("../shaders/bloom2.vertex", "../shaders/bloom2.fragment");
  
  rendererInitialized = true;
  
  return window;
}

void destroyRenderer()
{
  if (!rendererInitialized)
  {
    fprintf(stderr, "Renderer not initialized\n");
    exit(-1);
  }
  
  // Delete the plane buffer
  glDeleteBuffers(1, &quad_vertexbuffer);
  
  // Delete the shaders
  glDeleteProgram(ntscShader);
  glDeleteProgram(finalShader);
  glDeleteProgram(blitShader);
  glDeleteProgram(fillShader);
  glDeleteProgram(bloom1Shader);
  glDeleteProgram(bloom2Shader);
  
  // Delete the NTSC rendering buffers
  glDeleteTextures(1, &renderedTex1);
  glDeleteTextures(1, &renderedTex2);
  glDeleteTextures(1, &artifactsTex);
  glDeleteTextures(1, &scanlinesTex);
  glDeleteTextures(1, &preBloomTex);
  glDeleteTextures(1, &bloomPassTex);
  
  // Delete the framebuffer
  glDeleteFramebuffers(1, &FramebufferName);
  
  // Delete the VAO
  glDeleteVertexArrays(1, &VertexArrayID);
  
  // Kill the window
  glfwTerminate();
  
  rendererInitialized = false;
}

Texture* createTexture(int width, int height)
{
  if (!rendererInitialized)
  {
    fprintf(stderr, "Renderer not initialized\n");
    exit(-1);
  }
  
  Texture* tex = new Texture();
  tex->width = width;
  tex->height = height;
  
  glGenTextures(1, &(tex->texID));
  glBindTexture(GL_TEXTURE_2D, tex->texID);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  
  return tex;
}

void destroyTexture(Texture* tex)
{
  if (!rendererInitialized)
  {
    fprintf(stderr, "Renderer not initialized\n");
    exit(-1);
  }
  
  glDeleteTextures(1, &(tex->texID));
  
  delete tex;
}

Texture* loadTextureFromBMP(char* filename)
{
  if (!rendererInitialized)
  {
    fprintf(stderr, "Renderer not initialized\n");
    exit(-1);
  }
  
  Texture* tex = new Texture();
  tex->texID = loadBMP_custom(filename);
  
  glBindTexture(GL_TEXTURE_2D, tex->texID);
  glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &(tex->width));
  glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &(tex->height));
  
  return tex;
}

void saveTextureToBMP(Texture* tex, char* filename)
{
  if (!rendererInitialized)
  {
    fprintf(stderr, "Renderer not initialized\n");
    exit(-1);
  }
  
  int size = 54 + 3*tex->width*tex->height;
  
  char* buf = (char*) calloc(size, sizeof(char));
  buf[0x00] = 'B';
  buf[0x01] = 'M';
  *(int*)&(buf[0x0A]) = 54;
  *(int*)&(buf[0x12]) = tex->width;
  *(int*)&(buf[0x16]) = tex->height;
  *(int*)&(buf[0x1C]) = 24;
  *(int*)&(buf[0x1E]) = 0;
  *(int*)&(buf[0x22]) = size;
  
  glBindTexture(GL_TEXTURE_2D, tex->texID);
  glGetTexImage(GL_TEXTURE_2D, 0, GL_BGR, GL_UNSIGNED_BYTE, buf + 54);
  
  FILE* f = fopen(filename, "wb");
  fwrite(buf, sizeof(char), size, f);
  fclose(f);
  
  free(buf);
}

void fillTexture(Texture* tex, Rectangle* dstrect, int r, int g, int b)
{
  if (!rendererInitialized)
  {
    fprintf(stderr, "Renderer not initialized\n");
    exit(-1);
  }
  
  // Target the framebuffer
  glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
  glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tex->texID, 0);
  
  // Set up the vertex attributes
  GLfloat minx = (dstrect == NULL) ? 0.0f : dstrect->x;
  GLfloat miny = (dstrect == NULL) ? 0.0f : dstrect->y;
  GLfloat maxx = (dstrect == NULL) ? tex->width : dstrect->x + dstrect->w;
  GLfloat maxy = (dstrect == NULL) ? tex->height : dstrect->y + dstrect->h;
  
  minx = minx / tex->width * 2.0 - 1.0;
  miny = -(miny / tex->height * 2.0 - 1.0);
  maxx = maxx / tex->width * 2.0 - 1.0;
  maxy = -(maxy / tex->height * 2.0 - 1.0);
  
  GLfloat vertexbuffer_data[] = {
    minx, miny,
    maxx, miny,
    maxx, maxy,
    minx, miny,
    minx, maxy,
    maxx, maxy
  };
  GLuint vertexbuffer;
  glGenBuffers(1, &vertexbuffer);
  glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertexbuffer_data), vertexbuffer_data, GL_STATIC_DRAW);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
  
  glViewport(0, 0, tex->width, tex->height);
  glUseProgram(fillShader);
  glUniform3f(glGetUniformLocation(fillShader, "vecColor"), r / 255.0, g / 255.0, b / 255.0);
  
  glDrawArrays(GL_TRIANGLES, 0, 6);
  
  glDisableVertexAttribArray(0);
  glDeleteBuffers(1, &vertexbuffer);
}

void blitTexture(Texture* srctex, Texture* dsttex, Rectangle* srcrect, Rectangle* dstrect)
{
  if (!rendererInitialized)
  {
    fprintf(stderr, "Renderer not initialized\n");
    exit(-1);
  }
  
  // Target the framebuffer
  glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
  glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, dsttex->texID, 0);
  
  // Set up the vertex attributes
  GLfloat minx = (dstrect == NULL) ? 0.0f : dstrect->x;
  GLfloat miny = (dstrect == NULL) ? 0.0f : dstrect->y;
  GLfloat maxx = (dstrect == NULL) ? dsttex->width : dstrect->x + dstrect->w;
  GLfloat maxy = (dstrect == NULL) ? dsttex->height : dstrect->y + dstrect->h;
  
  minx = minx / dsttex->width * 2.0 - 1.0;
  miny = -(miny / dsttex->height * 2.0 - 1.0);
  maxx = maxx / dsttex->width * 2.0 - 1.0;
  maxy = -(maxy / dsttex->height * 2.0 - 1.0);
  
  GLfloat vertexbuffer_data[] = {
    minx, miny,
    maxx, miny,
    minx, maxy,
    maxx, maxy
  };
  GLuint vertexbuffer;
  glGenBuffers(1, &vertexbuffer);
  glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertexbuffer_data), vertexbuffer_data, GL_STATIC_DRAW);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
  
  GLfloat minu = (srcrect == NULL) ? 0.0f : srcrect->x;
  GLfloat minv = (srcrect == NULL) ? 0.0f : srcrect->y;
  GLfloat maxu = (srcrect == NULL) ? srctex->width : srcrect->x + srcrect->w;
  GLfloat maxv = (srcrect == NULL) ? srctex->height : srcrect->y + srcrect->h;
  
  minu = minu / srctex->width;
  minv = 1 - (minv / srctex->height);
  maxu = maxu / srctex->width;
  maxv = 1 - (maxv / srctex->height);
  
  GLfloat texcoordbuffer_data[] = {
    minu, minv,
    maxu, minv,
    minu, maxv,
    maxu, maxv
  };
  GLuint texcoordbuffer;
  glGenBuffers(1, &texcoordbuffer);
  glBindBuffer(GL_ARRAY_BUFFER, texcoordbuffer);
  glBufferData(GL_ARRAY_BUFFER, sizeof(texcoordbuffer_data), texcoordbuffer_data, GL_STATIC_DRAW);
  glEnableVertexAttribArray(1);
  glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
  
  // Set up the shader
  glUseProgram(blitShader);
  glViewport(0, 0, dsttex->width, dsttex->height);
  
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, srctex->texID);
  glUniform1i(glGetUniformLocation(blitShader, "srctex"), 0);
  
  // Blit!
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
  
  // Unload everything
  glDisableVertexAttribArray(1);
  glDisableVertexAttribArray(0);
  glDeleteBuffers(1, &texcoordbuffer);
  glDeleteBuffers(1, &vertexbuffer);
}

void renderScreen(Texture* tex)
{
  if (!rendererInitialized)
  {
    fprintf(stderr, "Renderer not initialized\n");
    exit(-1);
  }
  
  // First we're going to composite our frame with the previous frame
  // We start by setting up the framebuffer
  glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
  glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, renderedTexBufs[curBuf], 0);
  
  // Set up the shaer
  glViewport(0,0,GAME_WIDTH,GAME_HEIGHT);
  glClear(GL_COLOR_BUFFER_BIT);
  glUseProgram(ntscShader);
  
  // Use the current frame texture, nearest neighbor and clamped to edge
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, tex->texID);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glUniform1i(glGetUniformLocation(ntscShader, "curFrameSampler"), 0);
  
  // Use the previous frame composite texture, nearest neighbor and clamped to edge
  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, renderedTexBufs[(curBuf + 1) % 2]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glUniform1i(glGetUniformLocation(ntscShader, "prevFrameSampler"), 1);
  
  // Load the NTSC artifact texture
  glActiveTexture(GL_TEXTURE2);
  glBindTexture(GL_TEXTURE_2D, artifactsTex);
  glUniform1i(glGetUniformLocation(ntscShader, "NTSCArtifactSampler"), 2);
  glUniform1f(glGetUniformLocation(ntscShader, "NTSCLerp"), curBuf * 1.0);
  
  // Render our composition
  glEnableVertexAttribArray(0);
  glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
  glDrawArrays(GL_TRIANGLES, 0, 6);
  glDisableVertexAttribArray(0);

  // Load the normal vertices of a flat surface
  GLfloat g_norms_data[] = {
    0.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f
  };
  
  GLuint g_norms;
  glGenBuffers(1, &g_norms);
  glBindBuffer(GL_ARRAY_BUFFER, g_norms);
  glBufferData(GL_ARRAY_BUFFER, sizeof(g_norms_data), g_norms_data, GL_STATIC_DRAW);
  
  // We're going to render the screen now
  //glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, preBloomTex, 0);
  glViewport(0,0,1024,768);
  glClear(GL_COLOR_BUFFER_BIT);
  glUseProgram(finalShader);
  
  // Use the composited frame texture, linearly filtered and filling in black for the border
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, renderedTexBufs[curBuf]);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
  float border_color[] = {0.0f, 0.0f, 0.0f, 1.0f};
  glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border_color);
	glGenerateMipmap(GL_TEXTURE_2D);
  glUniform1i(glGetUniformLocation(finalShader, "rendertex"), 0);
  
  // Use the scanlines texture
  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, scanlinesTex);
  glUniform1i(glGetUniformLocation(finalShader, "scanlinestex"), 1);
  
  // Initialize the MVP matrices
  mat4 p_matrix = perspective(90.0f, 4.0f / 4.0f, 0.1f, 100.0f);
  mat4 v_matrix = lookAt(vec3(0,0,1), vec3(0,0,0), vec3(0,1,0));
  mat4 m_matrix = mat4(1.0f);
  mat4 mvp_matrix = p_matrix * v_matrix * m_matrix;
  //mat4 mv_matrix = v_matrix * m_matrix;
  
  glUniformMatrix4fv(glGetUniformLocation(finalShader, "MVP"), 1, GL_FALSE, &mvp_matrix[0][0]);
  glUniformMatrix4fv(glGetUniformLocation(finalShader, "worldMat"), 1, GL_FALSE, &m_matrix[0][0]);
  
  glEnableVertexAttribArray(0);
  glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
  
  glEnableVertexAttribArray(1);
  glBindBuffer(GL_ARRAY_BUFFER, g_norms);
  glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
  
  glDrawArrays(GL_TRIANGLES, 0, 6);
  glDisableVertexAttribArray(1);
  glDisableVertexAttribArray(0);
  
  // Do the first pass of bloom (downsampling and tapping)
  glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, bloomPassTex, 0);
  glViewport(0, 0, 64, 48);
  glClear(GL_COLOR_BUFFER_BIT);
  glUseProgram(bloom1Shader);
  
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, preBloomTex);
  glUniform1i(glGetUniformLocation(bloom1Shader, "screenTex"), 0);
  
  glUniform1f(glGetUniformLocation(bloom1Shader, "iGlobalTime"), glfwGetTime());
  
  glEnableVertexAttribArray(0);
  glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
  glDrawArrays(GL_TRIANGLES, 0, 6);
  glDisableVertexAttribArray(0);
  
  // Do the second pass of bloom and render to screen
  glBindFramebuffer(GL_FRAMEBUFFER, 0);
  glViewport(0, 0, 1024, 768);
  glClear(GL_COLOR_BUFFER_BIT);
  glUseProgram(bloom2Shader);
  
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, preBloomTex);
  glUniform1i(glGetUniformLocation(bloom2Shader, "screenTex"), 0);
  
  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, bloomPassTex);
  glUniform1i(glGetUniformLocation(bloom2Shader, "downsampledTex"), 1);
  
  glUniform1f(glGetUniformLocation(bloom2Shader, "iGlobalTime"), glfwGetTime());
  
  glEnableVertexAttribArray(0);
  glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
  glDrawArrays(GL_TRIANGLES, 0, 6);
  glDisableVertexAttribArray(0);
  
  glfwSwapBuffers(window);
  
  glDeleteBuffers(1, &g_norms);
  
  curBuf = (curBuf + 1) % 2;
}