source: git/src/gla-gl.cc @ 236a1b1

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

Add --stereo option

Supports arguments "buffers" (OpenGL stereo buffers), "anaglyph"
(for use with coloured glasses) and "2up" (suitable for use with
a "cardboard" headset).

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