Console Update
[tar-legacy.git] / MCDV / FrameBuffer.hpp
1 #pragma once
2 #include <glad\glad.h>
3 #include <GLFW\glfw3.h>
4 #include <iostream>
5 #include <fstream>
6 #include <sstream>
7 #include <vector>
8
9 #include "GLFWUtil.hpp"
10
11 #define STBI_MSC_SECURE_CRT
12 #define STB_IMAGE_WRITE_IMPLEMENTATION
13 #include "stb_image_write.h"
14
15
16 class FrameBuffer {
17 public:
18 unsigned int fbo;
19 unsigned int rbo;
20 unsigned int texture;
21
22 FrameBuffer(bool depthtest = true) {
23 glGenFramebuffers(1, &this->fbo); //Generate frame buffer
24 glBindFramebuffer(GL_FRAMEBUFFER, this->fbo);
25
26 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) {
27
28 glGenTextures(1, &this->texture);
29 glBindTexture(GL_TEXTURE_2D, this->texture);
30 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 1024, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
31
32 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
33 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
34 glBindTexture(GL_TEXTURE_2D, 0);
35
36 //attach
37 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->texture, 0);
38
39 if (depthtest)
40 {
41 glGenRenderbuffers(1, &this->rbo);
42 glBindRenderbuffer(GL_RENDERBUFFER, this->rbo);
43 glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, 1024, 1024);
44 glBindRenderbuffer(GL_RENDERBUFFER, 0);
45
46 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->rbo);
47 }
48
49 if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
50 std::cout << "Framebuffer failed to generate" << std::endl;
51 }
52
53 FrameBuffer::Unbind();
54 }
55
56 void Bind() {
57 glBindFramebuffer(GL_FRAMEBUFFER, this->fbo);
58 }
59
60 void Save() {
61 void* data = malloc(3 * 1024 * 1024);
62 glReadPixels(0, 0, 1024, 1024, GL_RGB, GL_UNSIGNED_BYTE, data);
63
64 if (data != 0)
65 stbi_write_png("test.png", 1024, 1024, 3, data, 1024 * 3);
66 else
67 std::cout << "Something went wrong making render" << std::endl;
68 }
69
70 static void Unbind() {
71 glBindFramebuffer(GL_FRAMEBUFFER, 0); //Revert to default framebuffer
72 }
73
74 ~FrameBuffer() {
75 glDeleteFramebuffers(1, &this->fbo);
76 }
77 };