goat3d

view goatview/src/goatview.cc @ 92:ae6c5941faac

[goatview] makefile rules to create app bundle and dmg archive [goatview] creating multisampling context
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 18 May 2014 01:19:10 +0300
parents 8b156bc5205b
children 07c0ec4a410d
line source
1 #include <stdio.h>
2 #include <map>
3 #include "opengl.h"
4 #include <QtOpenGL/QtOpenGL>
5 #include <vmath/vmath.h>
6 #include "goatview.h"
7 #include "goat3d.h"
9 static void draw_grid();
10 static void draw_grid(float sz, int nlines, float alpha = 1.0f);
11 static void draw_node(goat3d_node *node);
12 static void draw_mesh(goat3d_mesh *mesh);
13 static int next_pow2(int x);
15 goat3d *scene;
16 static SceneModel *sdata;
17 static GoatViewport *glview;
19 static long anim_time;
20 static float cam_theta, cam_phi = 25, cam_dist = 8;
21 static float fov = 60.0;
22 static bool use_nodes = true;
23 static bool use_lighting = true;
24 static bool use_textures = true;
26 void post_redisplay()
27 {
28 if(glview) {
29 glview->updateGL();
30 }
31 }
34 GoatView::GoatView()
35 {
36 glview = 0;
37 scene_model = 0;
39 QGLFormat glfmt = QGLFormat::defaultFormat();
40 glfmt.setSampleBuffers(true);
41 QGLFormat::setDefaultFormat(glfmt);
43 QSettings settings;
44 resize(settings.value("main/size", QSize(1024, 768)).toSize());
45 move(settings.value("main/pos", QPoint(100, 100)).toPoint());
46 use_nodes = settings.value("use_nodes", true).toBool();
47 use_lighting = settings.value("use_lighting", true).toBool();
48 use_textures = settings.value("use_textures", true).toBool();
50 make_center(); // must be first
51 make_menu();
52 make_dock();
54 statusBar();
56 setWindowTitle("GoatView");
57 }
59 GoatView::~GoatView()
60 {
61 delete scene_model;
62 sdata = 0;
63 }
65 void GoatView::closeEvent(QCloseEvent *ev)
66 {
67 QSettings settings;
68 settings.setValue("main/size", size());
69 settings.setValue("main/pos", pos());
70 settings.setValue("use_nodes", use_nodes);
71 settings.setValue("use_lighting", use_lighting);
72 }
75 bool GoatView::load_scene(const char *fname)
76 {
77 if(scene) {
78 goat3d_free(scene);
79 }
80 if(!(scene = goat3d_create()) || goat3d_load(scene, fname) == -1) {
81 return false;
82 }
84 float bmin[3], bmax[3];
85 if(goat3d_get_bounds(scene, bmin, bmax) != -1) {
86 float bsize = (Vector3(bmax[0], bmax[1], bmax[2]) - Vector3(bmin[0], bmin[1], bmin[2])).length();
87 cam_dist = bsize / tan(DEG_TO_RAD(fov) / 2.0);
88 printf("bounds size: %f, cam_dist: %f\n", bsize, cam_dist);
89 }
91 scene_model->set_scene(scene);
92 treeview->expandAll();
93 treeview->resizeColumnToContents(0);
95 sdata = scene_model; // set the global sdata ptr
96 return true;
97 }
99 bool GoatView::make_menu()
100 {
101 // file menu
102 QMenu *menu_file = menuBar()->addMenu("&File");
104 QAction *act_open_sce = new QAction("&Open Scene", this);
105 act_open_sce->setShortcuts(QKeySequence::Open);
106 connect(act_open_sce, &QAction::triggered, this, &GoatView::open_scene);
107 menu_file->addAction(act_open_sce);
109 QAction *act_open_anm = new QAction("Open &Animation", this);
110 connect(act_open_anm, &QAction::triggered, this, &GoatView::open_anim);
111 menu_file->addAction(act_open_anm);
113 QAction *act_quit = new QAction("&Quit", this);
114 act_quit->setShortcuts(QKeySequence::Quit);
115 connect(act_quit, &QAction::triggered, [&](){ qApp->quit(); });
116 menu_file->addAction(act_quit);
118 // view menu
119 QMenu *menu_view = menuBar()->addMenu("&View");
121 QAction *act_use_nodes = new QAction("use nodes", this);
122 act_use_nodes->setCheckable(true);
123 act_use_nodes->setChecked(use_nodes);
124 connect(act_use_nodes, &QAction::triggered, this,
125 [&](){ use_nodes = !use_nodes; post_redisplay(); });
126 menu_view->addAction(act_use_nodes);
128 QAction *act_use_lighting = new QAction("lighting", this);
129 act_use_lighting->setCheckable(true);
130 act_use_lighting->setChecked(use_lighting);
131 connect(act_use_lighting, &QAction::triggered, glview, &GoatViewport::toggle_lighting);
132 menu_view->addAction(act_use_lighting);
134 // help menu
135 QMenu *menu_help = menuBar()->addMenu("&Help");
137 QAction *act_about = new QAction("&About", this);
138 connect(act_about, &QAction::triggered, this, &GoatView::show_about);
139 menu_help->addAction(act_about);
140 return true;
141 }
143 bool GoatView::make_dock()
144 {
145 // ---- side-dock ----
146 QWidget *dock_cont = new QWidget;
147 QVBoxLayout *dock_vbox = new QVBoxLayout;
148 dock_cont->setLayout(dock_vbox);
150 QDockWidget *dock = new QDockWidget(this);
151 dock->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
152 dock->setWidget(dock_cont);
153 addDockWidget(Qt::LeftDockWidgetArea, dock);
155 // make the tree view widget
156 treeview = new QTreeView;
157 treeview->setAlternatingRowColors(true);
158 treeview->setSelectionMode(QAbstractItemView::SingleSelection);
159 dock_vbox->addWidget(treeview);
161 scene_model = new SceneModel;
162 connect(scene_model, &SceneModel::dataChanged, [&](){ post_redisplay(); });
163 treeview->setModel(scene_model);
165 connect(treeview->selectionModel(), &QItemSelectionModel::selectionChanged,
166 [&](){ scene_model->selchange(treeview->selectionModel()->selectedIndexes()); });
168 // misc
169 QPushButton *bn_quit = new QPushButton("quit");
170 dock_vbox->addWidget(bn_quit);
171 connect(bn_quit, &QPushButton::clicked, [&](){ qApp->quit(); });
173 // ---- bottom dock ----
174 dock_cont = new QWidget;
175 QHBoxLayout *dock_hbox = new QHBoxLayout;
176 dock_cont->setLayout(dock_hbox);
178 // animation control box
179 QGridLayout *anim_ctl_box = new QGridLayout;
180 dock_hbox->addLayout(anim_ctl_box);
182 anim_ctl_box->addWidget(new QLabel("Animation"), 0, 0);
183 cbox_anims = new QComboBox;
184 cbox_anims->setDisabled(true);
185 anim_ctl_box->addWidget(cbox_anims, 0, 1);
187 chk_loop = new QCheckBox("loop");
188 chk_loop->setChecked(false);
189 anim_ctl_box->addWidget(chk_loop, 1, 0);
191 QToolBar *toolbar_ctl = new QToolBar;
192 anim_ctl_box->addWidget(toolbar_ctl, 1, 1);
194 act_rewind = new QAction(style()->standardIcon(QStyle::SP_MediaSkipBackward), "Rewind", this);
195 act_rewind->setDisabled(true);
196 toolbar_ctl->addAction(act_rewind);
197 act_play = new QAction(style()->standardIcon(QStyle::SP_MediaPlay), "Play", this);
198 act_play->setDisabled(true);
199 toolbar_ctl->addAction(act_play);
201 // timeline slider
202 slider_time = new QSlider(Qt::Orientation::Horizontal);
203 slider_time->setDisabled(true);
204 connect(slider_time, &QSlider::valueChanged,
205 [&](){ anim_time = slider_time->value(); post_redisplay(); });
206 dock_hbox->addWidget(slider_time);
208 dock = new QDockWidget(this);
209 dock->setAllowedAreas(Qt::BottomDockWidgetArea);
210 dock->setWidget(dock_cont);
211 addDockWidget(Qt::BottomDockWidgetArea, dock);
213 return true;
214 }
216 bool GoatView::make_center()
217 {
218 glview = ::glview = new GoatViewport(this);
219 setCentralWidget(glview);
220 return true;
221 }
223 void GoatView::open_scene()
224 {
225 std::string fname = QFileDialog::getOpenFileName(this, "Open scene file", "",
226 "Goat3D Scene (*.goatsce);;All Files (*)").toStdString();
227 if(fname.empty()) {
228 statusBar()->showMessage("Abort: No file selected!");
229 return;
230 }
232 statusBar()->showMessage("opening scene file");
233 if(!load_scene(fname.c_str())) {
234 statusBar()->showMessage("failed to load scene file");
235 }
236 }
238 void GoatView::open_anim()
239 {
240 statusBar()->showMessage("opening animation...");
241 }
244 // ---- OpenGL viewport ----
245 GoatViewport::GoatViewport(QWidget *main_win)
246 : QGLWidget(QGLFormat(QGL::DepthBuffer | QGL::SampleBuffers))
247 {
248 this->main_win = main_win;
249 initialized = false;
250 }
252 GoatViewport::~GoatViewport()
253 {
254 }
256 QSize GoatViewport::sizeHint() const
257 {
258 return QSize(800, 600);
259 }
261 #define CRITICAL(error, detail) \
262 do { \
263 fprintf(stderr, "%s: %s\n", error, detail); \
264 QMessageBox::critical(main_win, error, detail); \
265 abort(); \
266 } while(0)
268 void GoatViewport::initializeGL()
269 {
270 if(initialized) return;
271 initialized = true;
273 init_opengl();
275 if(!GLEW_ARB_transpose_matrix) {
276 CRITICAL("OpenGL initialization failed", "ARB_transpose_matrix extension not found!");
277 }
279 glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
281 glEnable(GL_DEPTH_TEST);
282 glEnable(GL_CULL_FACE);
283 if(use_lighting) {
284 glEnable(GL_LIGHTING);
285 }
286 glEnable(GL_LIGHT0);
288 float ldir[] = {-1, 1, 2, 0};
289 glLightfv(GL_LIGHT0, GL_POSITION, ldir);
291 glEnable(GL_MULTISAMPLE);
292 }
294 void GoatViewport::resizeGL(int xsz, int ysz)
295 {
296 glViewport(0, 0, xsz, ysz);
297 glMatrixMode(GL_PROJECTION);
298 glLoadIdentity();
299 gluPerspective(60.0, (float)xsz / (float)ysz, 0.5, 5000.0);
300 }
302 void GoatViewport::paintGL()
303 {
304 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
306 glMatrixMode(GL_MODELVIEW);
307 glLoadIdentity();
308 glTranslatef(0, 0, -cam_dist);
309 glRotatef(cam_phi, 1, 0, 0);
310 glRotatef(cam_theta, 0, 1, 0);
312 draw_grid();
314 if(!scene) return;
316 if(use_nodes) {
317 int node_count = goat3d_get_node_count(scene);
318 for(int i=0; i<node_count; i++) {
319 goat3d_node *node = goat3d_get_node(scene, i);
320 if(!goat3d_get_node_parent(node)) {
321 draw_node(node); // only draw root nodes, the rest will be drawn recursively
322 }
323 }
324 } else {
325 int mesh_count = goat3d_get_mesh_count(scene);
326 for(int i=0; i<mesh_count; i++) {
327 goat3d_mesh *mesh = goat3d_get_mesh(scene, i);
328 draw_mesh(mesh);
329 }
330 }
331 }
333 void GoatViewport::toggle_lighting()
334 {
335 use_lighting = !use_lighting;
336 if(use_lighting) {
337 glEnable(GL_LIGHTING);
338 } else {
339 glDisable(GL_LIGHTING);
340 }
341 updateGL();
342 }
344 #ifndef GLEW_ARB_transpose_matrix
345 #error "GLEW_ARB_transpose_matrix undefined?"
346 #endif
348 static void draw_grid()
349 {
350 float viewsz_orig = cam_dist * tan(DEG_TO_RAD(fov) / 2.0);
351 float sz1 = next_pow2((int)viewsz_orig);
352 float sz0 = sz1 / 2.0;
353 float t = (viewsz_orig - sz0) / (sz1 - sz0);
354 float alpha = t < 0.333333 ? 0.0 : (t > 0.666666 ? 1.0 : (t - 0.333333) / 0.333333);
356 glPushAttrib(GL_ENABLE_BIT | GL_DEPTH_BITS);
358 glEnable(GL_BLEND);
359 glDepthFunc(GL_ALWAYS);
361 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
362 draw_grid(sz0 * 2.0, 10, 1.0 - alpha);
363 draw_grid(sz1 * 2.0, 10, alpha);
365 glPopAttrib();
366 }
368 static void draw_grid(float sz, int nlines, float alpha)
369 {
370 float hsz = sz / 2.0;
371 float offs = sz / (float)nlines;
373 glPushAttrib(GL_ENABLE_BIT);
374 glDisable(GL_LIGHTING);
375 glDisable(GL_TEXTURE_2D);
377 glLineWidth(2.0);
378 glBegin(GL_LINES);
379 glColor4f(1, 0, 0, alpha);
380 glVertex3f(-hsz, 0, 0);
381 glVertex3f(hsz, 0, 0);
382 glColor4f(0, 0, 1, alpha);
383 glVertex3f(0, 0, -hsz);
384 glVertex3f(0, 0, hsz);
385 glEnd();
387 glLineWidth(1.0);
388 glBegin(GL_LINES);
389 glColor4f(0.5, 0.5, 0.5, alpha);
390 for(int i=0; i<nlines / 2; i++) {
391 float dist = (float)(i + 1) * offs;
392 for(int j=0; j<2; j++) {
393 float sign = j > 0 ? -1.0 : 1.0;
394 glVertex3f(-hsz, 0, dist * sign);
395 glVertex3f(hsz, 0, dist * sign);
396 glVertex3f(dist * sign, 0, -hsz);
397 glVertex3f(dist * sign, 0, hsz);
398 }
399 }
400 glEnd();
402 glPopAttrib();
403 }
405 static void draw_node(goat3d_node *node)
406 {
407 SceneNodeData *data = sdata ? sdata->get_node_data(node) : 0;
408 if(!data) return;
410 float xform[16];
411 goat3d_get_node_matrix(node, xform, anim_time);
413 glPushMatrix();
414 glMultTransposeMatrixf(xform);
416 if(data->visible) {
417 if(goat3d_get_node_type(node) == GOAT3D_NODE_MESH) {
418 goat3d_mesh *mesh = (goat3d_mesh*)goat3d_get_node_object(node);
420 draw_mesh(mesh);
422 if(data->selected) {
423 float bmin[3], bmax[3];
424 goat3d_get_mesh_bounds(mesh, bmin, bmax);
426 glPushAttrib(GL_ENABLE_BIT);
427 glDisable(GL_LIGHTING);
429 glColor3f(0.3, 1, 0.2);
431 glBegin(GL_LINE_LOOP);
432 glVertex3f(bmin[0], bmin[1], bmin[2]);
433 glVertex3f(bmax[0], bmin[1], bmin[2]);
434 glVertex3f(bmax[0], bmin[1], bmax[2]);
435 glVertex3f(bmin[0], bmin[1], bmax[2]);
436 glEnd();
437 glBegin(GL_LINE_LOOP);
438 glVertex3f(bmin[0], bmax[1], bmin[2]);
439 glVertex3f(bmax[0], bmax[1], bmin[2]);
440 glVertex3f(bmax[0], bmax[1], bmax[2]);
441 glVertex3f(bmin[0], bmax[1], bmax[2]);
442 glEnd();
443 glBegin(GL_LINES);
444 glVertex3f(bmin[0], bmin[1], bmin[2]);
445 glVertex3f(bmin[0], bmax[1], bmin[2]);
446 glVertex3f(bmin[0], bmin[1], bmax[2]);
447 glVertex3f(bmin[0], bmax[1], bmax[2]);
448 glVertex3f(bmax[0], bmin[1], bmin[2]);
449 glVertex3f(bmax[0], bmax[1], bmin[2]);
450 glVertex3f(bmax[0], bmin[1], bmax[2]);
451 glVertex3f(bmax[0], bmax[1], bmax[2]);
452 glEnd();
454 glPopAttrib();
455 }
456 }
457 }
459 int num_child = goat3d_get_node_child_count(node);
460 for(int i=0; i<num_child; i++) {
461 draw_node(goat3d_get_node_child(node, i));
462 }
464 glPopMatrix();
465 }
467 static void draw_mesh(goat3d_mesh *mesh)
468 {
469 static const float white[] = {1, 1, 1, 1};
470 static const float black[] = {0, 0, 0, 1};
472 const float *color;
473 goat3d_material *mtl = goat3d_get_mesh_mtl(mesh);
475 if(mtl && (color = goat3d_get_mtl_attrib(mtl, GOAT3D_MAT_ATTR_DIFFUSE))) {
476 glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
477 glColor3fv(color);
478 } else {
479 glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, white);
480 glColor3fv(white);
481 }
482 if(mtl && (color = goat3d_get_mtl_attrib(mtl, GOAT3D_MAT_ATTR_SPECULAR))) {
483 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, color);
484 } else {
485 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, black);
486 }
487 if(mtl && (color = goat3d_get_mtl_attrib(mtl, GOAT3D_MAT_ATTR_SHININESS))) {
488 glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, color[0]);
489 } else {
490 glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 60.0);
491 }
492 // TODO texture
495 int num_faces = goat3d_get_mesh_face_count(mesh);
496 int num_verts = goat3d_get_mesh_attrib_count(mesh, GOAT3D_MESH_ATTR_VERTEX);
498 glEnableClientState(GL_VERTEX_ARRAY);
499 glVertexPointer(3, GL_FLOAT, 0, goat3d_get_mesh_attribs(mesh, GOAT3D_MESH_ATTR_VERTEX));
501 float *data;
502 if((data = (float*)goat3d_get_mesh_attribs(mesh, GOAT3D_MESH_ATTR_NORMAL))) {
503 glEnableClientState(GL_NORMAL_ARRAY);
504 glNormalPointer(GL_FLOAT, 0, data);
505 }
506 if((data = (float*)goat3d_get_mesh_attribs(mesh, GOAT3D_MESH_ATTR_TEXCOORD))) {
507 glEnableClientState(GL_TEXTURE_COORD_ARRAY);
508 glTexCoordPointer(2, GL_FLOAT, 0, data);
509 }
511 int *indices;
512 if((indices = goat3d_get_mesh_faces(mesh))) {
513 glDrawElements(GL_TRIANGLES, num_faces * 3, GL_UNSIGNED_INT, indices);
514 } else {
515 glDrawArrays(GL_TRIANGLES, 0, num_verts * 3);
516 }
518 glDisableClientState(GL_VERTEX_ARRAY);
519 glDisableClientState(GL_NORMAL_ARRAY);
520 glDisableClientState(GL_TEXTURE_COORD_ARRAY);
521 }
524 static float prev_x, prev_y;
525 void GoatViewport::mousePressEvent(QMouseEvent *ev)
526 {
527 prev_x = ev->x();
528 prev_y = ev->y();
529 }
531 void GoatViewport::mouseMoveEvent(QMouseEvent *ev)
532 {
533 int dx = ev->x() - prev_x;
534 int dy = ev->y() - prev_y;
535 prev_x = ev->x();
536 prev_y = ev->y();
538 if(!dx && !dy) return;
540 if(ev->buttons() & Qt::LeftButton) {
541 cam_theta += dx * 0.5;
542 cam_phi += dy * 0.5;
544 if(cam_phi < -90) cam_phi = -90;
545 if(cam_phi > 90) cam_phi = 90;
546 }
547 if(ev->buttons() & Qt::RightButton) {
548 cam_dist += dy * 0.1;
550 if(cam_dist < 0.0) cam_dist = 0.0;
551 }
552 updateGL();
553 }
555 static const char *about_str =
556 "GoatView - Goat3D scene file viewer<br>"
557 "Copyright (C) 2014 John Tsiombikas &lt;<a href=\"mailto:nuclear@mutantstargoat.com\">nuclear@mutantstargoat.com</a>&gt;<br>"
558 "<br>"
559 "This program is free software: you can redistribute it and/or modify<br>"
560 "it under the terms of the GNU General Public License as published by<br>"
561 "the Free Software Foundation, either version 3 of the License, or<br>"
562 "(at your option) any later version.<br>"
563 "<br>"
564 "This program is distributed in the hope that it will be useful,<br>"
565 "but WITHOUT ANY WARRANTY; without even the implied warranty of<br>"
566 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>"
567 "GNU General Public License for more details.<br>"
568 "<br>"
569 "You should have received a copy of the GNU General Public License<br>"
570 "along with this program. If not, see <a href=\"http://www.gnu.org/licenses/gpl\">http://www.gnu.org/licenses/gpl</a>.";
572 void GoatView::show_about()
573 {
574 QMessageBox::information(this, "About GoatView", about_str);
575 }
578 static int next_pow2(int x)
579 {
580 x--;
581 x = (x >> 1) | x;
582 x = (x >> 2) | x;
583 x = (x >> 4) | x;
584 x = (x >> 8) | x;
585 x = (x >> 16) | x;
586 return x + 1;
587 }