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

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

Support drawing blobs using point sprites

About 5 times faster than using lines on my netbook

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