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

Last change on this file since feedee2 was 5f8464d, checked in by Olly Betts <olly@…>, 4 months ago

Clean up handling of DPI and size changes

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