source: git/src/gla-gl.cc@ bb3d137

stereo
Last change on this file since bb3d137 was bb3d137, checked in by Olly Betts <olly@…>, 8 years ago

WIP

  • Property mode set to 100644
File size: 48.6 KB
Line 
1//
2// gla-gl.cc
3//
4// OpenGL implementation for the GLA abstraction layer.
5//
6// Copyright (C) 2002-2003,2005 Mark R. Shinwell
7// Copyright (C) 2003,2004,2005,2006,2007,2010,2011,2012,2013,2014,2015,2017,2018 Olly Betts
8//
9// This program is free software; you can redistribute it and/or modify
10// it under the terms of the GNU General Public License as published by
11// the Free Software Foundation; either version 2 of the License, or
12// (at your option) any later version.
13//
14// This program is distributed in the hope that it will be useful,
15// but WITHOUT ANY WARRANTY; without even the implied warranty of
16// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17// GNU General Public License for more details.
18//
19// You should have received a copy of the GNU General Public License
20// along with this program; if not, write to the Free Software
21// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22//
23
24#ifdef HAVE_CONFIG_H
25#include <config.h>
26#endif
27
28#include <wx/confbase.h>
29#include <wx/image.h>
30
31#include <algorithm>
32
33#include "aven.h"
34#include "gla.h"
35#include "message.h"
36#include "useful.h"
37
38#ifdef HAVE_GL_GL_H
39# include <GL/gl.h>
40#elif defined HAVE_OPENGL_GL_H
41# include <OpenGL/gl.h>
42#endif
43
44#ifdef HAVE_GL_GLEXT_H
45# include <GL/glext.h>
46#elif defined HAVE_OPENGL_GLEXT_H
47# include <OpenGL/glext.h>
48#endif
49
50#ifndef GL_POINT_SIZE_MAX
51#define GL_POINT_SIZE_MAX 0x8127
52#endif
53#ifndef GL_POINT_SPRITE
54#define GL_POINT_SPRITE 0x8861
55#endif
56#ifndef GL_COORD_REPLACE
57#define GL_COORD_REPLACE 0x8862
58#endif
59// GL_POINT_SIZE_RANGE is deprecated in OpenGL 1.2 and later, and replaced by
60// GL_SMOOTH_POINT_SIZE_RANGE.
61#ifndef GL_SMOOTH_POINT_SIZE_RANGE
62#define GL_SMOOTH_POINT_SIZE_RANGE GL_POINT_SIZE_RANGE
63#endif
64// GL_POINT_SIZE_GRANULARITY is deprecated in OpenGL 1.2 and later, and
65// replaced by GL_SMOOTH_POINT_SIZE_GRANULARITY.
66#ifndef GL_SMOOTH_POINT_SIZE_GRANULARITY
67#define GL_SMOOTH_POINT_SIZE_GRANULARITY GL_POINT_SIZE_GRANULARITY
68#endif
69// GL_ALIASED_POINT_SIZE_RANGE was added in OpenGL 1.2.
70#ifndef GL_ALIASED_POINT_SIZE_RANGE
71#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
72#endif
73
74using namespace std;
75
76const int BLOB_DIAMETER = 5;
77
78#define BLOB_TEXTURE \
79 o, o, o, o, o, o, o, o,\
80 o, o, o, o, o, o, o, o,\
81 o, o, I, I, I, o, o, o,\
82 o, I, I, I, I, I, o, o,\
83 o, I, I, I, I, I, o, o,\
84 o, I, I, I, I, I, o, o,\
85 o, o, I, I, I, o, o, o,\
86 o, o, o, o, o, o, o, o
87
88#define CROSS_TEXTURE \
89 o, o, o, o, o, o, o, o,\
90 I, o, o, o, o, o, I, o,\
91 o, I, o, o, o, I, o, o,\
92 o, o, I, o, I, o, o, o,\
93 o, o, o, I, o, o, o, o,\
94 o, o, I, o, I, o, o, o,\
95 o, I, o, o, o, I, o, o,\
96 I, o, o, o, o, o, I, o
97
98static bool opengl_initialised = false;
99
100string GetGLSystemDescription()
101{
102 // If OpenGL isn't initialised we may get a SEGV from glGetString.
103 if (!opengl_initialised)
104 return "No OpenGL information available yet - try opening a file.";
105 const char *p = (const char*)glGetString(GL_VERSION);
106 if (!p)
107 return "Couldn't read OpenGL version!";
108
109 string info;
110 info += "OpenGL ";
111 info += p;
112 info += '\n';
113 info += (const char*)glGetString(GL_VENDOR);
114 info += '\n';
115 info += (const char*)glGetString(GL_RENDERER);
116#if defined __WXGTK__ || defined __WXX11__ || defined __WXMOTIF__
117 info += string_format("\nGLX %0.1f\n", wxGLCanvas::GetGLXVersion() * 0.1);
118#else
119 info += '\n';
120#endif
121
122 GLint red, green, blue;
123 glGetIntegerv(GL_RED_BITS, &red);
124 glGetIntegerv(GL_GREEN_BITS, &green);
125 glGetIntegerv(GL_BLUE_BITS, &blue);
126 GLint max_texture_size;
127 glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size);
128 GLint max_viewport[2];
129 glGetIntegerv(GL_MAX_VIEWPORT_DIMS, max_viewport);
130 GLdouble point_size_range[2];
131 glGetDoublev(GL_SMOOTH_POINT_SIZE_RANGE, point_size_range);
132 GLdouble point_size_granularity;
133 glGetDoublev(GL_SMOOTH_POINT_SIZE_GRANULARITY, &point_size_granularity);
134 info += string_format("R%dG%dB%d\n"
135 "Max Texture size: %dx%d\n"
136 "Max Viewport size: %dx%d\n"
137 "Smooth Point Size %.3f-%.3f (granularity %.3f)",
138 (int)red, (int)green, (int)blue,
139 (int)max_texture_size, (int)max_texture_size,
140 (int)max_viewport[0], (int)max_viewport[1],
141 point_size_range[0], point_size_range[1],
142 point_size_granularity);
143 glGetDoublev(GL_ALIASED_POINT_SIZE_RANGE, point_size_range);
144 if (glGetError() != GL_INVALID_ENUM) {
145 info += string_format("\nAliased point size %.3f-%.3f",
146 point_size_range[0], point_size_range[1]);
147 }
148
149 info += "\nDouble buffered: ";
150 if (double_buffered)
151 info += "true";
152 else
153 info += "false";
154
155 const GLubyte* gl_extensions = glGetString(GL_EXTENSIONS);
156 if (*gl_extensions) {
157 info += '\n';
158 info += (const char*)gl_extensions;
159 }
160 return info;
161}
162
163static bool
164glpoint_sprite_works()
165{
166 // Point sprites provide an easy, fast way for us to draw crosses by
167 // texture mapping GL points.
168 //
169 // If we have OpenGL >= 2.0 then we definitely have GL_POINT_SPRITE.
170 // Otherwise see if we have the GL_ARB_point_sprite or GL_NV_point_sprite
171 // extensions.
172 //
173 // The symbolic constants GL_POINT_SPRITE, GL_POINT_SPRITE_ARB, and
174 // GL_POINT_SPRITE_NV all give the same number so it doesn't matter
175 // which we use.
176 static bool glpoint_sprite = false;
177 static bool checked = false;
178 if (!checked) {
179 float maxSize = 0.0f;
180 glGetFloatv(GL_POINT_SIZE_MAX, &maxSize);
181 if (maxSize >= 8) {
182 glpoint_sprite = (atoi((const char *)glGetString(GL_VERSION)) >= 2);
183 if (!glpoint_sprite) {
184 const char * p = (const char *)glGetString(GL_EXTENSIONS);
185 while (true) {
186 size_t l = 0;
187 if (memcmp(p, "GL_ARB_point_sprite", 19) == 0) {
188 l = 19;
189 } else if (memcmp(p, "GL_NV_point_sprite", 18) == 0) {
190 l = 18;
191 }
192 if (l) {
193 p += l;
194 if (*p == '\0' || *p == ' ') {
195 glpoint_sprite = true;
196 break;
197 }
198 }
199 p = strchr(p + 1, ' ');
200 if (!p) break;
201 ++p;
202 }
203 }
204 }
205 checked = true;
206 }
207 return glpoint_sprite;
208}
209
210static void
211log_gl_error(const wxChar * str, GLenum error_code)
212{
213 const char * e = reinterpret_cast<const char *>(gluErrorString(error_code));
214 wxLogError(str, wxString(e, wxConvUTF8).c_str());
215}
216
217// Important: CHECK_GL_ERROR must not be called within a glBegin()/glEnd() pair
218// (thus it must not be called from BeginLines(), etc., or within a
219// BeginLines()/EndLines() block etc.)
220#define CHECK_GL_ERROR(M, F) do { \
221 if (!opengl_initialised) { \
222 wxLogError(wxT(__FILE__ ":" STRING(__LINE__) ": OpenGL not initialised before (call " F " in method " M ")")); \
223 } \
224 GLenum error_code_ = glGetError(); \
225 if (error_code_ != GL_NO_ERROR) { \
226 log_gl_error(wxT(__FILE__ ":" STRING(__LINE__) ": OpenGL error: %s " \
227 "(call " F " in method " M ")"), error_code_); \
228 } \
229} while (0)
230
231//
232// GLAPen
233//
234
235GLAPen::GLAPen()
236{
237 components[0] = components[1] = components[2] = 0.0;
238}
239
240void GLAPen::SetColour(double red, double green, double blue)
241{
242 components[0] = red;
243 components[1] = green;
244 components[2] = blue;
245}
246
247double GLAPen::GetRed() const
248{
249 return components[0];
250}
251
252double GLAPen::GetGreen() const
253{
254 return components[1];
255}
256
257double GLAPen::GetBlue() const
258{
259 return components[2];
260}
261
262void GLAPen::Interpolate(const GLAPen& pen, double how_far)
263{
264 components[0] += how_far * (pen.GetRed() - components[0]);
265 components[1] += how_far * (pen.GetGreen() - components[1]);
266 components[2] += how_far * (pen.GetBlue() - components[2]);
267}
268
269struct ColourTriple {
270 // RGB triple: values are from 0-255 inclusive for each component.
271 unsigned char r, g, b;
272};
273
274// These must be in the same order as the entries in COLOURS[] below.
275const ColourTriple COLOURS[] = {
276 { 0, 0, 0 }, // black
277 { 100, 100, 100 }, // grey
278 { 180, 180, 180 }, // light grey
279 { 140, 140, 140 }, // light grey 2
280 { 90, 90, 90 }, // dark grey
281 { 255, 255, 255 }, // white
282 { 0, 100, 255}, // turquoise
283 { 0, 255, 40 }, // green
284 { 150, 205, 224 }, // indicator 1
285 { 114, 149, 160 }, // indicator 2
286 { 255, 255, 0 }, // yellow
287 { 255, 0, 0 }, // red
288 { 40, 40, 255 }, // blue
289};
290
291bool GLAList::need_to_generate() {
292 // Bail out if the list is already cached, or can't usefully be cached.
293 if (flags & (GLACanvas::CACHED|GLACanvas::NEVER_CACHE))
294 return false;
295
296 // Create a new OpenGL list to hold this sequence of drawing
297 // operations.
298 if (gl_list == 0) {
299 gl_list = glGenLists(1);
300 CHECK_GL_ERROR("GLAList::need_to_generate", "glGenLists");
301#ifdef GLA_DEBUG
302 printf("glGenLists(1) returned %u\n", (unsigned)gl_list);
303#endif
304 if (gl_list == 0) {
305 // If we can't create a list for any reason, fall back to just
306 // drawing directly, and flag the list as NEVER_CACHE as there's
307 // unlikely to be much point calling glGenLists() again.
308 flags = GLACanvas::NEVER_CACHE;
309 return false;
310 }
311
312 // We should have 256 lists for font drawing and a dozen or so for 2D
313 // and 3D lists. So something is amiss if we've generated 1000 lists,
314 // probably a infinite loop in the lazy list mechanism.
315 assert(gl_list < 1000);
316 }
317 // https://www.opengl.org/resources/faq/technical/displaylist.htm advises:
318 //
319 // "Stay away from GL_COMPILE_AND_EXECUTE mode. Instead, create the
320 // list using GL_COMPILE mode, then execute it with glCallList()."
321 glNewList(gl_list, GL_COMPILE);
322 CHECK_GL_ERROR("GLAList::need_to_generate", "glNewList");
323 return true;
324}
325
326void GLAList::finalise(unsigned int list_flags)
327{
328 glEndList();
329 CHECK_GL_ERROR("GLAList::finalise", "glEndList");
330 if (list_flags & GLACanvas::NEVER_CACHE) {
331 glDeleteLists(gl_list, 1);
332 CHECK_GL_ERROR("GLAList::finalise", "glDeleteLists");
333 gl_list = 0;
334 flags = GLACanvas::NEVER_CACHE;
335 } else {
336 flags = list_flags | GLACanvas::CACHED;
337 }
338}
339
340bool GLAList::DrawList() const {
341 if ((flags & GLACanvas::CACHED) == 0)
342 return false;
343 glCallList(gl_list);
344 CHECK_GL_ERROR("GLAList::DrawList", "glCallList");
345 return true;
346}
347
348//
349// GLACanvas
350//
351
352BEGIN_EVENT_TABLE(GLACanvas, wxGLCanvas)
353 EVT_SIZE(GLACanvas::OnSize)
354END_EVENT_TABLE()
355
356static const int wx_gl_window_attribs[] = {
357 WX_GL_DOUBLEBUFFER,
358 WX_GL_RGBA,
359#ifdef STEREO_BUFFERS
360 WX_GL_STEREO,
361#endif
362 WX_GL_DEPTH_SIZE, 16,
363 0
364};
365
366// Pass wxWANTS_CHARS so that the window gets cursor keys on MS Windows.
367GLACanvas::GLACanvas(wxWindow* parent, int id)
368 : wxGLCanvas(parent, id, wx_gl_window_attribs, wxDefaultPosition,
369 wxDefaultSize, wxWANTS_CHARS),
370 ctx(this), m_Translation(), blob_method(UNKNOWN), cross_method(UNKNOWN),
371 x_size(0), y_size(0)
372{
373 // Constructor.
374
375 m_Quadric = NULL;
376 m_Pan = 0.0;
377 m_Tilt = 0.0;
378 m_Scale = 0.0;
379 m_VolumeDiameter = 1.0;
380 m_SmoothShading = false;
381 m_Texture = 0;
382 m_Textured = false;
383 m_Perspective = false;
384 m_Fog = false;
385 m_AntiAlias = false;
386 list_flags = 0;
387 alpha = 1.0;
388}
389
390GLACanvas::~GLACanvas()
391{
392 // Destructor.
393
394 if (m_Quadric) {
395 gluDeleteQuadric(m_Quadric);
396 CHECK_GL_ERROR("~GLACanvas", "gluDeleteQuadric");
397 }
398}
399
400void GLACanvas::FirstShow()
401{
402 // Update our record of the client area size and centre.
403 GetClientSize(&x_size, &y_size);
404 if (x_size < 1) x_size = 1;
405 if (y_size < 1) y_size = 1;
406
407 ctx.SetCurrent(*this);
408 opengl_initialised = true;
409
410 // Set the background colour of the canvas to black.
411 glClearColor(0.0, 0.0, 0.0, 1.0);
412 CHECK_GL_ERROR("FirstShow", "glClearColor");
413
414 // Set viewport.
415 glViewport(0, 0, x_size, y_size);
416 CHECK_GL_ERROR("FirstShow", "glViewport");
417
418 save_hints = false;
419
420 vendor = wxString((const char *)glGetString(GL_VENDOR), wxConvUTF8);
421 renderer = wxString((const char *)glGetString(GL_RENDERER), wxConvUTF8);
422 {
423 wxConfigBase * cfg = wxConfigBase::Get();
424 wxString s;
425 if (cfg->Read(wxT("opengl_survex"), &s, wxString()) && s == wxT(VERSION) &&
426 cfg->Read(wxT("opengl_vendor"), &s, wxString()) && s == vendor &&
427 cfg->Read(wxT("opengl_renderer"), &s, wxString()) && s == renderer) {
428 // The survex version, vendor and renderer are the same as those
429 // we cached hints for, so use those hints.
430 int v;
431 if (cfg->Read(wxT("blob_method"), &v, 0) &&
432 (v == SPRITE || v == POINT || v == LINES)) {
433 // How to draw blobs.
434 blob_method = v;
435 }
436 if (cfg->Read(wxT("cross_method"), &v, 0) &&
437 (v == SPRITE || v == LINES)) {
438 // How to draw crosses.
439 cross_method = v;
440 }
441 }
442 }
443
444 if (m_Quadric) return;
445 // One time initialisation follows.
446
447 m_Quadric = gluNewQuadric();
448 CHECK_GL_ERROR("FirstShow", "gluNewQuadric");
449 if (!m_Quadric) {
450 abort(); // FIXME need to cope somehow
451 }
452
453 glShadeModel(GL_FLAT);
454 CHECK_GL_ERROR("FirstShow", "glShadeModel");
455 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // So text works.
456 CHECK_GL_ERROR("FirstShow", "glPolygonMode");
457 //glAlphaFunc(GL_GREATER, 0.5f);
458 //CHECK_GL_ERROR("FirstShow", "glAlphaFunc");
459
460 // We want glReadPixels() to read from the front buffer (which is the
461 // default for single-buffered displays).
462 if (double_buffered) {
463 glReadBuffer(GL_FRONT);
464 CHECK_GL_ERROR("FirstShow", "glReadBuffer");
465 }
466
467 // Grey fog effect.
468 GLfloat fogcolour[4] = { 0.5, 0.5, 0.5, 1.0 };
469 glFogfv(GL_FOG_COLOR, fogcolour);
470 CHECK_GL_ERROR("FirstShow", "glFogfv");
471
472 // Linear fogging.
473 glFogi(GL_FOG_MODE, GL_LINEAR);
474 CHECK_GL_ERROR("FirstShow", "glFogi");
475
476 // Optimise for speed (compute fog per vertex).
477 glHint(GL_FOG_HINT, GL_FASTEST);
478 CHECK_GL_ERROR("FirstShow", "glHint");
479
480 // No padding on pixel packing and unpacking (default is to pad each
481 // line to a multiple of 4 bytes).
482 glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // For setting texture maps.
483 CHECK_GL_ERROR("FirstShow", "glPixelStorei GL_UNPACK_ALIGNMENT");
484 glPixelStorei(GL_PACK_ALIGNMENT, 1); // For screengrabs and movies.
485 CHECK_GL_ERROR("FirstShow", "glPixelStorei GL_PACK_ALIGNMENT");
486
487 // Load font
488 wxString path = wmsg_cfgpth();
489 path += wxCONFIG_PATH_SEPARATOR;
490 path += wxT("unifont.pixelfont");
491 if (!m_Font.load(path)) {
492 // FIXME: do something better.
493 // We have this message available: Error in format of font file “%s”
494 fprintf(stderr, "Failed to parse compiled-in font data\n");
495 exit(1);
496 }
497
498 if (blob_method == UNKNOWN) {
499 // Check if we can use GL_POINTS to plot blobs at stations.
500 GLdouble point_size_range[2];
501 glGetDoublev(GL_SMOOTH_POINT_SIZE_RANGE, point_size_range);
502 CHECK_GL_ERROR("FirstShow", "glGetDoublev GL_SMOOTH_POINT_SIZE_RANGE");
503 if (point_size_range[0] <= BLOB_DIAMETER &&
504 point_size_range[1] >= BLOB_DIAMETER) {
505 blob_method = POINT;
506 } else {
507 blob_method = glpoint_sprite_works() ? SPRITE : LINES;
508 }
509 save_hints = true;
510 }
511
512 if (blob_method == POINT) {
513 glPointSize(BLOB_DIAMETER);
514 CHECK_GL_ERROR("FirstShow", "glPointSize");
515 }
516
517 if (cross_method == UNKNOWN) {
518 cross_method = glpoint_sprite_works() ? SPRITE : LINES;
519 save_hints = true;
520 }
521
522 if (cross_method == SPRITE) {
523 glGenTextures(1, &m_CrossTexture);
524 CHECK_GL_ERROR("FirstShow", "glGenTextures");
525 glBindTexture(GL_TEXTURE_2D, m_CrossTexture);
526 CHECK_GL_ERROR("FirstShow", "glBindTexture");
527 // Cross image for drawing crosses using texture mapped point sprites.
528 const unsigned char crossteximage[128] = {
529#define o 0,0
530#define I 255,255
531 CROSS_TEXTURE
532#undef o
533#undef I
534 };
535 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
536 CHECK_GL_ERROR("FirstShow", "glPixelStorei");
537 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
538 CHECK_GL_ERROR("FirstShow", "glTexEnvi");
539 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
540 CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_S");
541 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
542 CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_T");
543 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, 8, 8, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (GLvoid *)crossteximage);
544 CHECK_GL_ERROR("FirstShow", "glTexImage2D");
545 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
546 CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MAG_FILTER");
547 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
548 CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MIN_FILTER");
549 }
550
551 if (blob_method == SPRITE) {
552 glGenTextures(1, &m_BlobTexture);
553 CHECK_GL_ERROR("FirstShow", "glGenTextures");
554 glBindTexture(GL_TEXTURE_2D, m_BlobTexture);
555 CHECK_GL_ERROR("FirstShow", "glBindTexture");
556 // Image for drawing blobs using texture mapped point sprites.
557 const unsigned char blobteximage[128] = {
558#define o 0,0
559#define I 255,255
560 BLOB_TEXTURE
561#undef o
562#undef I
563 };
564 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
565 CHECK_GL_ERROR("FirstShow", "glPixelStorei");
566 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
567 CHECK_GL_ERROR("FirstShow", "glTexEnvi");
568 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
569 CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_S");
570 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
571 CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_T");
572 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, 8, 8, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (GLvoid *)blobteximage);
573 CHECK_GL_ERROR("FirstShow", "glTexImage2D");
574 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
575 CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MAG_FILTER");
576 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
577 CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MIN_FILTER");
578 }
579}
580
581void GLACanvas::Clear()
582{
583 // Clear the canvas.
584
585 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
586 CHECK_GL_ERROR("Clear", "glClear");
587}
588
589void GLACanvas::SetScale(Double scale)
590{
591 if (scale != m_Scale) {
592 vector<GLAList>::iterator i;
593 for (i = drawing_lists.begin(); i != drawing_lists.end(); ++i) {
594 i->invalidate_if(INVALIDATE_ON_SCALE);
595 }
596
597 m_Scale = scale;
598 }
599}
600
601void GLACanvas::OnSize(wxSizeEvent & event)
602{
603 wxSize size = event.GetSize();
604
605 unsigned int mask = 0;
606 if (size.GetWidth() != x_size) mask |= INVALIDATE_ON_X_RESIZE;
607 if (size.GetHeight() != y_size) mask |= INVALIDATE_ON_Y_RESIZE;
608 if (mask) {
609 vector<GLAList>::iterator i;
610 for (i = drawing_lists.begin(); i != drawing_lists.end(); ++i) {
611 i->invalidate_if(mask);
612 }
613
614 // The width and height go to zero when the panel is dragged right
615 // across so we clamp them to be at least 1 to avoid problems.
616 x_size = size.GetWidth();
617 y_size = size.GetHeight();
618 if (x_size < 1) x_size = 1;
619 if (y_size < 1) y_size = 1;
620 }
621
622 event.Skip();
623
624 if (!opengl_initialised) return;
625
626 // Set viewport.
627 glViewport(0, 0, x_size, y_size);
628 CHECK_GL_ERROR("OnSize", "glViewport");
629}
630
631void GLACanvas::AddTranslationScreenCoordinates(int dx, int dy)
632{
633 // Translate the data by a given amount, specified in screen coordinates.
634
635 // Find out how far the translation takes us in data coordinates.
636 SetDataTransform();
637
638 double x0, y0, z0;
639 double x, y, z;
640 gluUnProject(0.0, 0.0, 0.0, modelview_matrix, projection_matrix, viewport,
641 &x0, &y0, &z0);
642 CHECK_GL_ERROR("AddTranslationScreenCoordinates", "gluUnProject");
643 gluUnProject(dx, -dy, 0.0, modelview_matrix, projection_matrix, viewport,
644 &x, &y, &z);
645 CHECK_GL_ERROR("AddTranslationScreenCoordinates", "gluUnProject (2)");
646
647 // Apply the translation.
648 AddTranslation(Vector3(x - x0, y - y0, z - z0));
649}
650
651void GLACanvas::SetVolumeDiameter(glaCoord diameter)
652{
653 // Set the size of the data drawing volume by giving the diameter of the
654 // smallest sphere containing it.
655
656 m_VolumeDiameter = max(glaCoord(1.0), diameter);
657}
658
659void GLACanvas::StartDrawing()
660{
661 // Prepare for a redraw operation.
662
663 ctx.SetCurrent(*this);
664#ifdef STEREO_BUFFERS
665 if (m_Eye != 1) {
666 glDrawBuffer(GL_BACK_LEFT);
667 } else {
668 glDrawBuffer(GL_BACK_RIGHT);
669 }
670#endif
671 glDepthMask(GL_TRUE);
672
673 if (!save_hints) return;
674
675 // We want to check on the second redraw.
676 static int draw_count = 2;
677 if (--draw_count != 0) return;
678
679 if (cross_method != LINES) {
680 SetColour(col_WHITE);
681 Clear();
682 SetDataTransform();
683 BeginCrosses();
684 DrawCross(-m_Translation.GetX(), -m_Translation.GetY(), -m_Translation.GetZ());
685 EndCrosses();
686 static const unsigned char expected_cross[64 * 3] = {
687#define o 0,0,0
688#define I 255,255,255
689 CROSS_TEXTURE
690#undef o
691#undef I
692 };
693 if (!CheckVisualFidelity(expected_cross)) {
694 cross_method = LINES;
695 save_hints = true;
696 }
697 }
698
699 if (blob_method != LINES) {
700 SetColour(col_WHITE);
701 Clear();
702 SetDataTransform();
703 BeginBlobs();
704 DrawBlob(-m_Translation.GetX(), -m_Translation.GetY(), -m_Translation.GetZ());
705 EndBlobs();
706 static const unsigned char expected_blob[64 * 3] = {
707#define o 0,0,0
708#define I 255,255,255
709 BLOB_TEXTURE
710#undef o
711#undef I
712 };
713 if (!CheckVisualFidelity(expected_blob)) {
714 blob_method = LINES;
715 save_hints = true;
716 }
717 }
718
719 wxConfigBase * cfg = wxConfigBase::Get();
720 cfg->Write(wxT("opengl_survex"), wxT(VERSION));
721 cfg->Write(wxT("opengl_vendor"), vendor);
722 cfg->Write(wxT("opengl_renderer"), renderer);
723 cfg->Write(wxT("blob_method"), blob_method);
724 cfg->Write(wxT("cross_method"), cross_method);
725 cfg->Flush();
726 save_hints = false;
727}
728
729void GLACanvas::EnableSmoothPolygons(bool filled)
730{
731 // Prepare for drawing smoothly-shaded polygons.
732 // Only use this when required (in particular lines in lists may not be
733 // coloured correctly when this is enabled).
734
735 glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING_BIT|GL_POLYGON_BIT);
736 if (filled) {
737 glShadeModel(GL_SMOOTH);
738 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
739 } else {
740 glDisable(GL_LINE_SMOOTH);
741 glDisable(GL_TEXTURE_2D);
742 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
743 }
744 CHECK_GL_ERROR("EnableSmoothPolygons", "glPolygonMode");
745
746 if (filled && m_SmoothShading) {
747 static const GLfloat mat_specular[] = { 0.2, 0.2, 0.2, 1.0 };
748 static const GLfloat light_position[] = { -1.0, -1.0, -1.0, 0.0 };
749 static const GLfloat light_ambient[] = { 0.3, 0.3, 0.3, 1.0 };
750 static const GLfloat light_diffuse[] = { 0.7, 0.7, 0.7, 1.0 };
751 glEnable(GL_COLOR_MATERIAL);
752 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
753 glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 10.0);
754 glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
755 glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
756 glLightfv(GL_LIGHT0, GL_POSITION, light_position);
757 glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
758 glEnable(GL_LIGHTING);
759 glEnable(GL_LIGHT0);
760 }
761}
762
763void GLACanvas::DisableSmoothPolygons()
764{
765 glPopAttrib();
766}
767
768void GLACanvas::PlaceNormal(const Vector3 &v)
769{
770 // Add a normal (for polygons etc.)
771
772 glNormal3d(v.GetX(), v.GetY(), v.GetZ());
773}
774
775void GLACanvas::SetDataTransform()
776{
777 // Set projection.
778 glMatrixMode(GL_PROJECTION);
779 CHECK_GL_ERROR("SetDataTransform", "glMatrixMode");
780 glLoadIdentity();
781 CHECK_GL_ERROR("SetDataTransform", "glLoadIdentity");
782
783 double aspect = double(y_size) / double(x_size);
784
785 // 0.1 for mono?
786 Double near_plane = 1.0;
787 const double APERTURE = 50.0;
788 const double FOCAL_LEN = 70.0;
789 const double EYE_SEP = FOCAL_LEN / 20.0;
790 if (m_Perspective) {
791 near_plane = FOCAL_LEN / 5.0;
792 Double stereo_adj = 0.5 * EYE_SEP * near_plane / FOCAL_LEN;
793 Double lr = near_plane * tan(rad(APERTURE * 0.5));
794 Double far_plane = m_VolumeDiameter * 5 + near_plane; // FIXME: work out properly
795 Double tb = lr * aspect;
796 if (m_Eye == 0) stereo_adj = -stereo_adj;
797 glFrustum(-lr + stereo_adj, lr + stereo_adj, -tb, tb, near_plane, far_plane);
798 CHECK_GL_ERROR("SetViewportAndProjection", "glFrustum");
799 } else {
800 near_plane = 0.0;
801 assert(m_Scale != 0.0);
802 Double lr = m_VolumeDiameter / m_Scale * 0.5;
803 Double far_plane = m_VolumeDiameter + near_plane;
804 Double tb = lr * aspect;
805 glOrtho(-lr, lr, -tb, tb, near_plane, far_plane);
806 CHECK_GL_ERROR("SetViewportAndProjection", "glOrtho");
807 }
808
809 // Set the modelview transform for drawing data.
810 glMatrixMode(GL_MODELVIEW);
811 CHECK_GL_ERROR("SetDataTransform", "glMatrixMode");
812 glLoadIdentity();
813 CHECK_GL_ERROR("SetDataTransform", "glLoadIdentity");
814 if (m_Perspective) {
815 glTranslated(0.0, 0.0, -near_plane);
816 } else {
817 glTranslated(0.0, 0.0, -0.5 * m_VolumeDiameter);
818 }
819 CHECK_GL_ERROR("SetDataTransform", "glTranslated");
820 // Get axes the correct way around (z upwards, y into screen)
821 glRotated(-90.0, 1.0, 0.0, 0.0);
822 CHECK_GL_ERROR("SetDataTransform", "glRotated");
823 if (m_Perspective) {
824 glTranslated(m_Eye ? -0.5 * EYE_SEP : 0.5 * EYE_SEP, 0.0, 0.0);
825 CHECK_GL_ERROR("SetDataTransform", "glTranslated");
826 }
827 glRotated(-m_Tilt, 1.0, 0.0, 0.0);
828 CHECK_GL_ERROR("SetDataTransform", "glRotated");
829 glRotated(m_Pan, 0.0, 0.0, 1.0);
830 CHECK_GL_ERROR("SetDataTransform", "CopyToOpenGL");
831 if (m_Perspective) {
832 glTranslated(m_Translation.GetX(),
833 m_Translation.GetY(),
834 m_Translation.GetZ());
835 CHECK_GL_ERROR("SetDataTransform", "glTranslated");
836 }
837
838 // Save projection matrix.
839 glGetDoublev(GL_PROJECTION_MATRIX, projection_matrix);
840 CHECK_GL_ERROR("SetDataTransform", "glGetDoublev");
841
842 // Save viewport coordinates.
843 glGetIntegerv(GL_VIEWPORT, viewport);
844 CHECK_GL_ERROR("SetDataTransform", "glGetIntegerv");
845
846 // Save modelview matrix.
847 glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
848 CHECK_GL_ERROR("SetDataTransform", "glGetDoublev");
849
850 if (!m_Perspective) {
851 // Adjust the translation so we don't change the Z position of the model
852 double X, Y, Z;
853 gluProject(m_Translation.GetX(),
854 m_Translation.GetY(),
855 m_Translation.GetZ(),
856 modelview_matrix, projection_matrix, viewport,
857 &X, &Y, &Z);
858 double Tx, Ty, Tz;
859 gluUnProject(X, Y, 0.5, modelview_matrix, projection_matrix, viewport,
860 &Tx, &Ty, &Tz);
861 glTranslated(Tx, Ty, Tz);
862 CHECK_GL_ERROR("SetDataTransform", "glTranslated");
863 glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
864 }
865
866 glEnable(GL_DEPTH_TEST);
867 CHECK_GL_ERROR("SetDataTransform", "glEnable GL_DEPTH_TEST");
868
869 if (m_Textured) {
870 glBindTexture(GL_TEXTURE_2D, m_Texture);
871 glEnable(GL_TEXTURE_2D);
872 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
873 CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_WRAP_S");
874 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
875 CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_WRAP_T");
876 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
877 CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_MAG_FILTER");
878 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
879 GL_LINEAR_MIPMAP_LINEAR);
880 CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_MIN_FILTER");
881 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
882 } else {
883 glDisable(GL_TEXTURE_2D);
884 }
885 if (m_Fog) {
886 glFogf(GL_FOG_START, near_plane);
887 glFogf(GL_FOG_END, near_plane + m_VolumeDiameter);
888 glEnable(GL_FOG);
889 } else {
890 glDisable(GL_FOG);
891 }
892
893 glEnable(GL_BLEND);
894 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
895 if (m_AntiAlias) {
896 glEnable(GL_LINE_SMOOTH);
897 } else {
898 glDisable(GL_LINE_SMOOTH);
899 }
900}
901
902void GLACanvas::SetIndicatorTransform()
903{
904 list_flags |= NEVER_CACHE;
905
906 // Set the modelview transform and projection for drawing indicators.
907
908 glDisable(GL_DEPTH_TEST);
909 CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_DEPTH_TEST");
910 glDisable(GL_FOG);
911 CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_FOG");
912
913 // Just a simple 2D projection.
914 glMatrixMode(GL_PROJECTION);
915 CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
916 glLoadIdentity();
917 CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity (2)");
918 gluOrtho2D(0, x_size, 0, y_size);
919 CHECK_GL_ERROR("SetIndicatorTransform", "gluOrtho2D");
920
921 // No modelview transform.
922 glMatrixMode(GL_MODELVIEW);
923 CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
924 glLoadIdentity();
925 CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity");
926
927 glDisable(GL_TEXTURE_2D);
928 CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_TEXTURE_2D");
929 glDisable(GL_BLEND);
930 CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_BLEND");
931 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
932 CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_S");
933 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
934 CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_T");
935 glAlphaFunc(GL_GREATER, 0.5f);
936 CHECK_GL_ERROR("SetIndicatorTransform", "glAlphaFunc");
937 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
938 CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MAG_FILTER");
939 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
940 CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MIN_FILTER");
941 glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
942 CHECK_GL_ERROR("SetIndicatorTransform", "glHint");
943}
944
945void GLACanvas::FinishDrawing()
946{
947 // Complete a redraw operation.
948
949 if (double_buffered) {
950 SwapBuffers();
951 } else {
952 glFlush();
953 CHECK_GL_ERROR("FinishDrawing", "glFlush");
954 }
955}
956
957void GLACanvas::DrawList(unsigned int l)
958{
959 // FIXME: uncomment to disable use of lists for debugging:
960 // GenerateList(l); return;
961 if (l >= drawing_lists.size()) drawing_lists.resize(l + 1);
962
963 // We generate the OpenGL lists lazily to minimise delays on startup.
964 // So check if we need to generate the OpenGL list now.
965 if (drawing_lists[l].need_to_generate()) {
966 // Clear list_flags so that we can note what conditions to invalidate
967 // the cached OpenGL list on.
968 list_flags = 0;
969
970#ifdef GLA_DEBUG
971 printf("generating list #%u... ", l);
972 m_Vertices = 0;
973#endif
974 GenerateList(l);
975#ifdef GLA_DEBUG
976 printf("done (%d vertices)\n", m_Vertices);
977#endif
978 drawing_lists[l].finalise(list_flags);
979 }
980
981 if (!drawing_lists[l].DrawList()) {
982 // That list isn't cached (which means it probably can't usefully be
983 // cached).
984 GenerateList(l);
985 }
986}
987
988void GLACanvas::DrawListZPrepass(unsigned int l)
989{
990 glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
991 DrawList(l);
992 glDepthMask(GL_FALSE);
993 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
994 glDepthFunc(GL_EQUAL);
995 DrawList(l);
996 glDepthMask(GL_TRUE);
997 glDepthFunc(GL_LESS);
998}
999
1000void GLACanvas::DrawList2D(unsigned int l, glaCoord x, glaCoord y, Double rotation)
1001{
1002 glMatrixMode(GL_PROJECTION);
1003 CHECK_GL_ERROR("DrawList2D", "glMatrixMode");
1004 glPushMatrix();
1005 CHECK_GL_ERROR("DrawList2D", "glPushMatrix");
1006 glTranslated(x, y, 0);
1007 CHECK_GL_ERROR("DrawList2D", "glTranslated");
1008 if (rotation != 0.0) {
1009 glRotated(rotation, 0, 0, -1);
1010 CHECK_GL_ERROR("DrawList2D", "glRotated");
1011 }
1012 DrawList(l);
1013 glMatrixMode(GL_PROJECTION);
1014 CHECK_GL_ERROR("DrawList2D", "glMatrixMode 2");
1015 glPopMatrix();
1016 CHECK_GL_ERROR("DrawList2D", "glPopMatrix");
1017}
1018
1019void GLACanvas::SetColour(const GLAPen& pen, double rgb_scale)
1020{
1021 // Set the colour for subsequent operations.
1022 glColor4f(pen.GetRed() * rgb_scale, pen.GetGreen() * rgb_scale,
1023 pen.GetBlue() * rgb_scale, alpha);
1024}
1025
1026void GLACanvas::SetColour(const GLAPen& pen)
1027{
1028 // Set the colour for subsequent operations.
1029 glColor4d(pen.components[0], pen.components[1], pen.components[2], alpha);
1030}
1031
1032void GLACanvas::SetColour(gla_colour colour, double rgb_scale)
1033{
1034 // Set the colour for subsequent operations.
1035 rgb_scale /= 255.0;
1036 glColor4f(COLOURS[colour].r * rgb_scale,
1037 COLOURS[colour].g * rgb_scale,
1038 COLOURS[colour].b * rgb_scale,
1039 alpha);
1040}
1041
1042void GLACanvas::SetColour(gla_colour colour)
1043{
1044 // Set the colour for subsequent operations.
1045 if (alpha == 1.0) {
1046 glColor3ubv(&COLOURS[colour].r);
1047 } else {
1048 glColor4ub(COLOURS[colour].r,
1049 COLOURS[colour].g,
1050 COLOURS[colour].b,
1051 (unsigned char)(255 * alpha));
1052 }
1053}
1054
1055void GLACanvas::DrawText(glaCoord x, glaCoord y, glaCoord z, const wxString& str)
1056{
1057 // Draw a text string on the current buffer in the current font.
1058 glRasterPos3d(x, y, z);
1059 CHECK_GL_ERROR("DrawText", "glRasterPos3d");
1060 m_Font.write_string(str.data(), str.size());
1061}
1062
1063void GLACanvas::DrawIndicatorText(int x, int y, const wxString& str)
1064{
1065 glRasterPos2d(x, y);
1066 CHECK_GL_ERROR("DrawIndicatorText", "glRasterPos2d");
1067 m_Font.write_string(str.data(), str.size());
1068}
1069
1070void GLACanvas::GetTextExtent(const wxString& str, int * x_ext, int * y_ext) const
1071{
1072 m_Font.get_text_extent(str.data(), str.size(), x_ext, y_ext);
1073}
1074
1075void GLACanvas::BeginQuadrilaterals()
1076{
1077 // Commence drawing of quadrilaterals.
1078
1079 glBegin(GL_QUADS);
1080}
1081
1082void GLACanvas::EndQuadrilaterals()
1083{
1084 // Finish drawing of quadrilaterals.
1085
1086 glEnd();
1087 CHECK_GL_ERROR("EndQuadrilaterals", "glEnd GL_QUADS");
1088}
1089
1090void GLACanvas::BeginLines()
1091{
1092 // Commence drawing of a set of lines.
1093
1094 glBegin(GL_LINES);
1095}
1096
1097void GLACanvas::EndLines()
1098{
1099 // Finish drawing of a set of lines.
1100
1101 glEnd();
1102 CHECK_GL_ERROR("EndLines", "glEnd GL_LINES");
1103}
1104
1105void GLACanvas::BeginTriangles()
1106{
1107 // Commence drawing of a set of triangles.
1108
1109 glBegin(GL_TRIANGLES);
1110}
1111
1112void GLACanvas::EndTriangles()
1113{
1114 // Finish drawing of a set of triangles.
1115
1116 glEnd();
1117 CHECK_GL_ERROR("EndTriangles", "glEnd GL_TRIANGLES");
1118}
1119
1120void GLACanvas::BeginTriangleStrip()
1121{
1122 // Commence drawing of a triangle strip.
1123
1124 glBegin(GL_TRIANGLE_STRIP);
1125}
1126
1127void GLACanvas::EndTriangleStrip()
1128{
1129 // Finish drawing of a triangle strip.
1130
1131 glEnd();
1132 CHECK_GL_ERROR("EndTriangleStrip", "glEnd GL_TRIANGLE_STRIP");
1133}
1134
1135void GLACanvas::BeginPolyline()
1136{
1137 // Commence drawing of a polyline.
1138
1139 glBegin(GL_LINE_STRIP);
1140}
1141
1142void GLACanvas::EndPolyline()
1143{
1144 // Finish drawing of a polyline.
1145
1146 glEnd();
1147 CHECK_GL_ERROR("EndPolyline", "glEnd GL_LINE_STRIP");
1148}
1149
1150void GLACanvas::BeginPolygon()
1151{
1152 // Commence drawing of a polygon.
1153
1154 glBegin(GL_POLYGON);
1155}
1156
1157void GLACanvas::EndPolygon()
1158{
1159 // Finish drawing of a polygon.
1160
1161 glEnd();
1162 CHECK_GL_ERROR("EndPolygon", "glEnd GL_POLYGON");
1163}
1164
1165void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z)
1166{
1167 // Place a vertex for the current object being drawn.
1168
1169#ifdef GLA_DEBUG
1170 m_Vertices++;
1171#endif
1172 glVertex3d(x, y, z);
1173}
1174
1175void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z,
1176 glaTexCoord tex_x, glaTexCoord tex_y)
1177{
1178 // Place a vertex for the current object being drawn.
1179
1180#ifdef GLA_DEBUG
1181 m_Vertices++;
1182#endif
1183 glTexCoord2f(tex_x, tex_y);
1184 glVertex3d(x, y, z);
1185}
1186
1187void GLACanvas::PlaceIndicatorVertex(glaCoord x, glaCoord y)
1188{
1189 // Place a vertex for the current indicator object being drawn.
1190
1191 PlaceVertex(x, y, 0.0);
1192}
1193
1194void GLACanvas::BeginBlobs()
1195{
1196 // Commence drawing of a set of blobs.
1197 if (blob_method == SPRITE) {
1198 glPushAttrib(GL_ENABLE_BIT|GL_POINT_BIT);
1199 CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1200 glBindTexture(GL_TEXTURE_2D, m_BlobTexture);
1201 CHECK_GL_ERROR("BeginBlobs", "glBindTexture");
1202 glEnable(GL_ALPHA_TEST);
1203 CHECK_GL_ERROR("BeginBlobs", "glEnable GL_ALPHA_TEST");
1204 glPointSize(8);
1205 CHECK_GL_ERROR("BeginBlobs", "glPointSize");
1206 glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
1207 CHECK_GL_ERROR("BeginBlobs", "glTexEnvi GL_POINT_SPRITE");
1208 glEnable(GL_TEXTURE_2D);
1209 CHECK_GL_ERROR("BeginBlobs", "glEnable GL_TEXTURE_2D");
1210 glEnable(GL_POINT_SPRITE);
1211 CHECK_GL_ERROR("BeginBlobs", "glEnable GL_POINT_SPRITE");
1212 glBegin(GL_POINTS);
1213 } else if (blob_method == POINT) {
1214 glPushAttrib(GL_ENABLE_BIT);
1215 CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1216 glEnable(GL_ALPHA_TEST);
1217 CHECK_GL_ERROR("BeginBlobs", "glEnable GL_ALPHA_TEST");
1218 glEnable(GL_POINT_SMOOTH);
1219 CHECK_GL_ERROR("BeginBlobs", "glEnable GL_POINT_SMOOTH");
1220 glBegin(GL_POINTS);
1221 } else {
1222 glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
1223 CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1224 SetIndicatorTransform();
1225 glEnable(GL_DEPTH_TEST);
1226 CHECK_GL_ERROR("BeginBlobs", "glEnable GL_DEPTH_TEST");
1227 glBegin(GL_LINES);
1228 }
1229}
1230
1231void GLACanvas::EndBlobs()
1232{
1233 // Finish drawing of a set of blobs.
1234 glEnd();
1235 if (blob_method != LINES) {
1236 CHECK_GL_ERROR("EndBlobs", "glEnd GL_POINTS");
1237 } else {
1238 CHECK_GL_ERROR("EndBlobs", "glEnd GL_LINES");
1239 }
1240 glPopAttrib();
1241 CHECK_GL_ERROR("EndBlobs", "glPopAttrib");
1242}
1243
1244void GLACanvas::DrawBlob(glaCoord x, glaCoord y, glaCoord z)
1245{
1246 if (blob_method != LINES) {
1247 // Draw a marker.
1248 PlaceVertex(x, y, z);
1249 } else {
1250 double X, Y, Z;
1251 if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
1252 printf("bad transform\n");
1253 return;
1254 }
1255 // Stuff behind us (in perspective view) will get clipped,
1256 // but we can save effort with a cheap check here.
1257 if (Z <= 0) return;
1258
1259 X -= BLOB_DIAMETER * 0.5;
1260 Y -= BLOB_DIAMETER * 0.5;
1261
1262 PlaceVertex(X, Y + 1, Z);
1263 PlaceVertex(X, Y + (BLOB_DIAMETER - 1), Z);
1264
1265 for (int i = 1; i < (BLOB_DIAMETER - 1); ++i) {
1266 PlaceVertex(X + i, Y, Z);
1267 PlaceVertex(X + i, Y + BLOB_DIAMETER, Z);
1268 }
1269
1270 PlaceVertex(X + (BLOB_DIAMETER - 1), Y + 1, Z);
1271 PlaceVertex(X + (BLOB_DIAMETER - 1), Y + (BLOB_DIAMETER - 1), Z);
1272 }
1273#ifdef GLA_DEBUG
1274 m_Vertices++;
1275#endif
1276}
1277
1278void GLACanvas::DrawBlob(glaCoord x, glaCoord y)
1279{
1280 if (blob_method != LINES) {
1281 // Draw a marker.
1282 PlaceVertex(x, y, 0);
1283 } else {
1284 x -= BLOB_DIAMETER * 0.5;
1285 y -= BLOB_DIAMETER * 0.5;
1286
1287 PlaceVertex(x, y + 1, 0);
1288 PlaceVertex(x, y + (BLOB_DIAMETER - 1), 0);
1289
1290 for (int i = 1; i < (BLOB_DIAMETER - 1); ++i) {
1291 PlaceVertex(x + i, y, 0);
1292 PlaceVertex(x + i, y + BLOB_DIAMETER, 0);
1293 }
1294
1295 PlaceVertex(x + (BLOB_DIAMETER - 1), y + 1, 0);
1296 PlaceVertex(x + (BLOB_DIAMETER - 1), y + (BLOB_DIAMETER - 1), 0);
1297 }
1298#ifdef GLA_DEBUG
1299 m_Vertices++;
1300#endif
1301}
1302
1303void GLACanvas::BeginCrosses()
1304{
1305 // Plot crosses.
1306 if (cross_method == SPRITE) {
1307 glPushAttrib(GL_ENABLE_BIT|GL_POINT_BIT);
1308 CHECK_GL_ERROR("BeginCrosses", "glPushAttrib");
1309 glBindTexture(GL_TEXTURE_2D, m_CrossTexture);
1310 CHECK_GL_ERROR("BeginCrosses", "glBindTexture");
1311 glEnable(GL_ALPHA_TEST);
1312 CHECK_GL_ERROR("BeginCrosses", "glEnable GL_ALPHA_TEST");
1313 glPointSize(8);
1314 CHECK_GL_ERROR("BeginCrosses", "glPointSize");
1315 glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
1316 CHECK_GL_ERROR("BeginCrosses", "glTexEnvi GL_POINT_SPRITE");
1317 glEnable(GL_TEXTURE_2D);
1318 CHECK_GL_ERROR("BeginCrosses", "glEnable GL_TEXTURE_2D");
1319 glEnable(GL_POINT_SPRITE);
1320 CHECK_GL_ERROR("BeginCrosses", "glEnable GL_POINT_SPRITE");
1321 glBegin(GL_POINTS);
1322 } else {
1323 // To get the crosses to appear at a constant size and orientation on
1324 // screen, we plot them in the Indicator transform coordinates (which
1325 // unfortunately means they can't be usefully put in an opengl display
1326 // list).
1327 glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
1328 CHECK_GL_ERROR("BeginCrosses", "glPushAttrib 2");
1329 SetIndicatorTransform();
1330 // Align line drawing to pixel centres to get pixel-perfect rendering
1331 // (graphics card and driver bugs aside).
1332 glTranslated(-0.5, -0.5, 0);
1333 CHECK_GL_ERROR("BeginCrosses", "glTranslated");
1334 glEnable(GL_DEPTH_TEST);
1335 CHECK_GL_ERROR("BeginCrosses", "glEnable GL_DEPTH_TEST");
1336 glBegin(GL_LINES);
1337 }
1338}
1339
1340void GLACanvas::EndCrosses()
1341{
1342 glEnd();
1343 if (cross_method == SPRITE) {
1344 CHECK_GL_ERROR("EndCrosses", "glEnd GL_POINTS");
1345 } else {
1346 CHECK_GL_ERROR("EndCrosses", "glEnd GL_LINES");
1347 }
1348 glPopAttrib();
1349 CHECK_GL_ERROR("EndCrosses", "glPopAttrib");
1350}
1351
1352void GLACanvas::DrawCross(glaCoord x, glaCoord y, glaCoord z)
1353{
1354 if (cross_method == SPRITE) {
1355 // Draw a marker.
1356 PlaceVertex(x, y, z);
1357 } else {
1358 double X, Y, Z;
1359 if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
1360 printf("bad transform\n");
1361 return;
1362 }
1363 // Stuff behind us (in perspective view) will get clipped,
1364 // but we can save effort with a cheap check here.
1365 if (Z <= 0) return;
1366
1367 // Round to integers before adding on the offsets for the
1368 // cross arms to avoid uneven crosses.
1369 X = rint(X);
1370 Y = rint(Y);
1371 // Need to extend lines by an extra pixel (which shouldn't get drawn by
1372 // the diamond-exit rule).
1373 PlaceVertex(X - 3, Y - 3, Z);
1374 PlaceVertex(X + 4, Y + 4, Z);
1375 PlaceVertex(X - 3, Y + 3, Z);
1376 PlaceVertex(X + 4, Y - 4, Z);
1377 }
1378#ifdef GLA_DEBUG
1379 m_Vertices++;
1380#endif
1381}
1382
1383void GLACanvas::DrawRing(glaCoord x, glaCoord y)
1384{
1385 // Draw an unfilled circle
1386 const Double radius = 4;
1387 assert(m_Quadric);
1388 glMatrixMode(GL_MODELVIEW);
1389 CHECK_GL_ERROR("DrawRing", "glMatrixMode");
1390 glPushMatrix();
1391 CHECK_GL_ERROR("DrawRing", "glPushMatrix");
1392 glTranslated(x, y, 0.0);
1393 CHECK_GL_ERROR("DrawRing", "glTranslated");
1394 gluDisk(m_Quadric, radius - 1.0, radius, 12, 1);
1395 CHECK_GL_ERROR("DrawRing", "gluDisk");
1396 glPopMatrix();
1397 CHECK_GL_ERROR("DrawRing", "glPopMatrix");
1398}
1399
1400void GLACanvas::DrawRectangle(gla_colour fill, gla_colour edge,
1401 glaCoord x0, glaCoord y0, glaCoord w, glaCoord h)
1402{
1403 // Draw a filled rectangle with an edge in the indicator plane.
1404 // (x0, y0) specify the bottom-left corner of the rectangle and (w, h) the
1405 // size.
1406
1407 SetColour(fill);
1408 BeginQuadrilaterals();
1409 PlaceIndicatorVertex(x0, y0);
1410 PlaceIndicatorVertex(x0 + w, y0);
1411 PlaceIndicatorVertex(x0 + w, y0 + h);
1412 PlaceIndicatorVertex(x0, y0 + h);
1413 EndQuadrilaterals();
1414
1415 if (edge != fill) {
1416 SetColour(edge);
1417 BeginPolyline();
1418 PlaceIndicatorVertex(x0, y0);
1419 PlaceIndicatorVertex(x0 + w, y0);
1420 PlaceIndicatorVertex(x0 + w, y0 + h);
1421 PlaceIndicatorVertex(x0, y0 + h);
1422 PlaceIndicatorVertex(x0, y0);
1423 EndLines();
1424 }
1425}
1426
1427void
1428GLACanvas::DrawShadedRectangle(const GLAPen & fill_bot, const GLAPen & fill_top,
1429 glaCoord x0, glaCoord y0,
1430 glaCoord w, glaCoord h)
1431{
1432 // Draw a graduated filled rectangle in the indicator plane.
1433 // (x0, y0) specify the bottom-left corner of the rectangle and (w, h) the
1434 // size.
1435
1436 glShadeModel(GL_SMOOTH);
1437 CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_SMOOTH");
1438 BeginQuadrilaterals();
1439 SetColour(fill_bot);
1440 PlaceIndicatorVertex(x0, y0);
1441 PlaceIndicatorVertex(x0 + w, y0);
1442 SetColour(fill_top);
1443 PlaceIndicatorVertex(x0 + w, y0 + h);
1444 PlaceIndicatorVertex(x0, y0 + h);
1445 EndQuadrilaterals();
1446 glShadeModel(GL_FLAT);
1447 CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_FLAT");
1448}
1449
1450void GLACanvas::DrawCircle(gla_colour edge, gla_colour fill,
1451 glaCoord cx, glaCoord cy, glaCoord radius)
1452{
1453 // Draw a filled circle with an edge.
1454 SetColour(fill);
1455 glMatrixMode(GL_MODELVIEW);
1456 CHECK_GL_ERROR("DrawCircle", "glMatrixMode");
1457 glPushMatrix();
1458 CHECK_GL_ERROR("DrawCircle", "glPushMatrix");
1459 glTranslated(cx, cy, 0.0);
1460 CHECK_GL_ERROR("DrawCircle", "glTranslated");
1461 assert(m_Quadric);
1462 gluDisk(m_Quadric, 0.0, radius, 36, 1);
1463 CHECK_GL_ERROR("DrawCircle", "gluDisk");
1464 SetColour(edge);
1465 gluDisk(m_Quadric, radius - 1.0, radius, 36, 1);
1466 CHECK_GL_ERROR("DrawCircle", "gluDisk (2)");
1467 glPopMatrix();
1468 CHECK_GL_ERROR("DrawCircle", "glPopMatrix");
1469}
1470
1471void GLACanvas::DrawSemicircle(gla_colour edge, gla_colour fill,
1472 glaCoord cx, glaCoord cy,
1473 glaCoord radius, glaCoord start)
1474{
1475 // Draw a filled semicircle with an edge.
1476 // The semicircle extends from "start" deg to "start"+180 deg (increasing
1477 // clockwise, 0 deg upwards).
1478 SetColour(fill);
1479 glMatrixMode(GL_MODELVIEW);
1480 CHECK_GL_ERROR("DrawSemicircle", "glMatrixMode");
1481 glPushMatrix();
1482 CHECK_GL_ERROR("DrawSemicircle", "glPushMatrix");
1483 glTranslated(cx, cy, 0.0);
1484 CHECK_GL_ERROR("DrawSemicircle", "glTranslated");
1485 assert(m_Quadric);
1486 gluPartialDisk(m_Quadric, 0.0, radius, 36, 1, start, 180.0);
1487 CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk");
1488 SetColour(edge);
1489 gluPartialDisk(m_Quadric, radius - 1.0, radius, 36, 1, start, 180.0);
1490 CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk (2)");
1491 glPopMatrix();
1492 CHECK_GL_ERROR("DrawSemicircle", "glPopMatrix");
1493}
1494
1495void
1496GLACanvas::DrawTriangle(gla_colour edge, gla_colour fill,
1497 const Vector3 &p0, const Vector3 &p1, const Vector3 &p2)
1498{
1499 // Draw a filled triangle with an edge.
1500
1501 SetColour(fill);
1502 BeginTriangles();
1503 PlaceIndicatorVertex(p0.GetX(), p0.GetY());
1504 PlaceIndicatorVertex(p1.GetX(), p1.GetY());
1505 PlaceIndicatorVertex(p2.GetX(), p2.GetY());
1506 EndTriangles();
1507
1508 SetColour(edge);
1509 glBegin(GL_LINE_STRIP);
1510 PlaceIndicatorVertex(p0.GetX(), p0.GetY());
1511 PlaceIndicatorVertex(p1.GetX(), p1.GetY());
1512 PlaceIndicatorVertex(p2.GetX(), p2.GetY());
1513 glEnd();
1514 CHECK_GL_ERROR("DrawTriangle", "glEnd GL_LINE_STRIP");
1515}
1516
1517void GLACanvas::EnableDashedLines()
1518{
1519 // Enable dashed lines, and start drawing in them.
1520
1521 glLineStipple(1, 0x3333);
1522 CHECK_GL_ERROR("EnableDashedLines", "glLineStipple");
1523 glEnable(GL_LINE_STIPPLE);
1524 CHECK_GL_ERROR("EnableDashedLines", "glEnable GL_LINE_STIPPLE");
1525}
1526
1527void GLACanvas::DisableDashedLines()
1528{
1529 glDisable(GL_LINE_STIPPLE);
1530 CHECK_GL_ERROR("DisableDashedLines", "glDisable GL_LINE_STIPPLE");
1531}
1532
1533bool GLACanvas::Transform(const Vector3 & v,
1534 double* x_out, double* y_out, double* z_out) const
1535{
1536 // Convert from data coordinates to screen coordinates.
1537
1538 // Perform the projection.
1539 return gluProject(v.GetX(), v.GetY(), v.GetZ(),
1540 modelview_matrix, projection_matrix, viewport,
1541 x_out, y_out, z_out);
1542}
1543
1544void GLACanvas::ReverseTransform(Double x, Double y,
1545 double* x_out, double* y_out, double* z_out) const
1546{
1547 // Convert from screen coordinates to data coordinates.
1548
1549 // Perform the projection.
1550 gluUnProject(x, y, 0.0, modelview_matrix, projection_matrix, viewport,
1551 x_out, y_out, z_out);
1552 CHECK_GL_ERROR("ReverseTransform", "gluUnProject");
1553}
1554
1555Double GLACanvas::SurveyUnitsAcrossViewport() const
1556{
1557 // Measure the current viewport in survey units, taking into account the
1558 // current display scale.
1559
1560 assert(m_Scale != 0.0);
1561 list_flags |= INVALIDATE_ON_SCALE;
1562 return m_VolumeDiameter / m_Scale;
1563}
1564
1565void GLACanvas::ToggleSmoothShading()
1566{
1567 m_SmoothShading = !m_SmoothShading;
1568}
1569
1570void GLACanvas::ToggleTextured()
1571{
1572 m_Textured = !m_Textured;
1573 if (m_Textured && m_Texture == 0) {
1574 glGenTextures(1, &m_Texture);
1575 CHECK_GL_ERROR("ToggleTextured", "glGenTextures");
1576
1577 glBindTexture(GL_TEXTURE_2D, m_Texture);
1578 CHECK_GL_ERROR("ToggleTextured", "glBindTexture");
1579
1580 ::wxInitAllImageHandlers();
1581
1582 wxImage img;
1583 wxString texture(wmsg_cfgpth());
1584 texture += wxCONFIG_PATH_SEPARATOR;
1585 texture += wxT("images");
1586 texture += wxCONFIG_PATH_SEPARATOR;
1587 texture += wxT("texture.png");
1588 if (!img.LoadFile(texture, wxBITMAP_TYPE_PNG)) {
1589 // FIXME
1590 fprintf(stderr, "Couldn't load image.\n");
1591 exit(1);
1592 }
1593
1594 // Generate mipmaps.
1595 gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, // was GL_LUMINANCE
1596 img.GetWidth(), img.GetHeight(),
1597 GL_RGB, GL_UNSIGNED_BYTE, img.GetData());
1598 CHECK_GL_ERROR("ToggleTextured", "gluBuild2DMipmaps");
1599
1600 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1601 CHECK_GL_ERROR("ToggleTextured", "glTexEnvi");
1602 }
1603}
1604
1605bool GLACanvas::SaveScreenshot(const wxString & fnm, wxBitmapType type) const
1606{
1607 const int width = x_size;
1608 const int height = y_size;
1609 unsigned char *pixels = (unsigned char *)malloc(3 * width * (height + 1));
1610 if (!pixels) return false;
1611 glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
1612 CHECK_GL_ERROR("SaveScreenshot", "glReadPixels");
1613 unsigned char * tmp_row = pixels + 3 * width * height;
1614 // We need to flip the image vertically - this approach should be more
1615 // efficient than using wxImage::Mirror(false) as that creates a new
1616 // wxImage object.
1617 for (int y = height / 2 - 1; y >= 0; --y) {
1618 unsigned char * upper = pixels + 3 * width * y;
1619 unsigned char * lower = pixels + 3 * width * (height - y - 1);
1620 memcpy(tmp_row, upper, 3 * width);
1621 memcpy(upper, lower, 3 * width);
1622 memcpy(lower, tmp_row, 3 * width);
1623 }
1624 // NB wxImage constructor calls free(pixels) for us.
1625 wxImage grab(width, height, pixels);
1626 return grab.SaveFile(fnm, type);
1627}
1628
1629bool GLACanvas::CheckVisualFidelity(const unsigned char * target) const
1630{
1631 unsigned char pixels[3 * 8 * 8];
1632 if (double_buffered) {
1633 glReadBuffer(GL_BACK);
1634 CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1635 }
1636 glReadPixels(x_size / 2 - 4, y_size / 2 - 5, 8, 8,
1637 GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
1638 CHECK_GL_ERROR("CheckVisualFidelity", "glReadPixels");
1639 if (double_buffered) {
1640 glReadBuffer(GL_FRONT);
1641 CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1642 }
1643#if 0
1644 // Show what got drawn and what was expected for debugging.
1645 for (int y = 0; y < 8; ++y) {
1646 for (int x = 0; x < 8; ++x) {
1647 int o = (y * 8 + x) * 3;
1648 printf("%c", pixels[o] ? 'X' : '.');
1649 }
1650 printf(" ");
1651 for (int x = 0; x < 8; ++x) {
1652 int o = (y * 8 + x) * 3;
1653 printf("%c", target[o] ? 'X' : '.');
1654 }
1655 printf("\n");
1656 }
1657#endif
1658 return (memcmp(pixels, target, sizeof(pixels)) == 0);
1659}
1660
1661void GLACanvas::ReadPixels(int width, int height, unsigned char * buf) const
1662{
1663 CHECK_GL_ERROR("ReadPixels", "glReadPixels");
1664 glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)buf);
1665}
1666
1667void GLACanvas::PolygonOffset(bool on) const
1668{
1669 if (on) {
1670 glPolygonOffset(1.0, 1.0);
1671 glEnable(GL_POLYGON_OFFSET_FILL);
1672 } else {
1673 glDisable(GL_POLYGON_OFFSET_FILL);
1674 }
1675}
Note: See TracBrowser for help on using the repository browser.