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
|
#include "../utils/macros.h"
#include "canvas.h"
#include "window.h"
namespace jin
{
namespace render
{
Canvas::Canvas() :Drawable()
{
}
Canvas::~Canvas()
{
}
// no canvas has binded
shared GLint Canvas::cur = -1;
bool Canvas::init(int w, int h)
{
Drawable::init(w, h);
Drawable::setVertices(
new float [DRAWABLE_V_SIZE] {
0, 0,
0, (float)h,
(float)w, (float)h,
(float)w, 0,
},
new float [DRAWABLE_V_SIZE] {
0, 1,
0, 0,
1, 0,
1, 1
}
);
GLint current_fbo;
glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, ¤t_fbo);
// generate a new render buffer object
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
// generate texture save target
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glBindTexture(GL_TEXTURE_2D, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
// unbind framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, current_fbo);
if (status != GL_FRAMEBUFFER_COMPLETE_EXT)
return false;
return true;
}
bool Canvas::hasbind(GLint fbo)
{
return cur == fbo;
}
/**
* bind to canvas
*/
void Canvas::bind()
{
if (hasbind(fbo)) return;
cur = fbo;
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glViewport(0, 0, width, height);
glOrtho(0, width, height, 0, -1, 1);
// Switch back to modelview matrix
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
/**
* bind to default screen render buffer.
*/
shared void Canvas::unbind()
{
if (hasbind(0)) return;
cur = 0;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
Window* wnd = Window::get();
int ww = wnd->getW(),
wh = wnd->getH();
glViewport(0, 0, ww, wh);
// load back to normal
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
// set viewport matrix
glOrtho(0, ww, wh, 0, -1, 1);
// switch to model matrix
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
}
}
}
|