source: git/src/gla-gl.cc @ 8d74d05

stereo-2025
Last change on this file since 8d74d05 was 9284d37, checked in by Olly Betts <olly@…>, 4 months ago

Allow exaggerating Z in aven

Add a spin control to the toolbar which allows setting a Z scale
factor from 0.1 and 10.0.

Fixes #49

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