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

stereo-2025
Last change on this file since ff0f549 was a3f83057, checked in by Olly Betts <olly@…>, 7 months ago

Use C++11 member initialisation where sensible

  • Property mode set to 100644
File size: 49.5 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
[7eac11e]7//  Copyright (C) 2003-2022 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);
[2491b8c]873    CHECK_GL_ERROR("SetDataTransform", "CopyToOpenGL");
[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    }
[dde4fe7]880
[de24f93]881    // Save projection matrix.
882    glGetDoublev(GL_PROJECTION_MATRIX, projection_matrix);
883    CHECK_GL_ERROR("SetDataTransform", "glGetDoublev");
884
885    // Save viewport coordinates.
886    glGetIntegerv(GL_VIEWPORT, viewport);
887    CHECK_GL_ERROR("SetDataTransform", "glGetIntegerv");
888
889    // Save modelview matrix.
[dde4fe7]890    glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
891    CHECK_GL_ERROR("SetDataTransform", "glGetDoublev");
[de24f93]892
[5092ee7]893    if (!m_Perspective) {
894        // Adjust the translation so we don't change the Z position of the model
[f6d8375]895        double X, Y, Z;
[d67450e]896        gluProject(m_Translation.GetX(),
897                   m_Translation.GetY(),
898                   m_Translation.GetZ(),
[5092ee7]899                   modelview_matrix, projection_matrix, viewport,
900                   &X, &Y, &Z);
[f6d8375]901        double Tx, Ty, Tz;
[5092ee7]902        gluUnProject(X, Y, 0.5, modelview_matrix, projection_matrix, viewport,
903                     &Tx, &Ty, &Tz);
904        glTranslated(Tx, Ty, Tz);
905        CHECK_GL_ERROR("SetDataTransform", "glTranslated");
906        glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
907    }
[096e56c]908
[de24f93]909    glEnable(GL_DEPTH_TEST);
910    CHECK_GL_ERROR("SetDataTransform", "glEnable GL_DEPTH_TEST");
[c60062d]911
[a517825]912    if (m_Textured) {
913        glBindTexture(GL_TEXTURE_2D, m_Texture);
914        glEnable(GL_TEXTURE_2D);
915        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
916        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_WRAP_S");
917        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
918        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_WRAP_T");
919        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
920        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_MAG_FILTER");
[ecbdd96]921        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
922                        GL_LINEAR_MIPMAP_LINEAR);
[a517825]923        CHECK_GL_ERROR("ToggleTextured", "glTexParameteri GL_TEXTURE_MIN_FILTER");
924        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
925    } else {
926        glDisable(GL_TEXTURE_2D);
927    }
[c60062d]928    if (m_Fog) {
929        glFogf(GL_FOG_START, near_plane);
930        glFogf(GL_FOG_END, near_plane + m_VolumeDiameter);
931        glEnable(GL_FOG);
[db452ae]932    } else {
933        glDisable(GL_FOG);
934    }
935
[4a1cede]936    glEnable(GL_BLEND);
937    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
[db452ae]938    if (m_AntiAlias) {
939        glEnable(GL_LINE_SMOOTH);
940    } else {
941        glDisable(GL_LINE_SMOOTH);
[c60062d]942    }
[56da40e]943}
944
945void GLACanvas::SetIndicatorTransform()
946{
[db59b02]947    list_flags |= NEVER_CACHE;
948
[bb1f293]949    // Set the modelview transform and projection for drawing indicators.
[56da40e]950
[bb1f293]951    glDisable(GL_DEPTH_TEST);
952    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_DEPTH_TEST");
[c60062d]953    glDisable(GL_FOG);
954    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_FOG");
[bb1f293]955
[78924eb]956    // Just a simple 2D projection.
[bb1f293]957    glMatrixMode(GL_PROJECTION);
958    CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
959    glLoadIdentity();
960    CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity (2)");
[6cf4daa]961    gluOrtho2D(0, x_size, 0, y_size);
[bb1f293]962    CHECK_GL_ERROR("SetIndicatorTransform", "gluOrtho2D");
[a517825]963
[78924eb]964    // No modelview transform.
965    glMatrixMode(GL_MODELVIEW);
966    CHECK_GL_ERROR("SetIndicatorTransform", "glMatrixMode");
967    glLoadIdentity();
968    CHECK_GL_ERROR("SetIndicatorTransform", "glLoadIdentity");
969
[a517825]970    glDisable(GL_TEXTURE_2D);
[6adffadf]971    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_TEXTURE_2D");
[e4d40792]972    glDisable(GL_BLEND);
[6adffadf]973    CHECK_GL_ERROR("SetIndicatorTransform", "glDisable GL_BLEND");
[36c3285]974    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
[9baa53a]975    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_S");
[36c3285]976    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
[9baa53a]977    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_WRAP_T");
[36c3285]978    glAlphaFunc(GL_GREATER, 0.5f);
[9baa53a]979    CHECK_GL_ERROR("SetIndicatorTransform", "glAlphaFunc");
[096e56c]980    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
[9baa53a]981    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MAG_FILTER");
[36c3285]982    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
[9baa53a]983    CHECK_GL_ERROR("SetIndicatorTransform", "glTexParameteri GL_TEXTURE_MIN_FILTER");
[36c3285]984    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
[9baa53a]985    CHECK_GL_ERROR("SetIndicatorTransform", "glHint");
[56da40e]986}
987
988void GLACanvas::FinishDrawing()
989{
990    // Complete a redraw operation.
[096e56c]991
[c293aa9]992    if (double_buffered) {
993        SwapBuffers();
994    } else {
995        glFlush();
996        CHECK_GL_ERROR("FinishDrawing", "glFlush");
997    }
[56da40e]998}
999
[d2fcc9b]1000void GLACanvas::DrawList(unsigned int l)
[56da40e]1001{
[4ba80e0]1002    // FIXME: uncomment to disable use of lists for debugging:
1003    // GenerateList(l); return;
[d2fcc9b]1004    if (l >= drawing_lists.size()) drawing_lists.resize(l + 1);
[bae6a7c]1005
[d2fcc9b]1006    // We generate the OpenGL lists lazily to minimise delays on startup.
1007    // So check if we need to generate the OpenGL list now.
[620c0c9]1008    if (drawing_lists[l].need_to_generate()) {
[db59b02]1009        // Clear list_flags so that we can note what conditions to invalidate
1010        // the cached OpenGL list on.
1011        list_flags = 0;
[620c0c9]1012
1013#ifdef GLA_DEBUG
1014        printf("generating list #%u... ", l);
1015        m_Vertices = 0;
1016#endif
[d2fcc9b]1017        GenerateList(l);
[edb6576]1018#ifdef GLA_DEBUG
[bae6a7c]1019        printf("done (%d vertices)\n", m_Vertices);
[edb6576]1020#endif
[620c0c9]1021        drawing_lists[l].finalise(list_flags);
[bae6a7c]1022    }
[ee78822]1023
[620c0c9]1024    if (!drawing_lists[l].DrawList()) {
1025        // That list isn't cached (which means it probably can't usefully be
1026        // cached).
[db59b02]1027        GenerateList(l);
1028    }
[56da40e]1029}
1030
[11fe902]1031void GLACanvas::DrawListZPrepass(unsigned int l)
1032{
1033    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
1034    DrawList(l);
1035    glDepthMask(GL_FALSE);
1036    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
1037    glDepthFunc(GL_EQUAL);
1038    DrawList(l);
1039    glDepthMask(GL_TRUE);
1040    glDepthFunc(GL_LESS);
1041}
1042
[147847c]1043void GLACanvas::DrawList2D(unsigned int l, glaCoord x, glaCoord y, double rotation)
[76dd228]1044{
1045    glMatrixMode(GL_PROJECTION);
1046    CHECK_GL_ERROR("DrawList2D", "glMatrixMode");
1047    glPushMatrix();
1048    CHECK_GL_ERROR("DrawList2D", "glPushMatrix");
1049    glTranslated(x, y, 0);
1050    CHECK_GL_ERROR("DrawList2D", "glTranslated");
1051    if (rotation != 0.0) {
1052        glRotated(rotation, 0, 0, -1);
1053        CHECK_GL_ERROR("DrawList2D", "glRotated");
1054    }
1055    DrawList(l);
1056    glMatrixMode(GL_PROJECTION);
1057    CHECK_GL_ERROR("DrawList2D", "glMatrixMode 2");
1058    glPopMatrix();
1059    CHECK_GL_ERROR("DrawList2D", "glPopMatrix");
1060}
1061
[aa048c3]1062void GLACanvas::SetColour(const GLAPen& pen, double rgb_scale)
[56da40e]1063{
1064    // Set the colour for subsequent operations.
[4a1cede]1065    glColor4f(pen.GetRed() * rgb_scale, pen.GetGreen() * rgb_scale,
1066              pen.GetBlue() * rgb_scale, alpha);
[56da40e]1067}
1068
[aa048c3]1069void GLACanvas::SetColour(const GLAPen& pen)
[f383708]1070{
[aa048c3]1071    // Set the colour for subsequent operations.
[4a1cede]1072    glColor4d(pen.components[0], pen.components[1], pen.components[2], alpha);
[f383708]1073}
1074
[d1ce9bd]1075void GLACanvas::SetColour(gla_colour colour, double rgb_scale)
1076{
1077    // Set the colour for subsequent operations.
1078    rgb_scale /= 255.0;
1079    glColor4f(COLOURS[colour].r * rgb_scale,
1080              COLOURS[colour].g * rgb_scale,
1081              COLOURS[colour].b * rgb_scale,
1082              alpha);
1083}
1084
[aa048c3]1085void GLACanvas::SetColour(gla_colour colour)
[56da40e]1086{
[aa048c3]1087    // Set the colour for subsequent operations.
[4943ae8]1088    if (alpha == 1.0) {
1089        glColor3ubv(&COLOURS[colour].r);
1090    } else {
1091        glColor4ub(COLOURS[colour].r,
1092                   COLOURS[colour].g,
1093                   COLOURS[colour].b,
1094                   (unsigned char)(255 * alpha));
1095    }
[56da40e]1096}
1097
1098void GLACanvas::DrawText(glaCoord x, glaCoord y, glaCoord z, const wxString& str)
1099{
1100    // Draw a text string on the current buffer in the current font.
1101    glRasterPos3d(x, y, z);
[1897247]1102    CHECK_GL_ERROR("DrawText", "glRasterPos3d");
[1aa3fb7]1103    m_Font.write_string(str.data(), str.size());
[56da40e]1104}
1105
[1eeb55a]1106void GLACanvas::DrawIndicatorText(int x, int y, const wxString& str)
[56da40e]1107{
[1aa3fb7]1108    glRasterPos2d(x, y);
1109    CHECK_GL_ERROR("DrawIndicatorText", "glRasterPos2d");
1110    m_Font.write_string(str.data(), str.size());
[56da40e]1111}
1112
[dbd50e2]1113void GLACanvas::GetTextExtent(const wxString& str, int * x_ext, int * y_ext) const
[56da40e]1114{
[1aa3fb7]1115    m_Font.get_text_extent(str.data(), str.size(), x_ext, y_ext);
[56da40e]1116}
1117
1118void GLACanvas::BeginQuadrilaterals()
1119{
1120    // Commence drawing of quadrilaterals.
[096e56c]1121
[56da40e]1122    glBegin(GL_QUADS);
1123}
1124
1125void GLACanvas::EndQuadrilaterals()
1126{
1127    // Finish drawing of quadrilaterals.
[096e56c]1128
[56da40e]1129    glEnd();
[9baa53a]1130    CHECK_GL_ERROR("EndQuadrilaterals", "glEnd GL_QUADS");
[56da40e]1131}
1132
1133void GLACanvas::BeginLines()
1134{
1135    // Commence drawing of a set of lines.
1136
1137    glBegin(GL_LINES);
1138}
1139
1140void GLACanvas::EndLines()
1141{
1142    // Finish drawing of a set of lines.
1143
1144    glEnd();
[9baa53a]1145    CHECK_GL_ERROR("EndLines", "glEnd GL_LINES");
[56da40e]1146}
1147
1148void GLACanvas::BeginTriangles()
1149{
1150    // Commence drawing of a set of triangles.
1151
1152    glBegin(GL_TRIANGLES);
1153}
1154
1155void GLACanvas::EndTriangles()
1156{
1157    // Finish drawing of a set of triangles.
1158
1159    glEnd();
[9baa53a]1160    CHECK_GL_ERROR("EndTriangles", "glEnd GL_TRIANGLES");
[56da40e]1161}
1162
[dde4fe7]1163void GLACanvas::BeginTriangleStrip()
1164{
1165    // Commence drawing of a triangle strip.
1166
1167    glBegin(GL_TRIANGLE_STRIP);
1168}
1169
1170void GLACanvas::EndTriangleStrip()
1171{
1172    // Finish drawing of a triangle strip.
1173
1174    glEnd();
[9baa53a]1175    CHECK_GL_ERROR("EndTriangleStrip", "glEnd GL_TRIANGLE_STRIP");
[dde4fe7]1176}
1177
[56da40e]1178void GLACanvas::BeginPolyline()
1179{
1180    // Commence drawing of a polyline.
1181
1182    glBegin(GL_LINE_STRIP);
1183}
1184
1185void GLACanvas::EndPolyline()
1186{
1187    // Finish drawing of a polyline.
[096e56c]1188
[56da40e]1189    glEnd();
[9baa53a]1190    CHECK_GL_ERROR("EndPolyline", "glEnd GL_LINE_STRIP");
[56da40e]1191}
1192
[0642381]1193void GLACanvas::BeginPolyloop()
1194{
1195    // Commence drawing of a polyloop.
1196
1197    glBegin(GL_LINE_LOOP);
1198}
1199
1200void GLACanvas::EndPolyloop()
1201{
1202    // Finish drawing of a polyloop.
1203
1204    glEnd();
1205    CHECK_GL_ERROR("EndPolyloop", "glEnd GL_LINE_LOOP");
1206}
1207
[45aa1d6]1208void GLACanvas::BeginPolygon()
1209{
1210    // Commence drawing of a polygon.
1211
1212    glBegin(GL_POLYGON);
1213}
1214
1215void GLACanvas::EndPolygon()
1216{
1217    // Finish drawing of a polygon.
[096e56c]1218
[45aa1d6]1219    glEnd();
[9baa53a]1220    CHECK_GL_ERROR("EndPolygon", "glEnd GL_POLYGON");
[45aa1d6]1221}
1222
[51eab3b]1223void GLACanvas::BeginPoints()
1224{
1225    // Commence drawing points.
1226
1227    glPushAttrib(GL_POINT_BIT);
1228    CHECK_GL_ERROR("BeginPoints", "glPushAttrib");
1229    glPointSize(3);
1230    CHECK_GL_ERROR("BeginPoints", "glPointSize");
1231    glBegin(GL_POINTS);
1232}
1233
1234void GLACanvas::EndPoints()
1235{
1236    // Finish drawing points.
1237
1238    glEnd();
1239    CHECK_GL_ERROR("EndPoints", "glEnd GL_POINTS");
1240    glPopAttrib();
1241    CHECK_GL_ERROR("EndPoints", "glPopAttrib");
1242}
1243
[56da40e]1244void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z)
1245{
1246    // Place a vertex for the current object being drawn.
1247
[edb6576]1248#ifdef GLA_DEBUG
1249    m_Vertices++;
1250#endif
[56da40e]1251    glVertex3d(x, y, z);
1252}
1253
[f336ab9]1254void GLACanvas::PlaceVertex(glaCoord x, glaCoord y, glaCoord z,
1255                            glaTexCoord tex_x, glaTexCoord tex_y)
[b839829]1256{
1257    // Place a vertex for the current object being drawn.
1258
1259#ifdef GLA_DEBUG
1260    m_Vertices++;
1261#endif
[ba828d4]1262    glTexCoord2f(tex_x, tex_y);
[b839829]1263    glVertex3d(x, y, z);
1264}
1265
[56da40e]1266void GLACanvas::PlaceIndicatorVertex(glaCoord x, glaCoord y)
1267{
1268    // Place a vertex for the current indicator object being drawn.
1269
[087bc72]1270    PlaceVertex(x, y, 0.0);
[56da40e]1271}
1272
[e633bb1]1273void GLACanvas::BeginBlobs()
[d9b3270]1274{
[fe075d7]1275    // Commence drawing of a set of blobs.
[cab6f11]1276    if (blob_method == SPRITE) {
1277        glPushAttrib(GL_ENABLE_BIT|GL_POINT_BIT);
1278        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1279        glBindTexture(GL_TEXTURE_2D, m_BlobTexture);
1280        CHECK_GL_ERROR("BeginBlobs", "glBindTexture");
1281        glEnable(GL_ALPHA_TEST);
1282        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_ALPHA_TEST");
1283        glPointSize(8);
1284        CHECK_GL_ERROR("BeginBlobs", "glPointSize");
1285        glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
1286        CHECK_GL_ERROR("BeginBlobs", "glTexEnvi GL_POINT_SPRITE");
1287        glEnable(GL_TEXTURE_2D);
1288        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_TEXTURE_2D");
1289        glEnable(GL_POINT_SPRITE);
1290        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_POINT_SPRITE");
1291        glBegin(GL_POINTS);
1292    } else if (blob_method == POINT) {
[78924eb]1293        glPushAttrib(GL_ENABLE_BIT);
1294        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
[4ba80e0]1295        glEnable(GL_ALPHA_TEST);
1296        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_ALPHA_TEST");
1297        glEnable(GL_POINT_SMOOTH);
1298        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_POINT_SMOOTH");
1299        glBegin(GL_POINTS);
1300    } else {
[6662d02]1301        glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
[4ba80e0]1302        CHECK_GL_ERROR("BeginBlobs", "glPushAttrib");
1303        SetIndicatorTransform();
[6f5f9e5]1304        glEnable(GL_DEPTH_TEST);
1305        CHECK_GL_ERROR("BeginBlobs", "glEnable GL_DEPTH_TEST");
[bde8c9a]1306        glBegin(GL_LINES);
[4ba80e0]1307    }
[e633bb1]1308}
[d9b3270]1309
[e633bb1]1310void GLACanvas::EndBlobs()
1311{
[bde8c9a]1312    // Finish drawing of a set of blobs.
1313    glEnd();
[cab6f11]1314    if (blob_method != LINES) {
[bde8c9a]1315        CHECK_GL_ERROR("EndBlobs", "glEnd GL_POINTS");
1316    } else {
1317        CHECK_GL_ERROR("EndBlobs", "glEnd GL_LINES");
[4ba80e0]1318    }
[78924eb]1319    glPopAttrib();
1320    CHECK_GL_ERROR("EndBlobs", "glPopAttrib");
[e633bb1]1321}
[d9b3270]1322
[e633bb1]1323void GLACanvas::DrawBlob(glaCoord x, glaCoord y, glaCoord z)
1324{
[cab6f11]1325    if (blob_method != LINES) {
[4ba80e0]1326        // Draw a marker.
1327        PlaceVertex(x, y, z);
1328    } else {
[f6d8375]1329        double X, Y, Z;
[d67450e]1330        if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
[4ba80e0]1331            printf("bad transform\n");
1332            return;
1333        }
1334        // Stuff behind us (in perspective view) will get clipped,
1335        // but we can save effort with a cheap check here.
1336        if (Z <= 0) return;
1337
[bde8c9a]1338        X -= BLOB_DIAMETER * 0.5;
1339        Y -= BLOB_DIAMETER * 0.5;
1340
1341        PlaceVertex(X, Y + 1, Z);
1342        PlaceVertex(X, Y + (BLOB_DIAMETER - 1), Z);
1343
1344        for (int i = 1; i < (BLOB_DIAMETER - 1); ++i) {
1345            PlaceVertex(X + i, Y, Z);
1346            PlaceVertex(X + i, Y + BLOB_DIAMETER, Z);
1347        }
1348
1349        PlaceVertex(X + (BLOB_DIAMETER - 1), Y + 1, Z);
1350        PlaceVertex(X + (BLOB_DIAMETER - 1), Y + (BLOB_DIAMETER - 1), Z);
[78924eb]1351    }
[95ce35f]1352#ifdef GLA_DEBUG
[78924eb]1353    m_Vertices++;
[95ce35f]1354#endif
[429465a]1355}
1356
[81aea4e]1357void GLACanvas::DrawBlob(glaCoord x, glaCoord y)
1358{
[cab6f11]1359    if (blob_method != LINES) {
[81aea4e]1360        // Draw a marker.
1361        PlaceVertex(x, y, 0);
1362    } else {
[bde8c9a]1363        x -= BLOB_DIAMETER * 0.5;
1364        y -= BLOB_DIAMETER * 0.5;
1365
1366        PlaceVertex(x, y + 1, 0);
1367        PlaceVertex(x, y + (BLOB_DIAMETER - 1), 0);
1368
1369        for (int i = 1; i < (BLOB_DIAMETER - 1); ++i) {
1370            PlaceVertex(x + i, y, 0);
1371            PlaceVertex(x + i, y + BLOB_DIAMETER, 0);
1372        }
1373
1374        PlaceVertex(x + (BLOB_DIAMETER - 1), y + 1, 0);
1375        PlaceVertex(x + (BLOB_DIAMETER - 1), y + (BLOB_DIAMETER - 1), 0);
[81aea4e]1376    }
1377#ifdef GLA_DEBUG
1378    m_Vertices++;
1379#endif
1380}
1381
[86fe6e4]1382void GLACanvas::BeginCrosses()
1383{
[95ce35f]1384    // Plot crosses.
[fe075d7]1385    if (cross_method == SPRITE) {
[e473a81]1386        list_flags |= NEVER_CACHE;
1387        SetDataTransform();
[95ce35f]1388        glPushAttrib(GL_ENABLE_BIT|GL_POINT_BIT);
[9baa53a]1389        CHECK_GL_ERROR("BeginCrosses", "glPushAttrib");
[95ce35f]1390        glBindTexture(GL_TEXTURE_2D, m_CrossTexture);
[9baa53a]1391        CHECK_GL_ERROR("BeginCrosses", "glBindTexture");
[95ce35f]1392        glEnable(GL_ALPHA_TEST);
[9baa53a]1393        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_ALPHA_TEST");
[95ce35f]1394        glPointSize(8);
[9baa53a]1395        CHECK_GL_ERROR("BeginCrosses", "glPointSize");
1396        glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
1397        CHECK_GL_ERROR("BeginCrosses", "glTexEnvi GL_POINT_SPRITE");
[95ce35f]1398        glEnable(GL_TEXTURE_2D);
[9baa53a]1399        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_TEXTURE_2D");
1400        glEnable(GL_POINT_SPRITE);
1401        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_POINT_SPRITE");
[95ce35f]1402        glBegin(GL_POINTS);
1403    } else {
1404        // To get the crosses to appear at a constant size and orientation on
1405        // screen, we plot them in the Indicator transform coordinates (which
1406        // unfortunately means they can't be usefully put in an opengl display
1407        // list).
[6662d02]1408        glPushAttrib(GL_TRANSFORM_BIT|GL_VIEWPORT_BIT|GL_ENABLE_BIT);
[9baa53a]1409        CHECK_GL_ERROR("BeginCrosses", "glPushAttrib 2");
[95ce35f]1410        SetIndicatorTransform();
[200eca7]1411        // Align line drawing to pixel centres to get pixel-perfect rendering
1412        // (graphics card and driver bugs aside).
1413        glTranslated(-0.5, -0.5, 0);
1414        CHECK_GL_ERROR("BeginCrosses", "glTranslated");
[6f5f9e5]1415        glEnable(GL_DEPTH_TEST);
[9baa53a]1416        CHECK_GL_ERROR("BeginCrosses", "glEnable GL_DEPTH_TEST");
[95ce35f]1417        glBegin(GL_LINES);
1418    }
[86fe6e4]1419}
1420
1421void GLACanvas::EndCrosses()
1422{
[95ce35f]1423    glEnd();
[fe075d7]1424    if (cross_method == SPRITE) {
[9baa53a]1425        CHECK_GL_ERROR("EndCrosses", "glEnd GL_POINTS");
1426    } else {
1427        CHECK_GL_ERROR("EndCrosses", "glEnd GL_LINES");
1428    }
[86fe6e4]1429    glPopAttrib();
1430    CHECK_GL_ERROR("EndCrosses", "glPopAttrib");
1431}
1432
1433void GLACanvas::DrawCross(glaCoord x, glaCoord y, glaCoord z)
1434{
[fe075d7]1435    if (cross_method == SPRITE) {
[7e1da12]1436        // Draw a marker.
[95ce35f]1437        PlaceVertex(x, y, z);
1438    } else {
[f6d8375]1439        double X, Y, Z;
[d67450e]1440        if (!Transform(Vector3(x, y, z), &X, &Y, &Z)) {
[95ce35f]1441            printf("bad transform\n");
1442            return;
1443        }
1444        // Stuff behind us (in perspective view) will get clipped,
1445        // but we can save effort with a cheap check here.
[7e1da12]1446        if (Z <= 0) return;
1447
1448        // Round to integers before adding on the offsets for the
1449        // cross arms to avoid uneven crosses.
1450        X = rint(X);
1451        Y = rint(Y);
[200eca7]1452        // Need to extend lines by an extra pixel (which shouldn't get drawn by
1453        // the diamond-exit rule).
[7e1da12]1454        PlaceVertex(X - 3, Y - 3, Z);
[200eca7]1455        PlaceVertex(X + 4, Y + 4, Z);
[7e1da12]1456        PlaceVertex(X - 3, Y + 3, Z);
[200eca7]1457        PlaceVertex(X + 4, Y - 4, Z);
[86fe6e4]1458    }
[78924eb]1459#ifdef GLA_DEBUG
1460    m_Vertices++;
1461#endif
[86fe6e4]1462}
1463
[e633bb1]1464void GLACanvas::DrawRing(glaCoord x, glaCoord y)
[429465a]1465{
[127435f]1466    // Draw an unfilled circle of radius 4
1467
1468    // Round to integers to get an even ring.
1469    x = rint(x);
1470    y = rint(y);
1471
1472    glBegin(GL_LINE_LOOP);
1473    PlaceIndicatorVertex(x + 3.5, y - 1.5);
1474    PlaceIndicatorVertex(x + 1.5, y - 3.5);
1475    PlaceIndicatorVertex(x - 1.5, y - 3.5);
1476    PlaceIndicatorVertex(x - 3.5, y - 1.5);
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    glEnd();
1482    CHECK_GL_ERROR("DrawRing", "glEnd GL_LINE_LOOP");
[d9b3270]1483}
1484
[522e0bd]1485void GLACanvas::DrawRectangle(gla_colour fill, gla_colour edge,
[b49ac56]1486                              glaCoord x0, glaCoord y0, glaCoord w, glaCoord h)
[56da40e]1487{
1488    // Draw a filled rectangle with an edge in the indicator plane.
[ca8c864]1489    // (x0, y0) specify the bottom-left corner of the rectangle and (w, h) the
1490    // size.
[56da40e]1491
[c10dd28]1492    SetColour(fill);
[aa048c3]1493    BeginQuadrilaterals();
[56da40e]1494    PlaceIndicatorVertex(x0, y0);
1495    PlaceIndicatorVertex(x0 + w, y0);
1496    PlaceIndicatorVertex(x0 + w, y0 + h);
1497    PlaceIndicatorVertex(x0, y0 + h);
1498    EndQuadrilaterals();
1499
[aa048c3]1500    if (edge != fill) {
[b49ac56]1501        SetColour(edge);
[522e0bd]1502        BeginPolyline();
[b49ac56]1503        PlaceIndicatorVertex(x0, y0);
1504        PlaceIndicatorVertex(x0 + w, y0);
1505        PlaceIndicatorVertex(x0 + w, y0 + h);
1506        PlaceIndicatorVertex(x0, y0 + h);
[522e0bd]1507        PlaceIndicatorVertex(x0, y0);
[6e1a54e3]1508        EndPolyline();
[c10dd28]1509    }
[56da40e]1510}
1511
[aa048c3]1512void
1513GLACanvas::DrawShadedRectangle(const GLAPen & fill_bot, const GLAPen & fill_top,
1514                               glaCoord x0, glaCoord y0,
1515                               glaCoord w, glaCoord h)
1516{
1517    // Draw a graduated filled rectangle in the indicator plane.
1518    // (x0, y0) specify the bottom-left corner of the rectangle and (w, h) the
1519    // size.
1520
[02aa4d4]1521    glShadeModel(GL_SMOOTH);
[9baa53a]1522    CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_SMOOTH");
[aa048c3]1523    BeginQuadrilaterals();
1524    SetColour(fill_bot);
1525    PlaceIndicatorVertex(x0, y0);
1526    PlaceIndicatorVertex(x0 + w, y0);
1527    SetColour(fill_top);
1528    PlaceIndicatorVertex(x0 + w, y0 + h);
1529    PlaceIndicatorVertex(x0, y0 + h);
1530    EndQuadrilaterals();
[02aa4d4]1531    glShadeModel(GL_FLAT);
[9baa53a]1532    CHECK_GL_ERROR("DrawShadedRectangle", "glShadeModel GL_FLAT");
[aa048c3]1533}
1534
1535void GLACanvas::DrawCircle(gla_colour edge, gla_colour fill,
1536                           glaCoord cx, glaCoord cy, glaCoord radius)
[56da40e]1537{
[087bc72]1538    // Draw a filled circle with an edge.
[56da40e]1539    SetColour(fill);
[78924eb]1540    glMatrixMode(GL_MODELVIEW);
1541    CHECK_GL_ERROR("DrawCircle", "glMatrixMode");
1542    glPushMatrix();
1543    CHECK_GL_ERROR("DrawCircle", "glPushMatrix");
[56da40e]1544    glTranslated(cx, cy, 0.0);
[8326157]1545    CHECK_GL_ERROR("DrawCircle", "glTranslated");
[1b12b82]1546    assert(m_Quadric);
1547    gluDisk(m_Quadric, 0.0, radius, 36, 1);
[8326157]1548    CHECK_GL_ERROR("DrawCircle", "gluDisk");
[56da40e]1549    SetColour(edge);
[1b12b82]1550    gluDisk(m_Quadric, radius - 1.0, radius, 36, 1);
[8326157]1551    CHECK_GL_ERROR("DrawCircle", "gluDisk (2)");
[78924eb]1552    glPopMatrix();
1553    CHECK_GL_ERROR("DrawCircle", "glPopMatrix");
[56da40e]1554}
1555
[aa048c3]1556void GLACanvas::DrawSemicircle(gla_colour edge, gla_colour fill,
[b49ac56]1557                               glaCoord cx, glaCoord cy,
1558                               glaCoord radius, glaCoord start)
[56da40e]1559{
1560    // Draw a filled semicircle with an edge.
[ca8c864]1561    // The semicircle extends from "start" deg to "start"+180 deg (increasing
1562    // clockwise, 0 deg upwards).
[56da40e]1563    SetColour(fill);
[78924eb]1564    glMatrixMode(GL_MODELVIEW);
1565    CHECK_GL_ERROR("DrawSemicircle", "glMatrixMode");
1566    glPushMatrix();
1567    CHECK_GL_ERROR("DrawSemicircle", "glPushMatrix");
[56da40e]1568    glTranslated(cx, cy, 0.0);
[78924eb]1569    CHECK_GL_ERROR("DrawSemicircle", "glTranslated");
[1b12b82]1570    assert(m_Quadric);
1571    gluPartialDisk(m_Quadric, 0.0, radius, 36, 1, start, 180.0);
[78924eb]1572    CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk");
[56da40e]1573    SetColour(edge);
[1b12b82]1574    gluPartialDisk(m_Quadric, radius - 1.0, radius, 36, 1, start, 180.0);
[78924eb]1575    CHECK_GL_ERROR("DrawSemicircle", "gluPartialDisk (2)");
1576    glPopMatrix();
1577    CHECK_GL_ERROR("DrawSemicircle", "glPopMatrix");
[56da40e]1578}
1579
1580void GLACanvas::EnableDashedLines()
1581{
1582    // Enable dashed lines, and start drawing in them.
1583
[9eb58d0]1584    glLineStipple(1, 0x3333);
[8326157]1585    CHECK_GL_ERROR("EnableDashedLines", "glLineStipple");
[56da40e]1586    glEnable(GL_LINE_STIPPLE);
[bb1f293]1587    CHECK_GL_ERROR("EnableDashedLines", "glEnable GL_LINE_STIPPLE");
[56da40e]1588}
1589
1590void GLACanvas::DisableDashedLines()
1591{
1592    glDisable(GL_LINE_STIPPLE);
[bb1f293]1593    CHECK_GL_ERROR("DisableDashedLines", "glDisable GL_LINE_STIPPLE");
[56da40e]1594}
1595
[d67450e]1596bool GLACanvas::Transform(const Vector3 & v,
[147847c]1597                          glaCoord* x_out, glaCoord* y_out, glaCoord* z_out) const
[56da40e]1598{
1599    // Convert from data coordinates to screen coordinates.
[096e56c]1600
[087bc72]1601    // Perform the projection.
[d67450e]1602    return gluProject(v.GetX(), v.GetY(), v.GetZ(),
1603                      modelview_matrix, projection_matrix, viewport,
[6adffadf]1604                      x_out, y_out, z_out);
[56da40e]1605}
1606
[147847c]1607void GLACanvas::ReverseTransform(double x, double y,
1608                                 glaCoord* x_out, glaCoord* y_out, glaCoord* z_out) const
[a2b3d62]1609{
1610    // Convert from screen coordinates to data coordinates.
[096e56c]1611
[a2b3d62]1612    // Perform the projection.
[1b12b82]1613    gluUnProject(x, y, 0.0, modelview_matrix, projection_matrix, viewport,
[b49ac56]1614                 x_out, y_out, z_out);
[8326157]1615    CHECK_GL_ERROR("ReverseTransform", "gluUnProject");
[a2b3d62]1616}
1617
[147847c]1618double GLACanvas::SurveyUnitsAcrossViewport() const
[087bc72]1619{
[8326157]1620    // Measure the current viewport in survey units, taking into account the
1621    // current display scale.
[087bc72]1622
[9eb58d0]1623    assert(m_Scale != 0.0);
[db59b02]1624    list_flags |= INVALIDATE_ON_SCALE;
[147847c]1625    double result = m_VolumeDiameter / m_Scale;
[ea35995]1626    if (y_size < x_size) {
1627        result = result * x_size / y_size;
1628    }
1629    return result;
[087bc72]1630}
[045e2af]1631
[d67450e]1632void GLACanvas::ToggleSmoothShading()
1633{
1634    m_SmoothShading = !m_SmoothShading;
1635}
1636
[a517825]1637void GLACanvas::ToggleTextured()
1638{
1639    m_Textured = !m_Textured;
1640    if (m_Textured && m_Texture == 0) {
1641        glGenTextures(1, &m_Texture);
1642        CHECK_GL_ERROR("ToggleTextured", "glGenTextures");
1643
1644        glBindTexture(GL_TEXTURE_2D, m_Texture);
1645        CHECK_GL_ERROR("ToggleTextured", "glBindTexture");
1646
1647        ::wxInitAllImageHandlers();
[5627cbb]1648
[a517825]1649        wxImage img;
[8a05a7a]1650        wxString texture(wmsg_cfgpth());
[5627cbb]1651        texture += wxCONFIG_PATH_SEPARATOR;
[09dfd18]1652        texture += wxT("images");
[5627cbb]1653        texture += wxCONFIG_PATH_SEPARATOR;
1654        texture += wxT("texture.png");
1655        if (!img.LoadFile(texture, wxBITMAP_TYPE_PNG)) {
[a517825]1656            // FIXME
1657            fprintf(stderr, "Couldn't load image.\n");
1658            exit(1);
1659        }
[5627cbb]1660
[ecbdd96]1661        // Generate mipmaps.
[7c18431]1662        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, // was GL_LUMINANCE
[ecbdd96]1663                          img.GetWidth(), img.GetHeight(),
1664                          GL_RGB, GL_UNSIGNED_BYTE, img.GetData());
1665        CHECK_GL_ERROR("ToggleTextured", "gluBuild2DMipmaps");
[a517825]1666
1667        glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1668        CHECK_GL_ERROR("ToggleTextured", "glTexEnvi");
1669    }
1670}
1671
[1ada489]1672bool GLACanvas::SaveScreenshot(const wxString & fnm, wxBitmapType type) const
[045e2af]1673{
[6cf4daa]1674    const int width = x_size;
1675    const int height = y_size;
[1bd4841]1676    unsigned char *pixels = (unsigned char *)malloc(3 * width * (height + 1));
[045e2af]1677    if (!pixels) return false;
1678    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
[a106530]1679    CHECK_GL_ERROR("SaveScreenshot", "glReadPixels");
[1bd4841]1680    unsigned char * tmp_row = pixels + 3 * width * height;
1681    // We need to flip the image vertically - this approach should be more
1682    // efficient than using wxImage::Mirror(false) as that creates a new
1683    // wxImage object.
1684    for (int y = height / 2 - 1; y >= 0; --y) {
1685        unsigned char * upper = pixels + 3 * width * y;
1686        unsigned char * lower = pixels + 3 * width * (height - y - 1);
1687        memcpy(tmp_row, upper, 3 * width);
1688        memcpy(upper, lower, 3 * width);
1689        memcpy(lower, tmp_row, 3 * width);
1690    }
1691    // NB wxImage constructor calls free(pixels) for us.
[045e2af]1692    wxImage grab(width, height, pixels);
[1bd4841]1693    return grab.SaveFile(fnm, type);
[045e2af]1694}
[807f9dd]1695
1696bool GLACanvas::CheckVisualFidelity(const unsigned char * target) const
1697{
1698    unsigned char pixels[3 * 8 * 8];
[c8f449c3]1699    if (double_buffered) {
1700        glReadBuffer(GL_BACK);
1701        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1702    }
[edfaf35]1703    glReadPixels(x_size / 2 - 4, y_size / 2 - 5, 8, 8,
[6cf4daa]1704                 GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)pixels);
[a106530]1705    CHECK_GL_ERROR("CheckVisualFidelity", "glReadPixels");
[c8f449c3]1706    if (double_buffered) {
1707        glReadBuffer(GL_FRONT);
1708        CHECK_GL_ERROR("FirstShow", "glReadBuffer");
1709    }
[4f7f965]1710#if 0
1711    // Show what got drawn and what was expected for debugging.
1712    for (int y = 0; y < 8; ++y) {
1713        for (int x = 0; x < 8; ++x) {
1714            int o = (y * 8 + x) * 3;
1715            printf("%c", pixels[o] ? 'X' : '.');
1716        }
1717        printf(" ");
1718        for (int x = 0; x < 8; ++x) {
1719            int o = (y * 8 + x) * 3;
1720            printf("%c", target[o] ? 'X' : '.');
1721        }
1722        printf("\n");
1723    }
1724#endif
[807f9dd]1725    return (memcmp(pixels, target, sizeof(pixels)) == 0);
1726}
[aea4f8b]1727
1728void GLACanvas::ReadPixels(int width, int height, unsigned char * buf) const
1729{
[a106530]1730    CHECK_GL_ERROR("ReadPixels", "glReadPixels");
[aea4f8b]1731    glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *)buf);
1732}
[f9ca87c]1733
1734void GLACanvas::PolygonOffset(bool on) const
1735{
1736    if (on) {
1737        glPolygonOffset(1.0, 1.0);
1738        glEnable(GL_POLYGON_OFFSET_FILL);
1739    } else {
1740        glDisable(GL_POLYGON_OFFSET_FILL);
1741    }
1742}
Note: See TracBrowser for help on using the repository browser.