source: git/src/gla-gl.cc @ 5846a74

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 5846a74 was 5846a74, checked in by Olly Betts <olly@…>, 8 years ago

Invalidate opengl hints upon new survex version

The rendering code may have changed, so it is useful to recheck

  • Property mode set to 100644
File size: 47.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 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    // http://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    WX_GL_DEPTH_SIZE, 16,
360    0
361};
362
363// Pass wxWANTS_CHARS so that the window gets cursor keys on MS Windows.
364GLACanvas::GLACanvas(wxWindow* parent, int id)
365    : wxGLCanvas(parent, id, wx_gl_window_attribs, wxDefaultPosition,
366                 wxDefaultSize, wxWANTS_CHARS),
367      ctx(this), m_Translation(), blob_method(UNKNOWN), cross_method(UNKNOWN),
368      x_size(0), y_size(0)
369{
370    // Constructor.
371
372    m_Quadric = NULL;
373    m_Pan = 0.0;
374    m_Tilt = 0.0;
375    m_Scale = 0.0;
376    m_VolumeDiameter = 1.0;
377    m_SmoothShading = false;
378    m_Texture = 0;
379    m_Textured = false;
380    m_Perspective = false;
381    m_Fog = false;
382    m_AntiAlias = false;
383    list_flags = 0;
384    alpha = 1.0;
385}
386
387GLACanvas::~GLACanvas()
388{
389    // Destructor.
390
391    if (m_Quadric) {
392        gluDeleteQuadric(m_Quadric);
393        CHECK_GL_ERROR("~GLACanvas", "gluDeleteQuadric");
394    }
395}
396
397void GLACanvas::FirstShow()
398{
399    // Update our record of the client area size and centre.
400    GetClientSize(&x_size, &y_size);
401    if (x_size < 1) x_size = 1;
402    if (y_size < 1) y_size = 1;
403
404    ctx.SetCurrent(*this);
405    opengl_initialised = true;
406
407    // Set the background colour of the canvas to black.
408    glClearColor(0.0, 0.0, 0.0, 1.0);
409    CHECK_GL_ERROR("FirstShow", "glClearColor");
410
411    // Set viewport.
412    glViewport(0, 0, x_size, y_size);
413    CHECK_GL_ERROR("FirstShow", "glViewport");
414
415    save_hints = false;
416
417    vendor = wxString((const char *)glGetString(GL_VENDOR), wxConvUTF8);
418    renderer = wxString((const char *)glGetString(GL_RENDERER), wxConvUTF8);
419    {
420        wxConfigBase * cfg = wxConfigBase::Get();
421        wxString s;
422        if (cfg->Read(wxT("opengl_survex"), &s, wxString()) && s == wxT(VERSION) &&
423            cfg->Read(wxT("opengl_vendor"), &s, wxString()) && s == vendor &&
424            cfg->Read(wxT("opengl_renderer"), &s, wxString()) && s == renderer) {
425            // The survex version, vendor and renderer are the same as those
426            // we cached hints for, so use those hints.
427            int v;
428            if (cfg->Read(wxT("blob_method"), &v, 0) &&
429                (v == POINT || v == LINES)) {
430                // How to draw blobs.
431                blob_method = v;
432            }
433            if (cfg->Read(wxT("cross_method"), &v, 0) &&
434                (v == SPRITE || v == LINES)) {
435                // How to draw crosses.
436                cross_method = v;
437            }
438        }
439    }
440
441    if (m_Quadric) return;
442    // One time initialisation follows.
443
444    m_Quadric = gluNewQuadric();
445    CHECK_GL_ERROR("FirstShow", "gluNewQuadric");
446    if (!m_Quadric) {
447        abort(); // FIXME need to cope somehow
448    }
449
450    glShadeModel(GL_FLAT);
451    CHECK_GL_ERROR("FirstShow", "glShadeModel");
452    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // So text works.
453    CHECK_GL_ERROR("FirstShow", "glPolygonMode");
454    //glAlphaFunc(GL_GREATER, 0.5f);
455    //CHECK_GL_ERROR("FirstShow", "glAlphaFunc");
456
457    // We want glReadPixels() to read from the front buffer (which is the
458    // default for single-buffered displays).
459    if (double_buffered) {
460        glReadBuffer(GL_FRONT);
461        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
462    }
463
464    // Grey fog effect.
465    GLfloat fogcolour[4] = { 0.5, 0.5, 0.5, 1.0 };
466    glFogfv(GL_FOG_COLOR, fogcolour);
467    CHECK_GL_ERROR("FirstShow", "glFogfv");
468
469    // Linear fogging.
470    glFogi(GL_FOG_MODE, GL_LINEAR);
471    CHECK_GL_ERROR("FirstShow", "glFogi");
472
473    // Optimise for speed (compute fog per vertex).
474    glHint(GL_FOG_HINT, GL_FASTEST);
475    CHECK_GL_ERROR("FirstShow", "glHint");
476
477    // No padding on pixel packing and unpacking (default is to pad each
478    // line to a multiple of 4 bytes).
479    glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // For setting texture maps.
480    CHECK_GL_ERROR("FirstShow", "glPixelStorei GL_UNPACK_ALIGNMENT");
481    glPixelStorei(GL_PACK_ALIGNMENT, 1); // For screengrabs and movies.
482    CHECK_GL_ERROR("FirstShow", "glPixelStorei GL_PACK_ALIGNMENT");
483
484    // Load font
485    wxString path = wmsg_cfgpth();
486    path += wxCONFIG_PATH_SEPARATOR;
487    path += wxT("unifont.pixelfont");
488    if (!m_Font.load(path)) {
489        // FIXME: do something better.
490        // We have this message available: Error in format of font file “%s”
491        fprintf(stderr, "Failed to parse compiled-in font data\n");
492        exit(1);
493    }
494
495    if (blob_method == UNKNOWN) {
496        // Check if we can use GL_POINTS to plot blobs at stations.
497        GLdouble point_size_range[2];
498        glGetDoublev(GL_SMOOTH_POINT_SIZE_RANGE, point_size_range);
499        CHECK_GL_ERROR("FirstShow", "glGetDoublev GL_SMOOTH_POINT_SIZE_RANGE");
500        if (point_size_range[0] <= BLOB_DIAMETER &&
501            point_size_range[1] >= BLOB_DIAMETER) {
502            blob_method = POINT;
503        } else {
504            blob_method = glpoint_sprite_works() ? SPRITE : LINES;
505        }
506        save_hints = true;
507    }
508
509    if (blob_method == POINT) {
510        glPointSize(BLOB_DIAMETER);
511        CHECK_GL_ERROR("FirstShow", "glPointSize");
512    }
513
514    if (cross_method == UNKNOWN) {
515        cross_method = glpoint_sprite_works() ? SPRITE : LINES;
516        save_hints = true;
517    }
518
519    if (cross_method == SPRITE) {
520        glGenTextures(1, &m_CrossTexture);
521        CHECK_GL_ERROR("FirstShow", "glGenTextures");
522        glBindTexture(GL_TEXTURE_2D, m_CrossTexture);
523        CHECK_GL_ERROR("FirstShow", "glBindTexture");
524        // Cross image for drawing crosses using texture mapped point sprites.
525        const unsigned char crossteximage[128] = {
526#define o 0,0
527#define I 255,255
528            CROSS_TEXTURE
529#undef o
530#undef I
531        };
532        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
533        CHECK_GL_ERROR("FirstShow", "glPixelStorei");
534        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
535        CHECK_GL_ERROR("FirstShow", "glTexEnvi");
536        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
537        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_S");
538        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
539        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_T");
540        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, 8, 8, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (GLvoid *)crossteximage);
541        CHECK_GL_ERROR("FirstShow", "glTexImage2D");
542        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
543        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MAG_FILTER");
544        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
545        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MIN_FILTER");
546    }
547
548    if (blob_method == SPRITE) {
549        glGenTextures(1, &m_BlobTexture);
550        CHECK_GL_ERROR("FirstShow", "glGenTextures");
551        glBindTexture(GL_TEXTURE_2D, m_BlobTexture);
552        CHECK_GL_ERROR("FirstShow", "glBindTexture");
553        // Image for drawing blobs using texture mapped point sprites.
554        const unsigned char blobteximage[128] = {
555#define o 0,0
556#define I 255,255
557            BLOB_TEXTURE
558#undef o
559#undef I
560        };
561        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
562        CHECK_GL_ERROR("FirstShow", "glPixelStorei");
563        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
564        CHECK_GL_ERROR("FirstShow", "glTexEnvi");
565        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
566        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_S");
567        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
568        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_WRAP_T");
569        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, 8, 8, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (GLvoid *)blobteximage);
570        CHECK_GL_ERROR("FirstShow", "glTexImage2D");
571        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
572        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MAG_FILTER");
573        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
574        CHECK_GL_ERROR("FirstShow", "glTexParameteri GL_TEXTURE_MIN_FILTER");
575    }
576}
577
578void GLACanvas::Clear()
579{
580    // Clear the canvas.
581
582    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
583    CHECK_GL_ERROR("Clear", "glClear");
584}
585
586void GLACanvas::SetScale(Double scale)
587{
588    if (scale != m_Scale) {
589        vector<GLAList>::iterator i;
590        for (i = drawing_lists.begin(); i != drawing_lists.end(); ++i) {
591            i->invalidate_if(INVALIDATE_ON_SCALE);
592        }
593
594        m_Scale = scale;
595    }
596}
597
598void GLACanvas::OnSize(wxSizeEvent & event)
599{
600    wxSize size = event.GetSize();
601
602    unsigned int mask = 0;
603    if (size.GetWidth() != x_size) mask |= INVALIDATE_ON_X_RESIZE;
604    if (size.GetHeight() != y_size) mask |= INVALIDATE_ON_Y_RESIZE;
605    if (mask) {
606        vector<GLAList>::iterator i;
607        for (i = drawing_lists.begin(); i != drawing_lists.end(); ++i) {
608            i->invalidate_if(mask);
609        }
610
611        // The width and height go to zero when the panel is dragged right
612        // across so we clamp them to be at least 1 to avoid problems.
613        x_size = size.GetWidth();
614        y_size = size.GetHeight();
615        if (x_size < 1) x_size = 1;
616        if (y_size < 1) y_size = 1;
617    }
618
619    event.Skip();
620
621    if (!opengl_initialised) return;
622
623    // Set viewport.
624    glViewport(0, 0, x_size, y_size);
625    CHECK_GL_ERROR("OnSize", "glViewport");
626}
627
628void GLACanvas::AddTranslationScreenCoordinates(int dx, int dy)
629{
630    // Translate the data by a given amount, specified in screen coordinates.
631
632    // Find out how far the translation takes us in data coordinates.
633    SetDataTransform();
634
635    double x0, y0, z0;
636    double x, y, z;
637    gluUnProject(0.0, 0.0, 0.0, modelview_matrix, projection_matrix, viewport,
638                 &x0, &y0, &z0);
639    CHECK_GL_ERROR("AddTranslationScreenCoordinates", "gluUnProject");
640    gluUnProject(dx, -dy, 0.0, modelview_matrix, projection_matrix, viewport,
641                 &x, &y, &z);
642    CHECK_GL_ERROR("AddTranslationScreenCoordinates", "gluUnProject (2)");
643
644    // Apply the translation.
645    AddTranslation(Vector3(x - x0, y - y0, z - z0));
646}
647
648void GLACanvas::SetVolumeDiameter(glaCoord diameter)
649{
650    // Set the size of the data drawing volume by giving the diameter of the
651    // smallest sphere containing it.
652
653    m_VolumeDiameter = max(glaCoord(1.0), diameter);
654}
655
656void GLACanvas::StartDrawing()
657{
658    // Prepare for a redraw operation.
659
660    ctx.SetCurrent(*this);
661    glDepthMask(GL_TRUE);
662
663    if (!save_hints) return;
664
665    // We want to check on the second redraw.
666    static int draw_count = 2;
667    if (--draw_count != 0) return;
668
669    if (cross_method != LINES) {
670        SetColour(col_WHITE);
671        Clear();
672        SetDataTransform();
673        BeginCrosses();
674        DrawCross(-m_Translation.GetX(), -m_Translation.GetY(), -m_Translation.GetZ());
675        EndCrosses();
676        static const unsigned char expected_cross[64 * 3] = {
677#define o 0,0,0
678#define I 255,255,255
679            CROSS_TEXTURE
680#undef o
681#undef I
682        };
683        if (!CheckVisualFidelity(expected_cross)) {
684            cross_method = LINES;
685            save_hints = true;
686        }
687    }
688
689    if (blob_method != LINES) {
690        SetColour(col_WHITE);
691        Clear();
692        SetDataTransform();
693        BeginBlobs();
694        DrawBlob(-m_Translation.GetX(), -m_Translation.GetY(), -m_Translation.GetZ());
695        EndBlobs();
696        static const unsigned char expected_blob[64 * 3] = {
697#define o 0,0,0
698#define I 255,255,255
699            BLOB_TEXTURE
700#undef o
701#undef I
702        };
703        if (!CheckVisualFidelity(expected_blob)) {
704            blob_method = LINES;
705            save_hints = true;
706        }
707    }
708
709    wxConfigBase * cfg = wxConfigBase::Get();
710    cfg->Write(wxT("opengl_survex"), wxT(VERSION));
711    cfg->Write(wxT("opengl_vendor"), vendor);
712    cfg->Write(wxT("opengl_renderer"), renderer);
713    cfg->Write(wxT("blob_method"), blob_method);
714    cfg->Write(wxT("cross_method"), cross_method);
715    cfg->Flush();
716    save_hints = false;
717}
718
719void GLACanvas::EnableSmoothPolygons(bool filled)
720{
721    // Prepare for drawing smoothly-shaded polygons.
722    // Only use this when required (in particular lines in lists may not be
723    // coloured correctly when this is enabled).
724
725    glPushAttrib(GL_ENABLE_BIT|GL_LIGHTING_BIT|GL_POLYGON_BIT);
726    if (filled) {
727        glShadeModel(GL_SMOOTH);
728        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
729    } else {
730        glDisable(GL_LINE_SMOOTH);
731        glDisable(GL_TEXTURE_2D);
732        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
733    }
734    CHECK_GL_ERROR("EnableSmoothPolygons", "glPolygonMode");
735
736    if (filled && m_SmoothShading) {
737        static const GLfloat mat_specular[] = { 0.2, 0.2, 0.2, 1.0 };
738        static const GLfloat light_position[] = { -1.0, -1.0, -1.0, 0.0 };
739        static const GLfloat light_ambient[] = { 0.3, 0.3, 0.3, 1.0 };
740        static const GLfloat light_diffuse[] = { 0.7, 0.7, 0.7, 1.0 };
741        glEnable(GL_COLOR_MATERIAL);
742        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
743        glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 10.0);
744        glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
745        glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
746        glLightfv(GL_LIGHT0, GL_POSITION, light_position);
747        glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
748        glEnable(GL_LIGHTING);
749        glEnable(GL_LIGHT0);
750    }
751}
752
753void GLACanvas::DisableSmoothPolygons()
754{
755    glPopAttrib();
756}
757
758void GLACanvas::PlaceNormal(const Vector3 &v)
759{
760    // Add a normal (for polygons etc.)
761
762    glNormal3d(v.GetX(), v.GetY(), v.GetZ());
763}
764
765void GLACanvas::SetDataTransform()
766{
767    // Set projection.
768    glMatrixMode(GL_PROJECTION);
769    CHECK_GL_ERROR("SetDataTransform", "glMatrixMode");
770    glLoadIdentity();
771    CHECK_GL_ERROR("SetDataTransform", "glLoadIdentity");
772
773    double aspect = double(y_size) / double(x_size);
774
775    Double near_plane = 1.0;
776    if (m_Perspective) {
777        Double lr = near_plane * tan(rad(25.0));
778        Double far_plane = m_VolumeDiameter * 5 + near_plane; // FIXME: work out properly
779        Double tb = lr * aspect;
780        glFrustum(-lr, lr, -tb, tb, near_plane, far_plane);
781        CHECK_GL_ERROR("SetViewportAndProjection", "glFrustum");
782    } else {
783        near_plane = 0.0;
784        assert(m_Scale != 0.0);
785        Double lr = m_VolumeDiameter / m_Scale * 0.5;
786        Double far_plane = m_VolumeDiameter + near_plane;
787        Double tb = lr * aspect;
788        glOrtho(-lr, lr, -tb, tb, near_plane, far_plane);
789        CHECK_GL_ERROR("SetViewportAndProjection", "glOrtho");
790    }
791
792    // Set the modelview transform for drawing data.
793    glMatrixMode(GL_MODELVIEW);
794    CHECK_GL_ERROR("SetDataTransform", "glMatrixMode");
795    glLoadIdentity();
796    CHECK_GL_ERROR("SetDataTransform", "glLoadIdentity");
797    if (m_Perspective) {
798        glTranslated(0.0, 0.0, -near_plane);
799    } else {
800        glTranslated(0.0, 0.0, -0.5 * m_VolumeDiameter);
801    }
802    CHECK_GL_ERROR("SetDataTransform", "glTranslated");
803    // Get axes the correct way around (z upwards, y into screen)
804    glRotated(-90.0, 1.0, 0.0, 0.0);
805    CHECK_GL_ERROR("SetDataTransform", "glRotated");
806    glRotated(-m_Tilt, 1.0, 0.0, 0.0);
807    CHECK_GL_ERROR("SetDataTransform", "glRotated");
808    glRotated(m_Pan, 0.0, 0.0, 1.0);
809    CHECK_GL_ERROR("SetDataTransform", "CopyToOpenGL");
810    if (m_Perspective) {
811        glTranslated(m_Translation.GetX(),
812                     m_Translation.GetY(),
813                     m_Translation.GetZ());
814        CHECK_GL_ERROR("SetDataTransform", "glTranslated");
815    }
816
817    // Save projection matrix.
818    glGetDoublev(GL_PROJECTION_MATRIX, projection_matrix);
819    CHECK_GL_ERROR("SetDataTransform", "glGetDoublev");
820
821    // Save viewport coordinates.
822    glGetIntegerv(GL_VIEWPORT, viewport);
823    CHECK_GL_ERROR("SetDataTransform", "glGetIntegerv");
824
825    // Save modelview matrix.
826    glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
827    CHECK_GL_ERROR("SetDataTransform", "glGetDoublev");
828
829    if (!m_Perspective) {
830        // Adjust the translation so we don't change the Z position of the model
831        double X, Y, Z;
832        gluProject(m_Translation.GetX(),
833                   m_Translation.GetY(),
834                   m_Translation.GetZ(),
835                   modelview_matrix, projection_matrix, viewport,
836                   &X, &Y, &Z);
837        double Tx, Ty, Tz;
838        gluUnProject(X, Y, 0.5, modelview_matrix, projection_matrix, viewport,
839                     &Tx, &Ty, &Tz);
840        glTranslated(Tx, Ty, Tz);
841        CHECK_GL_ERROR("SetDataTransform", "glTranslated");
842        glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
843    }
844
845    glEnable(GL_DEPTH_TEST);
846    CHECK_GL_ERROR("SetDataTransform", "glEnable GL_DEPTH_TEST");
847
848    if (m_Textured) {
849        glBindTexture(GL_TEXTURE_2D, m_Texture);
850        glEnable(GL_TEXTURE_2D);
851        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
852        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_WRAP_S");
853        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
854        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_WRAP_T");
855        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
856        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_MAG_FILTER");
857        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
858                        GL_LINEAR_MIPMAP_LINEAR);
859        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_MIN_FILTER");
860        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
861    } else {
862        glDisable(GL_TEXTURE_2D);
863    }
864    if (m_Fog) {
865        glFogf(GL_FOG_START, near_plane);
866        glFogf(GL_FOG_END, near_plane + m_VolumeDiameter);
867        glEnable(GL_FOG);
868    } else {
869        glDisable(GL_FOG);
870    }
871
872    glEnable(GL_BLEND);
873    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
874    if (m_AntiAlias) {
875        glEnable(GL_LINE_SMOOTH);
876    } else {
877        glDisable(GL_LINE_SMOOTH);
878    }
879}
880
881void GLACanvas::SetIndicatorTransform()
882{
883    list_flags |= NEVER_CACHE;
884
885    // Set the modelview transform and projection for drawing indicators.
886
887    glDisable(GL_DEPTH_TEST);
888    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_DEPTH_TEST");
889    glDisable(GL_FOG);
890    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_FOG");
891
892    // Just a simple 2D projection.
893    glMatrixMode(GL_PROJECTION);
894    CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
895    glLoadIdentity();
896    CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity (2)");
897    gluOrtho2D(0, x_size, 0, y_size);
898    CHECK_GL_ERROR("SetIndicatorTransform", "gluOrtho2D");
899
900    // No modelview transform.
901    glMatrixMode(GL_MODELVIEW);
902    CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
903    glLoadIdentity();
904    CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity");
905
906    glDisable(GL_TEXTURE_2D);
907    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_TEXTURE_2D");
908    glDisable(GL_BLEND);
909    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_BLEND");
910    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
911    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_S");
912    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
913    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_T");
914    glAlphaFunc(GL_GREATER, 0.5f);
915    CHECK_GL_ERROR("SetIndicatorTransform", "glAlphaFunc");
916    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
917    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MAG_FILTER");
918    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
919    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MIN_FILTER");
920    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
921    CHECK_GL_ERROR("SetIndicatorTransform", "glHint");
922}
923
924void GLACanvas::FinishDrawing()
925{
926    // Complete a redraw operation.
927
928    if (double_buffered) {
929        SwapBuffers();
930    } else {
931        glFlush();
932        CHECK_GL_ERROR("FinishDrawing", "glFlush");
933    }
934}
935
936void GLACanvas::DrawList(unsigned int l)
937{
938    // FIXME: uncomment to disable use of lists for debugging:
939    // GenerateList(l); return;
940    if (l >= drawing_lists.size()) drawing_lists.resize(l + 1);
941
942    // We generate the OpenGL lists lazily to minimise delays on startup.
943    // So check if we need to generate the OpenGL list now.
944    if (drawing_lists[l].need_to_generate()) {
945        // Clear list_flags so that we can note what conditions to invalidate
946        // the cached OpenGL list on.
947        list_flags = 0;
948
949#ifdef GLA_DEBUG
950        printf("generating list #%u... ", l);
951        m_Vertices = 0;
952#endif
953        GenerateList(l);
954#ifdef GLA_DEBUG
955        printf("done (%d vertices)\n", m_Vertices);
956#endif
957        drawing_lists[l].finalise(list_flags);
958    }
959
960    if (!drawing_lists[l].DrawList()) {
961        // That list isn't cached (which means it probably can't usefully be
962        // cached).
963        GenerateList(l);
964    }
965}
966
967void GLACanvas::DrawListZPrepass(unsigned int l)
968{
969    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
970    DrawList(l);
971    glDepthMask(GL_FALSE);
972    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
973    glDepthFunc(GL_EQUAL);
974    DrawList(l);
975    glDepthMask(GL_TRUE);
976    glDepthFunc(GL_LESS);
977}
978
979void GLACanvas::DrawList2D(unsigned int l, glaCoord x, glaCoord y, Double rotation)
980{
981    glMatrixMode(GL_PROJECTION);
982    CHECK_GL_ERROR("DrawList2D", "glMatrixMode");
983    glPushMatrix();
984    CHECK_GL_ERROR("DrawList2D", "glPushMatrix");
985    glTranslated(x, y, 0);
986    CHECK_GL_ERROR("DrawList2D", "glTranslated");
987    if (rotation != 0.0) {
988        glRotated(rotation, 0, 0, -1);
989        CHECK_GL_ERROR("DrawList2D", "glRotated");
990    }
991    DrawList(l);
992    glMatrixMode(GL_PROJECTION);
993    CHECK_GL_ERROR("DrawList2D", "glMatrixMode 2");
994    glPopMatrix();
995    CHECK_GL_ERROR("DrawList2D", "glPopMatrix");
996}
997
998void GLACanvas::SetColour(const GLAPen& pen, double rgb_scale)
999{
1000    // Set the colour for subsequent operations.
1001    glColor4f(pen.GetRed() * rgb_scale, pen.GetGreen() * rgb_scale,
1002              pen.GetBlue() * rgb_scale, alpha);
1003}
1004
1005void GLACanvas::SetColour(const GLAPen& pen)
1006{
1007    // Set the colour for subsequent operations.
1008    glColor4d(pen.components[0], pen.components[1], pen.components[2], alpha);
1009}
1010
1011void GLACanvas::SetColour(gla_colour colour, double rgb_scale)
1012{
1013    // Set the colour for subsequent operations.
1014    rgb_scale /= 255.0;
1015    glColor4f(COLOURS[colour].r * rgb_scale,
1016              COLOURS[colour].g * rgb_scale,
1017              COLOURS[colour].b * rgb_scale,
1018              alpha);
1019}
1020
1021void GLACanvas::SetColour(gla_colour colour)
1022{
1023    // Set the colour for subsequent operations.
1024    if (alpha == 1.0) {
1025        glColor3ubv(&COLOURS[colour].r);
1026    } else {
1027        glColor4ub(COLOURS[colour].r,
1028                   COLOURS[colour].g,
1029                   COLOURS[colour].b,
1030                   (unsigned char)(255 * alpha));
1031    }
1032}
1033
1034void GLACanvas::DrawText(glaCoord x, glaCoord y, glaCoord z, const wxString& str)
1035{
1036    // Draw a text string on the current buffer in the current font.
1037    glRasterPos3d(x, y, z);
1038    CHECK_GL_ERROR("DrawText", "glRasterPos3d");
1039    m_Font.write_string(str.data(), str.size());
1040}
1041
1042void GLACanvas::DrawIndicatorText(int x, int y, const wxString& str)
1043{
1044    glRasterPos2d(x, y);
1045    CHECK_GL_ERROR("DrawIndicatorText", "glRasterPos2d");
1046    m_Font.write_string(str.data(), str.size());
1047}
1048
1049void GLACanvas::GetTextExtent(const wxString& str, int * x_ext, int * y_ext) const
1050{
1051    m_Font.get_text_extent(str.data(), str.size(), x_ext, y_ext);
1052}
1053
1054void GLACanvas::BeginQuadrilaterals()
1055{
1056    // Commence drawing of quadrilaterals.
1057
1058    glBegin(GL_QUADS);
1059}
1060
1061void GLACanvas::EndQuadrilaterals()
1062{
1063    // Finish drawing of quadrilaterals.
1064
1065    glEnd();
1066    CHECK_GL_ERROR("EndQuadrilaterals", "glEnd GL_QUADS");
1067}
1068
1069void GLACanvas::BeginLines()
1070{
1071    // Commence drawing of a set of lines.
1072
1073    glBegin(GL_LINES);
1074}
1075
1076void GLACanvas::EndLines()
1077{
1078    // Finish drawing of a set of lines.
1079
1080    glEnd();
1081    CHECK_GL_ERROR("EndLines", "glEnd GL_LINES");
1082}
1083
1084void GLACanvas::BeginTriangles()
1085{
1086    // Commence drawing of a set of triangles.
1087
1088    glBegin(GL_TRIANGLES);
1089}
1090
1091void GLACanvas::EndTriangles()
1092{
1093    // Finish drawing of a set of triangles.
1094
1095    glEnd();
1096    CHECK_GL_ERROR("EndTriangles", "glEnd GL_TRIANGLES");
1097}
1098
1099void GLACanvas::BeginTriangleStrip()
1100{
1101    // Commence drawing of a triangle strip.
1102
1103    glBegin(GL_TRIANGLE_STRIP);
1104}
1105
1106void GLACanvas::EndTriangleStrip()
1107{
1108    // Finish drawing of a triangle strip.
1109
1110    glEnd();
1111    CHECK_GL_ERROR("EndTriangleStrip", "glEnd GL_TRIANGLE_STRIP");
1112}
1113
1114void GLACanvas::BeginPolyline()
1115{
1116    // Commence drawing of a polyline.
1117
1118    glBegin(GL_LINE_STRIP);
1119}
1120
1121void GLACanvas::EndPolyline()
1122{
1123    // Finish drawing of a polyline.
1124
1125    glEnd();
1126    CHECK_GL_ERROR("EndPolyline", "glEnd GL_LINE_STRIP");
1127}
1128
1129void GLACanvas::BeginPolygon()
1130{
1131    // Commence drawing of a polygon.
1132
1133    glBegin(GL_POLYGON);
1134}
1135
1136void GLACanvas::EndPolygon()
1137{
1138    // Finish drawing of a polygon.
1139
1140    glEnd();
1141    CHECK_GL_ERROR("EndPolygon", "glEnd GL_POLYGON");
1142}
1143
1144void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z)
1145{
1146    // Place a vertex for the current object being drawn.
1147
1148#ifdef GLA_DEBUG
1149    m_Vertices++;
1150#endif
1151    glVertex3d(x, y, z);
1152}
1153
1154void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z,
1155                            glaTexCoord tex_x, glaTexCoord tex_y)
1156{
1157    // Place a vertex for the current object being drawn.
1158
1159#ifdef GLA_DEBUG
1160    m_Vertices++;
1161#endif
1162    glTexCoord2i(tex_x, tex_y);
1163    glVertex3d(x, y, z);
1164}
1165
1166void GLACanvas::PlaceIndicatorVertex(glaCoord x, glaCoord y)
1167{
1168    // Place a vertex for the current indicator object being drawn.
1169
1170    PlaceVertex(x, y, 0.0);
1171}
1172
1173void GLACanvas::BeginBlobs()
1174{
1175    // Commence drawing of a set of blobs.
1176    if (blob_method == SPRITE) {
1177        glPushAttrib(GL_ENABLE_BIT|GL_POINT_BIT);
1178        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1179        glBindTexture(GL_TEXTURE_2D, m_BlobTexture);
1180        CHECK_GL_ERROR("BeginBlobs", "glBindTexture");
1181        glEnable(GL_ALPHA_TEST);
1182        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_ALPHA_TEST");
1183        glPointSize(8);
1184        CHECK_GL_ERROR("BeginBlobs", "glPointSize");
1185        glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
1186        CHECK_GL_ERROR("BeginBlobs", "glTexEnvi GL_POINT_SPRITE");
1187        glEnable(GL_TEXTURE_2D);
1188        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_TEXTURE_2D");
1189        glEnable(GL_POINT_SPRITE);
1190        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_POINT_SPRITE");
1191        glBegin(GL_POINTS);
1192    } else if (blob_method == POINT) {
1193        glPushAttrib(GL_ENABLE_BIT);
1194        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1195        glEnable(GL_ALPHA_TEST);
1196        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_ALPHA_TEST");
1197        glEnable(GL_POINT_SMOOTH);
1198        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_POINT_SMOOTH");
1199        glBegin(GL_POINTS);
1200    } else {
1201        glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
1202        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1203        SetIndicatorTransform();
1204        glEnable(GL_DEPTH_TEST);
1205        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_DEPTH_TEST");
1206        glBegin(GL_LINES);
1207    }
1208}
1209
1210void GLACanvas::EndBlobs()
1211{
1212    // Finish drawing of a set of blobs.
1213    glEnd();
1214    if (blob_method != LINES) {
1215        CHECK_GL_ERROR("EndBlobs", "glEnd GL_POINTS");
1216    } else {
1217        CHECK_GL_ERROR("EndBlobs", "glEnd GL_LINES");
1218    }
1219    glPopAttrib();
1220    CHECK_GL_ERROR("EndBlobs", "glPopAttrib");
1221}
1222
1223void GLACanvas::DrawBlob(glaCoord x, glaCoord y, glaCoord z)
1224{
1225    if (blob_method != LINES) {
1226        // Draw a marker.
1227        PlaceVertex(x, y, z);
1228    } else {
1229        double X, Y, Z;
1230        if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
1231            printf("bad transform\n");
1232            return;
1233        }
1234        // Stuff behind us (in perspective view) will get clipped,
1235        // but we can save effort with a cheap check here.
1236        if (Z <= 0) return;
1237
1238        X -= BLOB_DIAMETER * 0.5;
1239        Y -= BLOB_DIAMETER * 0.5;
1240
1241        PlaceVertex(X, Y + 1, Z);
1242        PlaceVertex(X, Y + (BLOB_DIAMETER - 1), Z);
1243
1244        for (int i = 1; i < (BLOB_DIAMETER - 1); ++i) {
1245            PlaceVertex(X + i, Y, Z);
1246            PlaceVertex(X + i, Y + BLOB_DIAMETER, Z);
1247        }
1248
1249        PlaceVertex(X + (BLOB_DIAMETER - 1), Y + 1, Z);
1250        PlaceVertex(X + (BLOB_DIAMETER - 1), Y + (BLOB_DIAMETER - 1), Z);
1251    }
1252#ifdef GLA_DEBUG
1253    m_Vertices++;
1254#endif
1255}
1256
1257void GLACanvas::DrawBlob(glaCoord x, glaCoord y)
1258{
1259    if (blob_method != LINES) {
1260        // Draw a marker.
1261        PlaceVertex(x, y, 0);
1262    } else {
1263        x -= BLOB_DIAMETER * 0.5;
1264        y -= BLOB_DIAMETER * 0.5;
1265
1266        PlaceVertex(x, y + 1, 0);
1267        PlaceVertex(x, y + (BLOB_DIAMETER - 1), 0);
1268
1269        for (int i = 1; i < (BLOB_DIAMETER - 1); ++i) {
1270            PlaceVertex(x + i, y, 0);
1271            PlaceVertex(x + i, y + BLOB_DIAMETER, 0);
1272        }
1273
1274        PlaceVertex(x + (BLOB_DIAMETER - 1), y + 1, 0);
1275        PlaceVertex(x + (BLOB_DIAMETER - 1), y + (BLOB_DIAMETER - 1), 0);
1276    }
1277#ifdef GLA_DEBUG
1278    m_Vertices++;
1279#endif
1280}
1281
1282void GLACanvas::BeginCrosses()
1283{
1284    // Plot crosses.
1285    if (cross_method == SPRITE) {
1286        glPushAttrib(GL_ENABLE_BIT|GL_POINT_BIT);
1287        CHECK_GL_ERROR("BeginCrosses", "glPushAttrib");
1288        glBindTexture(GL_TEXTURE_2D, m_CrossTexture);
1289        CHECK_GL_ERROR("BeginCrosses", "glBindTexture");
1290        glEnable(GL_ALPHA_TEST);
1291        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_ALPHA_TEST");
1292        glPointSize(8);
1293        CHECK_GL_ERROR("BeginCrosses", "glPointSize");
1294        glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
1295        CHECK_GL_ERROR("BeginCrosses", "glTexEnvi GL_POINT_SPRITE");
1296        glEnable(GL_TEXTURE_2D);
1297        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_TEXTURE_2D");
1298        glEnable(GL_POINT_SPRITE);
1299        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_POINT_SPRITE");
1300        glBegin(GL_POINTS);
1301    } else {
1302        // To get the crosses to appear at a constant size and orientation on
1303        // screen, we plot them in the Indicator transform coordinates (which
1304        // unfortunately means they can't be usefully put in an opengl display
1305        // list).
1306        glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
1307        CHECK_GL_ERROR("BeginCrosses", "glPushAttrib 2");
1308        SetIndicatorTransform();
1309        glEnable(GL_DEPTH_TEST);
1310        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_DEPTH_TEST");
1311        glBegin(GL_LINES);
1312    }
1313}
1314
1315void GLACanvas::EndCrosses()
1316{
1317    glEnd();
1318    if (cross_method == SPRITE) {
1319        CHECK_GL_ERROR("EndCrosses", "glEnd GL_POINTS");
1320    } else {
1321        CHECK_GL_ERROR("EndCrosses", "glEnd GL_LINES");
1322    }
1323    glPopAttrib();
1324    CHECK_GL_ERROR("EndCrosses", "glPopAttrib");
1325}
1326
1327void GLACanvas::DrawCross(glaCoord x, glaCoord y, glaCoord z)
1328{
1329    if (cross_method == SPRITE) {
1330        // Draw a marker.
1331        PlaceVertex(x, y, z);
1332    } else {
1333        double X, Y, Z;
1334        if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
1335            printf("bad transform\n");
1336            return;
1337        }
1338        // Stuff behind us (in perspective view) will get clipped,
1339        // but we can save effort with a cheap check here.
1340        if (Z <= 0) return;
1341
1342        // Round to integers before adding on the offsets for the
1343        // cross arms to avoid uneven crosses.
1344        X = rint(X);
1345        Y = rint(Y);
1346        PlaceVertex(X - 3, Y - 3, Z);
1347        PlaceVertex(X + 3, Y + 3, Z);
1348        PlaceVertex(X - 3, Y + 3, Z);
1349        PlaceVertex(X + 3, Y - 3, Z);
1350    }
1351#ifdef GLA_DEBUG
1352    m_Vertices++;
1353#endif
1354}
1355
1356void GLACanvas::DrawRing(glaCoord x, glaCoord y)
1357{
1358    // Draw an unfilled circle
1359    const Double radius = 4;
1360    assert(m_Quadric);
1361    glMatrixMode(GL_MODELVIEW);
1362    CHECK_GL_ERROR("DrawRing", "glMatrixMode");
1363    glPushMatrix();
1364    CHECK_GL_ERROR("DrawRing", "glPushMatrix");
1365    glTranslated(x, y, 0.0);
1366    CHECK_GL_ERROR("DrawRing", "glTranslated");
1367    gluDisk(m_Quadric, radius - 1.0, radius, 12, 1);
1368    CHECK_GL_ERROR("DrawRing", "gluDisk");
1369    glPopMatrix();
1370    CHECK_GL_ERROR("DrawRing", "glPopMatrix");
1371}
1372
1373void GLACanvas::DrawRectangle(gla_colour edge, gla_colour fill,
1374                              glaCoord x0, glaCoord y0, glaCoord w, glaCoord h)
1375{
1376    // Draw a filled rectangle with an edge in the indicator plane.
1377    // (x0, y0) specify the bottom-left corner of the rectangle and (w, h) the
1378    // size.
1379
1380    SetColour(fill);
1381    BeginQuadrilaterals();
1382    PlaceIndicatorVertex(x0, y0);
1383    PlaceIndicatorVertex(x0 + w, y0);
1384    PlaceIndicatorVertex(x0 + w, y0 + h);
1385    PlaceIndicatorVertex(x0, y0 + h);
1386    EndQuadrilaterals();
1387
1388    if (edge != fill) {
1389        SetColour(edge);
1390        BeginLines();
1391        PlaceIndicatorVertex(x0, y0);
1392        PlaceIndicatorVertex(x0 + w, y0);
1393        PlaceIndicatorVertex(x0 + w, y0 + h);
1394        PlaceIndicatorVertex(x0, y0 + h);
1395        EndLines();
1396    }
1397}
1398
1399void
1400GLACanvas::DrawShadedRectangle(const GLAPen & fill_bot, const GLAPen & fill_top,
1401                               glaCoord x0, glaCoord y0,
1402                               glaCoord w, glaCoord h)
1403{
1404    // Draw a graduated filled rectangle in the indicator plane.
1405    // (x0, y0) specify the bottom-left corner of the rectangle and (w, h) the
1406    // size.
1407
1408    glShadeModel(GL_SMOOTH);
1409    CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_SMOOTH");
1410    BeginQuadrilaterals();
1411    SetColour(fill_bot);
1412    PlaceIndicatorVertex(x0, y0);
1413    PlaceIndicatorVertex(x0 + w, y0);
1414    SetColour(fill_top);
1415    PlaceIndicatorVertex(x0 + w, y0 + h);
1416    PlaceIndicatorVertex(x0, y0 + h);
1417    EndQuadrilaterals();
1418    glShadeModel(GL_FLAT);
1419    CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_FLAT");
1420}
1421
1422void GLACanvas::DrawCircle(gla_colour edge, gla_colour fill,
1423                           glaCoord cx, glaCoord cy, glaCoord radius)
1424{
1425    // Draw a filled circle with an edge.
1426    SetColour(fill);
1427    glMatrixMode(GL_MODELVIEW);
1428    CHECK_GL_ERROR("DrawCircle", "glMatrixMode");
1429    glPushMatrix();
1430    CHECK_GL_ERROR("DrawCircle", "glPushMatrix");
1431    glTranslated(cx, cy, 0.0);
1432    CHECK_GL_ERROR("DrawCircle", "glTranslated");
1433    assert(m_Quadric);
1434    gluDisk(m_Quadric, 0.0, radius, 36, 1);
1435    CHECK_GL_ERROR("DrawCircle", "gluDisk");
1436    SetColour(edge);
1437    gluDisk(m_Quadric, radius - 1.0, radius, 36, 1);
1438    CHECK_GL_ERROR("DrawCircle", "gluDisk (2)");
1439    glPopMatrix();
1440    CHECK_GL_ERROR("DrawCircle", "glPopMatrix");
1441}
1442
1443void GLACanvas::DrawSemicircle(gla_colour edge, gla_colour fill,
1444                               glaCoord cx, glaCoord cy,
1445                               glaCoord radius, glaCoord start)
1446{
1447    // Draw a filled semicircle with an edge.
1448    // The semicircle extends from "start" deg to "start"+180 deg (increasing
1449    // clockwise, 0 deg upwards).
1450    SetColour(fill);
1451    glMatrixMode(GL_MODELVIEW);
1452    CHECK_GL_ERROR("DrawSemicircle", "glMatrixMode");
1453    glPushMatrix();
1454    CHECK_GL_ERROR("DrawSemicircle", "glPushMatrix");
1455    glTranslated(cx, cy, 0.0);
1456    CHECK_GL_ERROR("DrawSemicircle", "glTranslated");
1457    assert(m_Quadric);
1458    gluPartialDisk(m_Quadric, 0.0, radius, 36, 1, start, 180.0);
1459    CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk");
1460    SetColour(edge);
1461    gluPartialDisk(m_Quadric, radius - 1.0, radius, 36, 1, start, 180.0);
1462    CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk (2)");
1463    glPopMatrix();
1464    CHECK_GL_ERROR("DrawSemicircle", "glPopMatrix");
1465}
1466
1467void
1468GLACanvas::DrawTriangle(gla_colour edge, gla_colour fill,
1469                        const Vector3 &p0, const Vector3 &p1, const Vector3 &p2)
1470{
1471    // Draw a filled triangle with an edge.
1472
1473    SetColour(fill);
1474    BeginTriangles();
1475    PlaceIndicatorVertex(p0.GetX(), p0.GetY());
1476    PlaceIndicatorVertex(p1.GetX(), p1.GetY());
1477    PlaceIndicatorVertex(p2.GetX(), p2.GetY());
1478    EndTriangles();
1479
1480    SetColour(edge);
1481    glBegin(GL_LINE_STRIP);
1482    PlaceIndicatorVertex(p0.GetX(), p0.GetY());
1483    PlaceIndicatorVertex(p1.GetX(), p1.GetY());
1484    PlaceIndicatorVertex(p2.GetX(), p2.GetY());
1485    glEnd();
1486    CHECK_GL_ERROR("DrawTriangle", "glEnd GL_LINE_STRIP");
1487}
1488
1489void GLACanvas::EnableDashedLines()
1490{
1491    // Enable dashed lines, and start drawing in them.
1492
1493    glLineStipple(1, 0x3333);
1494    CHECK_GL_ERROR("EnableDashedLines", "glLineStipple");
1495    glEnable(GL_LINE_STIPPLE);
1496    CHECK_GL_ERROR("EnableDashedLines", "glEnable GL_LINE_STIPPLE");
1497}
1498
1499void GLACanvas::DisableDashedLines()
1500{
1501    glDisable(GL_LINE_STIPPLE);
1502    CHECK_GL_ERROR("DisableDashedLines", "glDisable GL_LINE_STIPPLE");
1503}
1504
1505bool GLACanvas::Transform(const Vector3 & v,
1506                          double* x_out, double* y_out, double* z_out) const
1507{
1508    // Convert from data coordinates to screen coordinates.
1509
1510    // Perform the projection.
1511    return gluProject(v.GetX(), v.GetY(), v.GetZ(),
1512                      modelview_matrix, projection_matrix, viewport,
1513                      x_out, y_out, z_out);
1514}
1515
1516void GLACanvas::ReverseTransform(Double x, Double y,
1517                                 double* x_out, double* y_out, double* z_out) const
1518{
1519    // Convert from screen coordinates to data coordinates.
1520
1521    // Perform the projection.
1522    gluUnProject(x, y, 0.0, modelview_matrix, projection_matrix, viewport,
1523                 x_out, y_out, z_out);
1524    CHECK_GL_ERROR("ReverseTransform", "gluUnProject");
1525}
1526
1527Double GLACanvas::SurveyUnitsAcrossViewport() const
1528{
1529    // Measure the current viewport in survey units, taking into account the
1530    // current display scale.
1531
1532    assert(m_Scale != 0.0);
1533    list_flags |= INVALIDATE_ON_SCALE;
1534    return m_VolumeDiameter / m_Scale;
1535}
1536
1537void GLACanvas::ToggleSmoothShading()
1538{
1539    m_SmoothShading = !m_SmoothShading;
1540}
1541
1542void GLACanvas::ToggleTextured()
1543{
1544    m_Textured = !m_Textured;
1545    if (m_Textured && m_Texture == 0) {
1546        glGenTextures(1, &m_Texture);
1547        CHECK_GL_ERROR("ToggleTextured", "glGenTextures");
1548
1549        glBindTexture(GL_TEXTURE_2D, m_Texture);
1550        CHECK_GL_ERROR("ToggleTextured", "glBindTexture");
1551
1552        ::wxInitAllImageHandlers();
1553
1554        wxImage img;
1555        wxString texture(wmsg_cfgpth());
1556        texture += wxCONFIG_PATH_SEPARATOR;
1557        texture += wxT("images");
1558        texture += wxCONFIG_PATH_SEPARATOR;
1559        texture += wxT("texture.png");
1560        if (!img.LoadFile(texture, wxBITMAP_TYPE_PNG)) {
1561            // FIXME
1562            fprintf(stderr, "Couldn't load image.\n");
1563            exit(1);
1564        }
1565
1566        // Generate mipmaps.
1567        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, // was GL_LUMINANCE
1568                          img.GetWidth(), img.GetHeight(),
1569                          GL_RGB, GL_UNSIGNED_BYTE, img.GetData());
1570        CHECK_GL_ERROR("ToggleTextured", "gluBuild2DMipmaps");
1571
1572        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1573        CHECK_GL_ERROR("ToggleTextured", "glTexEnvi");
1574    }
1575}
1576
1577bool GLACanvas::SaveScreenshot(const wxString & fnm, wxBitmapType type) const
1578{
1579    const int width = x_size;
1580    const int height = y_size;
1581    unsigned char *pixels = (unsigned char *)malloc(3 * width * (height + 1));
1582    if (!pixels) return false;
1583    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
1584    CHECK_GL_ERROR("SaveScreenshot", "glReadPixels");
1585    unsigned char * tmp_row = pixels + 3 * width * height;
1586    // We need to flip the image vertically - this approach should be more
1587    // efficient than using wxImage::Mirror(false) as that creates a new
1588    // wxImage object.
1589    for (int y = height / 2 - 1; y >= 0; --y) {
1590        unsigned char * upper = pixels + 3 * width * y;
1591        unsigned char * lower = pixels + 3 * width * (height - y - 1);
1592        memcpy(tmp_row, upper, 3 * width);
1593        memcpy(upper, lower, 3 * width);
1594        memcpy(lower, tmp_row, 3 * width);
1595    }
1596    // NB wxImage constructor calls free(pixels) for us.
1597    wxImage grab(width, height, pixels);
1598    return grab.SaveFile(fnm, type);
1599}
1600
1601bool GLACanvas::CheckVisualFidelity(const unsigned char * target) const
1602{
1603    unsigned char pixels[3 * 8 * 8];
1604    if (double_buffered) {
1605        glReadBuffer(GL_BACK);
1606        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1607    }
1608    glReadPixels(x_size / 2 - 4, y_size / 2 - 5, 8, 8,
1609                 GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
1610    CHECK_GL_ERROR("CheckVisualFidelity", "glReadPixels");
1611    if (double_buffered) {
1612        glReadBuffer(GL_FRONT);
1613        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1614    }
1615#if 0
1616    // Show what got drawn and what was expected for debugging.
1617    for (int y = 0; y < 8; ++y) {
1618        for (int x = 0; x < 8; ++x) {
1619            int o = (y * 8 + x) * 3;
1620            printf("%c", pixels[o] ? 'X' : '.');
1621        }
1622        printf(" ");
1623        for (int x = 0; x < 8; ++x) {
1624            int o = (y * 8 + x) * 3;
1625            printf("%c", target[o] ? 'X' : '.');
1626        }
1627        printf("\n");
1628    }
1629#endif
1630    return (memcmp(pixels, target, sizeof(pixels)) == 0);
1631}
1632
1633void GLACanvas::ReadPixels(int width, int height, unsigned char * buf) const
1634{
1635    CHECK_GL_ERROR("ReadPixels", "glReadPixels");
1636    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)buf);
1637}
1638
1639void GLACanvas::PolygonOffset(bool on) const
1640{
1641    if (on) {
1642        glPolygonOffset(1.0, 1.0);
1643        glEnable(GL_POLYGON_OFFSET_FILL);
1644    } else {
1645        glDisable(GL_POLYGON_OFFSET_FILL);
1646    }
1647}
Note: See TracBrowser for help on using the repository browser.