Debian Codegraph @

demos/gtk-demo/example_glarea.cc

raw
1 /* Open GL Area
2 *
3 * Gtk::GLArea is a widget that allows custom drawing using OpenGL calls.
4 *
5 */
6
7 #include <iostream>
8 #include <string>
9 #include <vector>
10
11 #include <gtkmm.h>
12 #include <giomm/resource.h>
13 #include <epoxy/gl.h>
14
15 using std::cerr;
16 using std::endl;
17 using std::string;
18
19 enum {
20 X_AXIS,
21 Y_AXIS,
22 Z_AXIS,
23
24 N_AXIS
25 };
26
27 static const GLfloat vertex_data[] = {
28 0.f, 0.5f, 0.f, 1.f,
29 0.5f, -0.366f, 0.f, 1.f,
30 -0.5f, -0.366f, 0.f, 1.f,
31 };
32
33 class Example_GLArea : public Gtk::Window
34 {
35 public:
36 Example_GLArea();
37 ~Example_GLArea() override;
38
39 protected:
40 // The m_GLContext must be deleted after m_GLArea, therefore declared before m_GLArea.
41 Glib::RefPtr<Gdk::GLContext> m_GLContext;
42 Gtk::Box m_VBox {Gtk::ORIENTATION_VERTICAL, false};
43 Gtk::GLArea m_GLArea;
44 Gtk::Box m_Controls {Gtk::ORIENTATION_VERTICAL, false};
45 Gtk::Button m_Button {"Quit"};
46
47 GLuint m_Vao {0};
48 GLuint m_Buffer {0};
49 GLuint m_Program {0};
50 GLuint m_Mvp {0};
51
52 std::vector<float> m_RotationAngles;
53
54 void on_axis_value_change(int axis, const Glib::RefPtr<Gtk::Adjustment>& adj);
55
56 void realize();
57 void unrealize();
58 bool render(const Glib::RefPtr<Gdk::GLContext>& context);
59
60 Gtk::Box* create_axis_slider_box(int axis);
61 void init_buffers();
62 void init_shaders(const std::string& vertex_path, const std::string& fragment_path);
63 void draw_triangle();
64 };
65
66 Gtk::Window* do_glarea()
67 {
68 return new Example_GLArea();
69 }
70
71 Example_GLArea::Example_GLArea() : m_RotationAngles(N_AXIS, 0.0f)
72 {
73 set_title("GL Area");
74 set_default_size(400, 600);
75 set_border_width(12);
76
77 m_VBox.set_spacing(6);
78 add(m_VBox);
79
80 m_GLArea.set_hexpand(true);
81 m_GLArea.set_vexpand(true);
82 m_GLArea.set_auto_render(true);
83 m_VBox.add(m_GLArea);
84
85 // Connect gl area signals
86 // Important that the realize signal calls our handler to clean up
87 // GL resources _after_ the default unrealize handler is called (the "true")
88 m_GLArea.signal_realize().connect(sigc::mem_fun(*this, &Example_GLArea::realize), true);
89 // Important that the unrealize signal calls our handler to clean up
90 // GL resources _before_ the default unrealize handler is called (the "false")
91 m_GLArea.signal_unrealize().connect(sigc::mem_fun(*this, &Example_GLArea::unrealize), false);
92 m_GLArea.signal_render().connect(sigc::mem_fun(*this, &Example_GLArea::render));
93
94 m_VBox.add(m_Controls);
95 m_Controls.set_hexpand(true);
96
97 for(int i = 0 ; i < N_AXIS ; ++i)
98 {
99 auto sliderBox = create_axis_slider_box(i);
100 m_Controls.add(*sliderBox);
101 }
102
103 m_Button.set_hexpand(true);
104 m_VBox.add(m_Button);
105 // Connect clicked to close of window
106 m_Button.signal_clicked().connect(sigc::mem_fun(*this, &Gtk::Window::close));
107
108 show_all();
109 }
110
111 Example_GLArea::~Example_GLArea()
112 {
113 }
114
115 void Example_GLArea::on_axis_value_change(int axis, const Glib::RefPtr<Gtk::Adjustment>& adj)
116 {
117 m_RotationAngles[axis] = adj->get_value();
118 m_GLArea.queue_draw();
119 }
120
121 void Example_GLArea::realize()
122 {
123 m_GLArea.make_current();
124 try
125 {
126 m_GLArea.throw_if_error();
127 init_buffers();
128
129 const bool use_es = m_GLArea.get_context()->get_use_es();
130 const std::string vertex_path = use_es ? "/glarea/glarea-gles.vs.glsl" : "/glarea/glarea-gl.vs.glsl";
131 const std::string fragment_path = use_es ? "/glarea/glarea-gles.fs.glsl" : "/glarea/glarea-gl.fs.glsl";
132 init_shaders(vertex_path, fragment_path);
133
134 // GtkGLArea can drop its reference on the GLContext before the unrealize signal
135 // is emitted. We get our own reference and keep it until Example_GLArea::unrealize()
136 // has been called, thus making sure the context is not prematurely deleted.
137 // https://gitlab.gnome.org/GNOME/gtkmm/issues/63
138 // m_GLContext is unnecessary if https://gitlab.gnome.org/GNOME/gtk/issues/2309
139 // is fixed as in gtk4.
140 m_GLContext = m_GLArea.get_context();
141 }
142 catch(const Gdk::GLError& gle)
143 {
144 cerr << "An error occured making the context current during realize:" << endl;
145 cerr << gle.domain() << "-" << gle.code() << "-" << gle.what() << endl;
146 }
147 }
148
149 void Example_GLArea::unrealize()
150 {
151 // Does nothing if GtkGLArea has dropped its reference on the GLContext.
152 m_GLArea.make_current();
153
154 if (m_GLContext)
155 // Necessary if m_GLArea.make_current() does nothing.
156 m_GLContext->make_current();
157
158 try
159 {
160 m_GLArea.throw_if_error();
161
162 // Delete buffers and program
163 glDeleteBuffers(1, &m_Buffer);
164 glDeleteProgram(m_Program);
165 }
166 catch(const Gdk::GLError& gle)
167 {
168 cerr << "An error occured making the context current during unrealize" << endl;
169 cerr << gle.domain() << "-" << gle.code() << "-" << gle.what() << endl;
170 }
171 }
172
173 bool Example_GLArea::render(const Glib::RefPtr<Gdk::GLContext>& /* context */)
174 {
175 try
176 {
177 m_GLArea.throw_if_error();
178 glClearColor(0.5, 0.5, 0.5, 1.0);
179 glClear(GL_COLOR_BUFFER_BIT);
180
181 draw_triangle();
182
183 glFlush();
184
185 return true;
186 }
187 catch(const Gdk::GLError& gle)
188 {
189 cerr << "An error occurred in the render callback of the GLArea" << endl;
190 cerr << gle.domain() << "-" << gle.code() << "-" << gle.what() << endl;
191 return false;
192 }
193 }
194
195 Gtk::Box* Example_GLArea::create_axis_slider_box(int axis)
196 {
197 auto box = Gtk::manage(new Gtk::Box{Gtk::ORIENTATION_HORIZONTAL, false});
198
199 const char* text;
200
201 switch(axis)
202 {
203 case X_AXIS:
204 {
205 text = "X axis";
206 break;
207 }
208 case Y_AXIS:
209 {
210 text = "Y axis";
211 break;
212 }
213 case Z_AXIS:
214 {
215 text = "Z axis";
216 break;
217 }
218 default:
219 {
220 g_assert_not_reached();
221 }
222 }
223
224 auto label = Gtk::manage(new Gtk::Label{text});
225 box->add(*label);
226 label->show();
227
228 auto adj = Gtk::Adjustment::create(0.0, 0.0, 360.0, 1.0, 12.0, 0.0);
229
230 adj->signal_value_changed().connect(
231 sigc::bind(sigc::mem_fun(*this, &Example_GLArea::on_axis_value_change), axis, adj)
232 );
233 auto slider = Gtk::manage(new Gtk::Scale{adj, Gtk::ORIENTATION_HORIZONTAL});
234 box->add(*slider);
235 slider->set_hexpand(true);
236 slider->show();
237
238 box->show();
239
240 return box;
241 }
242
243 void Example_GLArea::init_buffers()
244 {
245 glGenVertexArrays(1, &m_Vao);
246 glBindVertexArray(m_Vao);
247
248 glGenBuffers(1, &m_Buffer);
249 glBindBuffer(GL_ARRAY_BUFFER, m_Buffer);
250 glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW);
251 glBindBuffer(GL_ARRAY_BUFFER, 0);
252 }
253
254 static GLuint create_shader(int type, const char *src)
255 {
256 auto shader = glCreateShader(type);
257 glShaderSource(shader, 1, &src, nullptr);
258 glCompileShader(shader);
259
260 int status;
261 glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
262 if(status == GL_FALSE)
263 {
264 int log_len;
265 glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_len);
266
267 string log_space(log_len+1, ' ');
268 glGetShaderInfoLog(shader, log_len, nullptr, (GLchar*)log_space.c_str());
269
270 cerr << "Compile failure in " <<
271 (type == GL_VERTEX_SHADER ? "vertex" : "fragment") <<
272 " shader: " << log_space << endl;
273
274 glDeleteShader(shader);
275
276 return 0;
277 }
278
279 return shader;
280 }
281
282 void Example_GLArea::init_shaders(const std::string& vertex_path, const std::string& fragment_path)
283 {
284 auto vshader_bytes = Gio::Resource::lookup_data_global(vertex_path);
285 if(!vshader_bytes)
286 {
287 cerr << "Failed fetching vertex shader resource" << endl;
288 m_Program = 0;
289 return;
290 }
291 gsize vshader_size {vshader_bytes->get_size()};
292 auto vertex = create_shader(GL_VERTEX_SHADER,
293 (const char*)vshader_bytes->get_data(vshader_size));
294
295 if(vertex == 0)
296 {
297 m_Program = 0;
298 return;
299 }
300
301 auto fshader_bytes = Gio::Resource::lookup_data_global(fragment_path);
302 if(!fshader_bytes)
303 {
304 cerr << "Failed fetching fragment shader resource" << endl;
305 glDeleteShader(vertex);
306 m_Program = 0;
307 return;
308 }
309 gsize fshader_size {fshader_bytes->get_size()};
310 auto fragment = create_shader(GL_FRAGMENT_SHADER,
311 (const char*)fshader_bytes->get_data(fshader_size));
312
313 if(fragment == 0)
314 {
315 glDeleteShader(vertex);
316 m_Program = 0;
317 return;
318 }
319
320 m_Program = glCreateProgram();
321 glAttachShader(m_Program, vertex);
322 glAttachShader(m_Program, fragment);
323
324 glLinkProgram(m_Program);
325
326 int status;
327 glGetProgramiv(m_Program, GL_LINK_STATUS, &status);
328 if(status == GL_FALSE)
329 {
330 int log_len;
331 glGetProgramiv(m_Program, GL_INFO_LOG_LENGTH, &log_len);
332
333 string log_space(log_len+1, ' ');
334 glGetProgramInfoLog(m_Program, log_len, nullptr, (GLchar*)log_space.c_str());
335
336 cerr << "Linking failure: " << log_space << endl;
337
338 glDeleteProgram(m_Program);
339 m_Program = 0;
340 }
341 else
342 {
343 /* Get the location of the "mvp" uniform */
344 m_Mvp = glGetUniformLocation(m_Program, "mvp");
345
346 glDetachShader(m_Program, vertex);
347 glDetachShader(m_Program, fragment);
348 }
349 glDeleteShader(vertex);
350 glDeleteShader(fragment);
351 }
352
353 static void compute_mvp(float *res,
354 float phi,
355 float theta,
356 float psi)
357 {
358 float x {phi * ((float)G_PI / 180.f)};
359 float y {theta * ((float)G_PI / 180.f)};
360 float z {psi * ((float)G_PI / 180.f)};
361 float c1 {cosf (x)};
362 float s1 {sinf (x)};
363 float c2 {cosf (y)};
364 float s2 {sinf (y)};
365 float c3 {cosf (z)};
366 float s3 {sinf (z)};
367 float c3c2 {c3 * c2};
368 float s3c1 {s3 * c1};
369 float c3s2s1 {c3 * s2 * s1};
370 float s3s1 {s3 * s1};
371 float c3s2c1 {c3 * s2 * c1};
372 float s3c2 {s3 * c2};
373 float c3c1 {c3 * c1};
374 float s3s2s1 {s3 * s2 * s1};
375 float c3s1 {c3 * s1};
376 float s3s2c1 {s3 * s2 * c1};
377 float c2s1 {c2 * s1};
378 float c2c1 {c2 * c1};
379
380 /* apply all three rotations using the three matrices:
381 *
382 * ⎡ c3 s3 0 ⎤ ⎡ c2 0 -s2 ⎤ ⎡ 1 0 0 ⎤
383 * ⎢ -s3 c3 0 ⎥ ⎢ 0 1 0 ⎥ ⎢ 0 c1 s1 ⎥
384 * ⎣ 0 0 1 ⎦ ⎣ s2 0 c2 ⎦ ⎣ 0 -s1 c1 ⎦
385 */
386 res[0] = c3c2; res[4] = s3c1 + c3s2s1; res[8] = s3s1 - c3s2c1; res[12] = 0.f;
387 res[1] = -s3c2; res[5] = c3c1 - s3s2s1; res[9] = c3s1 + s3s2c1; res[13] = 0.f;
388 res[2] = s2; res[6] = -c2s1; res[10] = c2c1; res[14] = 0.f;
389 res[3] = 0.f; res[7] = 0.f; res[11] = 0.f; res[15] = 1.f;
390 }
391
392 void Example_GLArea::draw_triangle()
393 {
394 float mvp[16];
395
396 compute_mvp(mvp,
397 m_RotationAngles[X_AXIS],
398 m_RotationAngles[Y_AXIS],
399 m_RotationAngles[Z_AXIS]);
400
401 glUseProgram(m_Program);
402
403 glUniformMatrix4fv(m_Mvp, 1, GL_FALSE, &mvp[0]);
404
405 glBindBuffer(GL_ARRAY_BUFFER, m_Buffer);
406 glEnableVertexAttribArray(0);
407 glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, nullptr);
408
409 glDrawArrays(GL_TRIANGLES, 0, 3);
410
411 glDisableVertexAttribArray(0);
412 glBindBuffer(GL_ARRAY_BUFFER, 0);
413 glUseProgram(0);
414 }