source: git/src/gfxcore.cc @ 236a1b1

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

Add --stereo option

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

  • Property mode set to 100644
File size: 113.0 KB
Line 
1//
2//  gfxcore.cc
3//
4//  Core drawing code for Aven.
5//
6//  Copyright (C) 2000-2003,2005,2006 Mark R. Shinwell
7//  Copyright (C) 2001-2003,2004,2005,2006,2007,2010,2011,2012,2014,2015,2016,2017,2018 Olly Betts
8//  Copyright (C) 2005 Martin Green
9//
10//  This program is free software; you can redistribute it and/or modify
11//  it under the terms of the GNU General Public License as published by
12//  the Free Software Foundation; either version 2 of the License, or
13//  (at your option) any later version.
14//
15//  This program is distributed in the hope that it will be useful,
16//  but WITHOUT ANY WARRANTY; without even the implied warranty of
17//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18//  GNU General Public License for more details.
19//
20//  You should have received a copy of the GNU General Public License
21//  along with this program; if not, write to the Free Software
22//  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
23//
24
25#ifdef HAVE_CONFIG_H
26#include <config.h>
27#endif
28
29#include <assert.h>
30#include <float.h>
31
32#include "aven.h"
33#include "date.h"
34#include "filename.h"
35#include "gfxcore.h"
36#include "mainfrm.h"
37#include "message.h"
38#include "useful.h"
39#include "printing.h"
40#include "guicontrol.h"
41#include "moviemaker.h"
42
43#include <wx/confbase.h>
44#include <wx/wfstream.h>
45#include <wx/image.h>
46#include <wx/zipstrm.h>
47
48#include <proj_api.h>
49
50const unsigned long DEFAULT_HGT_DIM = 3601;
51const unsigned long DEFAULT_HGT_SIZE = sqrd(DEFAULT_HGT_DIM) * 2;
52
53// Values for m_SwitchingTo
54#define PLAN 1
55#define ELEVATION 2
56#define NORTH 3
57#define EAST 4
58#define SOUTH 5
59#define WEST 6
60
61// Any error value higher than this is clamped to this.
62#define MAX_ERROR 12.0
63
64// Any length greater than pow(10, LOG_LEN_MAX) will be clamped to this.
65const Double LOG_LEN_MAX = 1.5;
66
67// How many bins per letter height to use when working out non-overlapping
68// labels.
69const unsigned int QUANTISE_FACTOR = 2;
70
71#include "avenpal.h"
72
73static const int INDICATOR_BOX_SIZE = 60;
74static const int INDICATOR_GAP = 2;
75static const int INDICATOR_MARGIN = 5;
76static const int INDICATOR_OFFSET_X = 15;
77static const int INDICATOR_OFFSET_Y = 15;
78static const int INDICATOR_RADIUS = INDICATOR_BOX_SIZE / 2 - INDICATOR_MARGIN;
79static const int KEY_OFFSET_X = 10;
80static const int KEY_OFFSET_Y = 10;
81static const int KEY_EXTRA_LEFT_MARGIN = 2;
82static const int KEY_BLOCK_WIDTH = 20;
83static const int KEY_BLOCK_HEIGHT = 16;
84static const int TICK_LENGTH = 4;
85static const int SCALE_BAR_OFFSET_X = 15;
86static const int SCALE_BAR_OFFSET_Y = 12;
87static const int SCALE_BAR_HEIGHT = 12;
88
89static const gla_colour TEXT_COLOUR = col_GREEN;
90static const gla_colour HERE_COLOUR = col_WHITE;
91static const gla_colour NAME_COLOUR = col_GREEN;
92static const gla_colour SEL_COLOUR = col_WHITE;
93// Used with colour by date for legs without date information and with colour
94// by error for legs not in a loop.
95static const gla_colour NODATA_COLOUR = col_LIGHT_GREY_2;
96
97// Number of entries across and down the hit-test grid:
98#define HITTEST_SIZE 20
99
100// How close the pointer needs to be to a station to be considered:
101#define MEASURE_THRESHOLD 7
102
103// vector for lighting angle
104static const Vector3 light(.577, .577, .577);
105
106BEGIN_EVENT_TABLE(GfxCore, GLACanvas)
107    EVT_PAINT(GfxCore::OnPaint)
108    EVT_LEFT_DOWN(GfxCore::OnLButtonDown)
109    EVT_LEFT_UP(GfxCore::OnLButtonUp)
110    EVT_MIDDLE_DOWN(GfxCore::OnMButtonDown)
111    EVT_MIDDLE_UP(GfxCore::OnMButtonUp)
112    EVT_RIGHT_DOWN(GfxCore::OnRButtonDown)
113    EVT_RIGHT_UP(GfxCore::OnRButtonUp)
114    EVT_MOUSEWHEEL(GfxCore::OnMouseWheel)
115    EVT_MOTION(GfxCore::OnMouseMove)
116    EVT_LEAVE_WINDOW(GfxCore::OnLeaveWindow)
117    EVT_SIZE(GfxCore::OnSize)
118    EVT_IDLE(GfxCore::OnIdle)
119    EVT_CHAR(GfxCore::OnKeyPress)
120END_EVENT_TABLE()
121
122GfxCore::GfxCore(MainFrm* parent, wxWindow* parent_win, GUIControl* control) :
123    GLACanvas(parent_win, 100),
124    m_Scale(0.0),
125    initial_scale(1.0),
126    m_ScaleBarWidth(0),
127    m_Control(control),
128    m_LabelGrid(NULL),
129    m_Parent(parent),
130    m_DoneFirstShow(false),
131    m_TiltAngle(0.0),
132    m_PanAngle(0.0),
133    m_Rotating(false),
134    m_RotationStep(0.0),
135    m_SwitchingTo(0),
136    m_Crosses(false),
137    m_Legs(true),
138    m_Splays(SHOW_FADED),
139    m_Dupes(SHOW_DASHED),
140    m_Names(false),
141    m_Scalebar(true),
142    m_ColourKey(true),
143    m_OverlappingNames(false),
144    m_Compass(true),
145    m_Clino(true),
146    m_Tubes(false),
147    m_ColourBy(COLOUR_BY_DEPTH),
148    m_HaveData(false),
149    m_HaveTerrain(true),
150    m_MouseOutsideCompass(false),
151    m_MouseOutsideElev(false),
152    m_Surface(false),
153    m_Entrances(false),
154    m_FixedPts(false),
155    m_ExportedPts(false),
156    m_Grid(false),
157    m_BoundingBox(false),
158    m_Terrain(false),
159    m_Degrees(false),
160    m_Metric(false),
161    m_Percent(false),
162    m_HitTestDebug(false),
163    m_RenderStats(false),
164    m_PointGrid(NULL),
165    m_HitTestGridValid(false),
166    m_here(NULL),
167    m_there(NULL),
168    presentation_mode(0),
169    pres_reverse(false),
170    pres_speed(0.0),
171    movie(NULL),
172    current_cursor(GfxCore::CURSOR_DEFAULT),
173    sqrd_measure_threshold(sqrd(MEASURE_THRESHOLD)),
174    dem(NULL),
175    last_time(0),
176    n_tris(0)
177{
178    AddQuad = &GfxCore::AddQuadrilateralDepth;
179    AddPoly = &GfxCore::AddPolylineDepth;
180    wxConfigBase::Get()->Read(wxT("metric"), &m_Metric, true);
181    wxConfigBase::Get()->Read(wxT("degrees"), &m_Degrees, true);
182    wxConfigBase::Get()->Read(wxT("percent"), &m_Percent, false);
183
184    for (int pen = 0; pen < NUM_COLOUR_BANDS + 1; ++pen) {
185        m_Pens[pen].SetColour(REDS[pen] / 255.0,
186                              GREENS[pen] / 255.0,
187                              BLUES[pen] / 255.0);
188    }
189
190    if (stereo_mode == STEREO_ANAGLYPH) {
191        SetColourBy(COLOUR_BY_NONE);
192    }
193    timer.Start();
194}
195
196GfxCore::~GfxCore()
197{
198    TryToFreeArrays();
199
200    delete[] m_PointGrid;
201}
202
203void GfxCore::TryToFreeArrays()
204{
205    // Free up any memory allocated for arrays.
206    delete[] m_LabelGrid;
207    m_LabelGrid = NULL;
208}
209
210//
211//  Initialisation methods
212//
213
214void GfxCore::Initialise(bool same_file)
215{
216    // Initialise the view from the parent holding the survey data.
217
218    TryToFreeArrays();
219
220    m_DoneFirstShow = false;
221
222    m_HitTestGridValid = false;
223    m_here = NULL;
224    m_there = NULL;
225
226    m_MouseOutsideCompass = m_MouseOutsideElev = false;
227
228    if (!same_file) {
229        // Apply default parameters unless reloading the same file.
230        DefaultParameters();
231    }
232
233    m_HaveData = true;
234
235    // Clear any cached OpenGL lists which depend on the data.
236    InvalidateList(LIST_SCALE_BAR);
237    InvalidateList(LIST_DEPTH_KEY);
238    InvalidateList(LIST_DATE_KEY);
239    InvalidateList(LIST_ERROR_KEY);
240    InvalidateList(LIST_GRADIENT_KEY);
241    InvalidateList(LIST_LENGTH_KEY);
242    InvalidateList(LIST_UNDERGROUND_LEGS);
243    InvalidateList(LIST_TUBES);
244    InvalidateList(LIST_SURFACE_LEGS);
245    InvalidateList(LIST_BLOBS);
246    InvalidateList(LIST_CROSSES);
247    InvalidateList(LIST_GRID);
248    InvalidateList(LIST_SHADOW);
249    InvalidateList(LIST_TERRAIN);
250
251    // Set diameter of the viewing volume.
252    auto ext = m_Parent->GetExtent();
253    double cave_diameter = sqrt(sqrd(ext.GetX()) +
254                                sqrd(ext.GetY()) +
255                                sqrd(ext.GetZ()));
256
257    // Allow for terrain.
258    double diameter = max(1000.0 * 2, cave_diameter * 2);
259
260    if (!same_file) {
261        SetVolumeDiameter(diameter);
262
263        // Set initial scale based on the size of the cave.
264        initial_scale = diameter / cave_diameter;
265        SetScale(initial_scale);
266    } else {
267        // Adjust the position when restricting the view to a subsurvey (or
268        // expanding the view to show the whole survey).
269        AddTranslation(m_Parent->GetOffset() - offsets);
270
271        // Try to keep the same scale, allowing for the
272        // cave having grown (or shrunk).
273        double rescale = GetVolumeDiameter() / diameter;
274        SetVolumeDiameter(diameter);
275        SetScale(GetScale() / rescale); // ?
276        initial_scale = initial_scale * rescale;
277    }
278
279    offsets = m_Parent->GetOffset();
280
281    ForceRefresh();
282}
283
284void GfxCore::FirstShow()
285{
286    GLACanvas::FirstShow();
287
288    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
289    list<LabelInfo*>::iterator pos = m_Parent->GetLabelsNC();
290    while (pos != m_Parent->GetLabelsNCEnd()) {
291        LabelInfo* label = *pos++;
292        // Calculate and set the label width for use when plotting
293        // none-overlapping labels.
294        int ext_x;
295        GLACanvas::GetTextExtent(label->GetText(), &ext_x, NULL);
296        label->set_width(unsigned(ext_x) / quantise + 1);
297    }
298
299    m_DoneFirstShow = true;
300}
301
302//
303//  Recalculating methods
304//
305
306void GfxCore::SetScale(Double scale)
307{
308    if (scale < 0.05) {
309        scale = 0.05;
310    } else if (scale > GetVolumeDiameter()) {
311        scale = GetVolumeDiameter();
312    }
313
314    m_Scale = scale;
315    m_HitTestGridValid = false;
316    if (m_here && m_here == &temp_here) SetHere();
317
318    GLACanvas::SetScale(scale);
319}
320
321bool GfxCore::HasUndergroundLegs() const
322{
323    return m_Parent->HasUndergroundLegs();
324}
325
326bool GfxCore::HasSplays() const
327{
328    return m_Parent->HasSplays();
329}
330
331bool GfxCore::HasDupes() const
332{
333    return m_Parent->HasDupes();
334}
335
336bool GfxCore::HasSurfaceLegs() const
337{
338    return m_Parent->HasSurfaceLegs();
339}
340
341bool GfxCore::HasTubes() const
342{
343    return m_Parent->HasTubes();
344}
345
346void GfxCore::UpdateBlobs()
347{
348    InvalidateList(LIST_BLOBS);
349}
350
351//
352//  Event handlers
353//
354
355void GfxCore::OnLeaveWindow(wxMouseEvent&) {
356    SetHere();
357    ClearCoords();
358}
359
360void GfxCore::OnIdle(wxIdleEvent& event)
361{
362    // Handle an idle event.
363    if (Animating()) {
364        Animate();
365        // If still animating, we want more idle events.
366        if (Animating())
367            event.RequestMore();
368    } else {
369        // If we're idle, don't show a bogus FPS next time we render.
370        last_time = 0;
371    }
372}
373
374void GfxCore::OnPaint(wxPaintEvent&)
375{
376    // Redraw the window.
377
378    // Get a graphics context.
379    wxPaintDC dc(this);
380
381    if (!m_HaveData) {
382        dc.SetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
383        dc.Clear();
384        return;
385    }
386
387    // Make sure we're initialised.
388    bool first_time = !m_DoneFirstShow;
389    if (first_time) {
390        FirstShow();
391    }
392
393    int n_Eyes = (stereo_mode ? 2 : 1);
394    // 0 for left eye, 1 for right.
395    for (m_Eye = 0; m_Eye < n_Eyes; m_Eye++) {
396        if (m_Eye == 0 || stereo_mode != STEREO_ANAGLYPH) {
397            StartDrawing();
398
399            if (m_Eye == 0 || stereo_mode != STEREO_2UP) {
400                // Clear the background.
401                Clear();
402            }
403        }
404
405        if (stereo_mode == STEREO_ANAGLYPH) {
406            if (m_Eye) {
407                // Clear alpha and the depth buffer.
408                glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE);
409                Clear();
410
411                // Right is green and blue.
412                glColorMask(GL_FALSE, GL_TRUE, GL_TRUE, GL_TRUE);
413            } else {
414                // Left is red.
415                glColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_TRUE);
416            }
417        }
418
419        // Set up model transformation matrix.
420        SetDataTransform();
421
422        if (m_Legs || m_Tubes) {
423            if (m_Tubes) {
424                EnableSmoothPolygons(true); // FIXME: allow false for wireframe view
425                DrawList(LIST_TUBES);
426                DisableSmoothPolygons();
427            }
428
429            // Draw the underground legs.  Do this last so that anti-aliasing
430            // works over polygons.
431            SetColour(col_GREEN);
432            DrawList(LIST_UNDERGROUND_LEGS);
433        }
434
435        if (m_Surface) {
436            // Draw the surface legs.
437            DrawList(LIST_SURFACE_LEGS);
438        }
439
440        if (m_BoundingBox) {
441            DrawShadowedBoundingBox();
442        }
443        if (m_Grid) {
444            // Draw the grid.
445            DrawList(LIST_GRID);
446        }
447
448        DrawList(LIST_BLOBS);
449
450        if (m_Crosses) {
451            DrawList(LIST_CROSSES);
452        }
453
454        if (m_Terrain) {
455            // Disable texturing while drawing terrain.
456            bool texturing = GetTextured();
457            if (texturing) GLACanvas::ToggleTextured();
458
459            // This is needed if blobs and/or crosses are drawn using lines -
460            // otherwise the terrain doesn't appear when they are enabled.
461            SetDataTransform();
462
463            // We don't want to be able to see the terrain through itself, so
464            // do a "Z-prepass" - plot the terrain once only updating the
465            // Z-buffer, then again with Z-clipping only plotting where the
466            // depth matches the value in the Z-buffer.
467            DrawListZPrepass(LIST_TERRAIN);
468
469            if (texturing) GLACanvas::ToggleTextured();
470        }
471
472        SetIndicatorTransform();
473
474        // Draw station names.
475        if (m_Names /*&& !m_Control->MouseDown() && !Animating()*/) {
476            SetColour(NAME_COLOUR);
477
478            if (m_OverlappingNames) {
479                SimpleDrawNames();
480            } else {
481                NattyDrawNames();
482            }
483        }
484
485        if (m_HitTestDebug) {
486            // Show the hit test grid bucket sizes...
487            SetColour(m_HitTestGridValid ? col_LIGHT_GREY : col_DARK_GREY);
488            if (m_PointGrid) {
489                for (int i = 0; i != HITTEST_SIZE; ++i) {
490                    int x = (GetXSize() + 1) * i / HITTEST_SIZE + 2;
491                    for (int j = 0; j != HITTEST_SIZE; ++j) {
492                        int square = i + j * HITTEST_SIZE;
493                        unsigned long bucket_size = m_PointGrid[square].size();
494                        if (bucket_size) {
495                            int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
496                            DrawIndicatorText(x, y, wxString::Format(wxT("%lu"), bucket_size));
497                        }
498                    }
499                }
500            }
501
502            EnableDashedLines();
503            BeginLines();
504            for (int i = 0; i != HITTEST_SIZE; ++i) {
505                int x = (GetXSize() + 1) * i / HITTEST_SIZE;
506                PlaceIndicatorVertex(x, 0);
507                PlaceIndicatorVertex(x, GetYSize());
508            }
509            for (int j = 0; j != HITTEST_SIZE; ++j) {
510                int y = (GetYSize() + 1) * (HITTEST_SIZE - 1 - j) / HITTEST_SIZE;
511                PlaceIndicatorVertex(0, y);
512                PlaceIndicatorVertex(GetXSize(), y);
513            }
514            EndLines();
515            DisableDashedLines();
516        }
517
518        long now = timer.Time();
519        if (m_RenderStats) {
520            // Show stats about rendering.
521            SetColour(col_TURQUOISE);
522            int y = GetYSize() - GetFontSize();
523            if (last_time != 0.0) {
524                // timer.Time() measure in milliseconds.
525                double fps = 1000.0 / (now - last_time);
526                DrawIndicatorText(1, y, wxString::Format(wxT("FPS:% 5.1f"), fps));
527            }
528            y -= GetFontSize();
529            DrawIndicatorText(1, y, wxString::Format(wxT("▲:%lu"), (unsigned long)n_tris));
530        }
531        last_time = now;
532
533        // Draw indicators.
534        //
535        // There's no advantage in generating an OpenGL list for the
536        // indicators since they change with almost every redraw (and
537        // sometimes several times between redraws).  This way we avoid
538        // the need to track when to update the indicator OpenGL list,
539        // and also avoid indicator update bugs when we don't quite get this
540        // right...
541        DrawIndicators();
542
543        if (zoombox.active()) {
544            SetColour(SEL_COLOUR);
545            EnableDashedLines();
546            BeginPolyline();
547            glaCoord Y = GetYSize();
548            PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
549            PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y2);
550            PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y2);
551            PlaceIndicatorVertex(zoombox.x2, Y - zoombox.y1);
552            PlaceIndicatorVertex(zoombox.x1, Y - zoombox.y1);
553            EndPolyline();
554            DisableDashedLines();
555        } else if (MeasuringLineActive()) {
556            // Draw "here" and "there".
557            double hx, hy;
558            SetColour(HERE_COLOUR);
559            if (m_here) {
560                double dummy;
561                Transform(*m_here, &hx, &hy, &dummy);
562                if (m_here != &temp_here) DrawRing(hx, hy);
563            }
564            if (m_there) {
565                double tx, ty;
566                double dummy;
567                Transform(*m_there, &tx, &ty, &dummy);
568                if (m_here) {
569                    BeginLines();
570                    PlaceIndicatorVertex(hx, hy);
571                    PlaceIndicatorVertex(tx, ty);
572                    EndLines();
573                }
574                BeginBlobs();
575                DrawBlob(tx, ty);
576                EndBlobs();
577            }
578        }
579    }
580
581    if (stereo_mode == STEREO_ANAGLYPH) {
582        // Reset colour mask.
583        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
584    }
585    FinishDrawing();
586}
587
588void GfxCore::DrawBoundingBox()
589{
590    const Vector3 v = 0.5 * m_Parent->GetExtent();
591
592    SetColour(col_BLUE);
593    EnableDashedLines();
594    BeginPolyline();
595    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
596    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
597    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
598    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
599    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
600    EndPolyline();
601    BeginPolyline();
602    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
603    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
604    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
605    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
606    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
607    EndPolyline();
608    BeginLines();
609    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
610    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
611    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
612    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
613    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
614    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
615    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
616    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
617    EndLines();
618    DisableDashedLines();
619}
620
621void GfxCore::DrawShadowedBoundingBox()
622{
623    const Vector3 v = 0.5 * m_Parent->GetExtent();
624
625    DrawBoundingBox();
626
627    PolygonOffset(true);
628    SetColour(col_DARK_GREY);
629    BeginQuadrilaterals();
630    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
631    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
632    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
633    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
634    EndQuadrilaterals();
635    PolygonOffset(false);
636
637    DrawList(LIST_SHADOW);
638}
639
640void GfxCore::DrawGrid()
641{
642    // Draw the grid.
643    SetColour(col_RED);
644
645    // Calculate the extent of the survey, in metres across the screen plane.
646    Double m_across_screen = SurveyUnitsAcrossViewport();
647    // Calculate the length of the scale bar in metres.
648    //--move this elsewhere
649    Double size_snap = pow(10.0, floor(log10(0.75 * m_across_screen)));
650    Double t = m_across_screen * 0.75 / size_snap;
651    if (t >= 5.0) {
652        size_snap *= 5.0;
653    }
654    else if (t >= 2.0) {
655        size_snap *= 2.0;
656    }
657
658    Double grid_size = size_snap * 0.1;
659    Double edge = grid_size * 2.0;
660    auto ext = m_Parent->GetExtent();
661    Double grid_z = -ext.GetZ() * 0.5 - grid_size;
662    Double left = -ext.GetX() * 0.5 - edge;
663    Double right = ext.GetX() * 0.5 + edge;
664    Double bottom = -ext.GetY() * 0.5 - edge;
665    Double top = ext.GetY() * 0.5 + edge;
666    int count_x = (int) ceil((right - left) / grid_size);
667    int count_y = (int) ceil((top - bottom) / grid_size);
668    Double actual_right = left + count_x*grid_size;
669    Double actual_top = bottom + count_y*grid_size;
670
671    BeginLines();
672
673    for (int xc = 0; xc <= count_x; xc++) {
674        Double x = left + xc*grid_size;
675
676        PlaceVertex(x, bottom, grid_z);
677        PlaceVertex(x, actual_top, grid_z);
678    }
679
680    for (int yc = 0; yc <= count_y; yc++) {
681        Double y = bottom + yc*grid_size;
682        PlaceVertex(left, y, grid_z);
683        PlaceVertex(actual_right, y, grid_z);
684    }
685
686    EndLines();
687}
688
689int GfxCore::GetClinoOffset() const
690{
691    int result = INDICATOR_OFFSET_X;
692    if (m_Compass) {
693        result += 6 + GetCompassWidth() + INDICATOR_GAP;
694    }
695    return result;
696}
697
698void GfxCore::DrawTick(int angle_cw)
699{
700    const Double theta = rad(angle_cw);
701    const wxCoord length1 = INDICATOR_RADIUS;
702    const wxCoord length0 = length1 + TICK_LENGTH;
703    wxCoord x0 = wxCoord(length0 * sin(theta));
704    wxCoord y0 = wxCoord(length0 * cos(theta));
705    wxCoord x1 = wxCoord(length1 * sin(theta));
706    wxCoord y1 = wxCoord(length1 * cos(theta));
707
708    PlaceIndicatorVertex(x0, y0);
709    PlaceIndicatorVertex(x1, y1);
710}
711
712void GfxCore::DrawArrow(gla_colour col1, gla_colour col2) {
713    Vector3 p1(0, INDICATOR_RADIUS, 0);
714    Vector3 p2(INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 150deg
715    Vector3 p3(-INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 210deg
716    Vector3 pc(0, 0, 0);
717
718    DrawTriangle(col_LIGHT_GREY, col1, p2, p1, pc);
719    DrawTriangle(col_LIGHT_GREY, col2, p3, p1, pc);
720}
721
722void GfxCore::DrawCompass() {
723    // Ticks.
724    BeginLines();
725    for (int angle = 315; angle > 0; angle -= 45) {
726        DrawTick(angle);
727    }
728    SetColour(col_GREEN);
729    DrawTick(0);
730    EndLines();
731
732    // Compass background.
733    DrawCircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS);
734
735    // Compass arrow.
736    DrawArrow(col_INDICATOR_1, col_INDICATOR_2);
737}
738
739// Draw the non-rotating background to the clino.
740void GfxCore::DrawClinoBack() {
741    BeginLines();
742    for (int angle = 0; angle <= 180; angle += 90) {
743        DrawTick(angle);
744    }
745
746    SetColour(col_GREY);
747    PlaceIndicatorVertex(0, INDICATOR_RADIUS);
748    PlaceIndicatorVertex(0, -INDICATOR_RADIUS);
749    PlaceIndicatorVertex(0, 0);
750    PlaceIndicatorVertex(INDICATOR_RADIUS, 0);
751
752    EndLines();
753}
754
755void GfxCore::DrawClino() {
756    // Ticks.
757    SetColour(col_GREEN);
758    BeginLines();
759    DrawTick(0);
760    EndLines();
761
762    // Clino background.
763    DrawSemicircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS, 0);
764
765    // Elevation arrow.
766    DrawArrow(col_INDICATOR_2, col_INDICATOR_1);
767}
768
769void GfxCore::Draw2dIndicators()
770{
771    // Draw the compass and elevation indicators.
772
773    const int centre_y = INDICATOR_BOX_SIZE / 2 + INDICATOR_OFFSET_Y;
774
775    const int comp_centre_x = GetCompassXPosition();
776
777    if (m_Compass && !m_Parent->IsExtendedElevation()) {
778        // If the user is dragging the compass with the pointer outside the
779        // compass, we snap to 45 degree multiples, and the ticks go white.
780        SetColour(m_MouseOutsideCompass ? col_WHITE : col_LIGHT_GREY_2);
781        DrawList2D(LIST_COMPASS, comp_centre_x, centre_y, -m_PanAngle);
782    }
783
784    const int elev_centre_x = GetClinoXPosition();
785
786    if (m_Clino) {
787        // If the user is dragging the clino with the pointer outside the
788        // clino, we snap to 90 degree multiples, and the ticks go white.
789        SetColour(m_MouseOutsideElev ? col_WHITE : col_LIGHT_GREY_2);
790        DrawList2D(LIST_CLINO_BACK, elev_centre_x, centre_y, 0);
791        DrawList2D(LIST_CLINO, elev_centre_x, centre_y, 90 - m_TiltAngle);
792    }
793
794    SetColour(TEXT_COLOUR);
795
796    static int triple_zero_width = 0;
797    static int height = 0;
798    if (!triple_zero_width) {
799        GetTextExtent(wxT("000"), &triple_zero_width, &height);
800    }
801    const int y_off = INDICATOR_OFFSET_Y + INDICATOR_BOX_SIZE + height / 2;
802
803    if (m_Compass && !m_Parent->IsExtendedElevation()) {
804        wxString str;
805        int value;
806        int brg_unit;
807        if (m_Degrees) {
808            value = int(m_PanAngle);
809            /* TRANSLATORS: degree symbol - probably should be translated to
810             * itself. */
811            brg_unit = /*°*/344;
812        } else {
813            value = int(m_PanAngle * 200.0 / 180.0);
814            /* TRANSLATORS: symbol for grad (400 grad = 360 degrees = full
815             * circle). */
816            brg_unit = /*ᵍ*/345;
817        }
818        str.Printf(wxT("%03d"), value);
819        str += wmsg(brg_unit);
820        DrawIndicatorText(comp_centre_x - triple_zero_width / 2, y_off, str);
821
822        // TRANSLATORS: Used in aven above the compass indicator at the lower
823        // right of the display, with a bearing below "Facing".  This indicates the
824        // direction the viewer is "facing" in.
825        //
826        // Try to keep this translation short - ideally at most 10 characters -
827        // as otherwise the compass and clino will be moved further apart to
828        // make room. */
829        str = wmsg(/*Facing*/203);
830        int w;
831        GetTextExtent(str, &w, NULL);
832        DrawIndicatorText(comp_centre_x - w / 2, y_off + height, str);
833    }
834
835    if (m_Clino) {
836        if (m_TiltAngle == -90.0) {
837            // TRANSLATORS: Label used for "clino" in Aven when the view is
838            // from directly above.
839            //
840            // Try to keep this translation short - ideally at most 10
841            // characters - as otherwise the compass and clino will be moved
842            // further apart to make room. */
843            wxString str = wmsg(/*Plan*/432);
844            static int width = 0;
845            if (!width) {
846                GetTextExtent(str, &width, NULL);
847            }
848            int x = elev_centre_x - width / 2;
849            DrawIndicatorText(x, y_off + height / 2, str);
850        } else if (m_TiltAngle == 90.0) {
851            // TRANSLATORS: Label used for "clino" in Aven when the view is
852            // from directly below.
853            //
854            // Try to keep this translation short - ideally at most 10
855            // characters - as otherwise the compass and clino will be moved
856            // further apart to make room. */
857            wxString str = wmsg(/*Kiwi Plan*/433);
858            static int width = 0;
859            if (!width) {
860                GetTextExtent(str, &width, NULL);
861            }
862            int x = elev_centre_x - width / 2;
863            DrawIndicatorText(x, y_off + height / 2, str);
864        } else {
865            int angle;
866            wxString str;
867            int width;
868            int unit;
869            if (m_Percent) {
870                static int zero_width = 0;
871                if (!zero_width) {
872                    GetTextExtent(wxT("0"), &zero_width, NULL);
873                }
874                width = zero_width;
875                if (m_TiltAngle > 89.99) {
876                    angle = 1000000;
877                } else if (m_TiltAngle < -89.99) {
878                    angle = -1000000;
879                } else {
880                    angle = int(100 * tan(rad(m_TiltAngle)));
881                }
882                if (angle > 99999 || angle < -99999) {
883                    str = angle > 0 ? wxT("+") : wxT("-");
884                    /* TRANSLATORS: infinity symbol - used for the percentage gradient on
885                     * vertical angles. */
886                    str += wmsg(/*∞*/431);
887                } else {
888                    str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("0");
889                }
890                /* TRANSLATORS: symbol for percentage gradient (100% = 45
891                 * degrees = 50 grad). */
892                unit = /*%*/96;
893            } else if (m_Degrees) {
894                static int zero_zero_width = 0;
895                if (!zero_zero_width) {
896                    GetTextExtent(wxT("00"), &zero_zero_width, NULL);
897                }
898                width = zero_zero_width;
899                angle = int(m_TiltAngle);
900                str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("00");
901                unit = /*°*/344;
902            } else {
903                width = triple_zero_width;
904                angle = int(m_TiltAngle * 200.0 / 180.0);
905                str = angle ? wxString::Format(wxT("%+04d"), angle) : wxT("000");
906                unit = /*ᵍ*/345;
907            }
908
909            int sign_offset = 0;
910            if (unit == /*%*/96) {
911                // Right align % since the width changes so much.
912                GetTextExtent(str, &sign_offset, NULL);
913                sign_offset -= width;
914            } else if (angle < 0) {
915                // Adjust horizontal position so the left of the first digit is
916                // always in the same place.
917                static int minus_width = 0;
918                if (!minus_width) {
919                    GetTextExtent(wxT("-"), &minus_width, NULL);
920                }
921                sign_offset = minus_width;
922            } else if (angle > 0) {
923                // Adjust horizontal position so the left of the first digit is
924                // always in the same place.
925                static int plus_width = 0;
926                if (!plus_width) {
927                    GetTextExtent(wxT("+"), &plus_width, NULL);
928                }
929                sign_offset = plus_width;
930            }
931
932            str += wmsg(unit);
933            DrawIndicatorText(elev_centre_x - sign_offset - width / 2, y_off, str);
934
935            // TRANSLATORS: Label used for "clino" in Aven when the view is
936            // neither from directly above nor from directly below.  It is
937            // also used in the dialog for editing a marked position in a
938            // presentation.
939            //
940            // Try to keep this translation short - ideally at most 10
941            // characters - as otherwise the compass and clino will be moved
942            // further apart to make room. */
943            str = wmsg(/*Elevation*/118);
944            static int elevation_width = 0;
945            if (!elevation_width) {
946                GetTextExtent(str, &elevation_width, NULL);
947            }
948            int x = elev_centre_x - elevation_width / 2;
949            DrawIndicatorText(x, y_off + height, str);
950        }
951    }
952}
953
954void GfxCore::NattyDrawNames()
955{
956    // Draw station names, without overlapping.
957
958    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
959    const unsigned int quantised_x = GetXSize() / quantise;
960    const unsigned int quantised_y = GetYSize() / quantise;
961    const size_t buffer_size = quantised_x * quantised_y;
962
963    if (!m_LabelGrid) m_LabelGrid = new char[buffer_size];
964
965    memset((void*) m_LabelGrid, 0, buffer_size);
966
967    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
968    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
969        if (!((m_Surface && (*label)->IsSurface()) ||
970              (m_Legs && (*label)->IsUnderground()) ||
971              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
972            // if this station isn't to be displayed, skip to the next
973            // (last case is for stns with no legs attached)
974            continue;
975        }
976
977        double x, y, z;
978
979        Transform(**label, &x, &y, &z);
980        // Check if the label is behind us (in perspective view).
981        if (z <= 0.0 || z >= 1.0) continue;
982
983        // Apply a small shift so that translating the view doesn't make which
984        // labels are displayed change as the resulting twinkling effect is
985        // distracting.
986        double tx, ty, tz;
987        Transform(Vector3(), &tx, &ty, &tz);
988        tx -= floor(tx / quantise) * quantise;
989        ty -= floor(ty / quantise) * quantise;
990
991        tx = x - tx;
992        if (tx < 0) continue;
993
994        ty = y - ty;
995        if (ty < 0) continue;
996
997        unsigned int iy = unsigned(ty) / quantise;
998        if (iy >= quantised_y) continue;
999        unsigned int width = (*label)->get_width();
1000        unsigned int ix = unsigned(tx) / quantise;
1001        if (ix + width >= quantised_x) continue;
1002
1003        char * test = m_LabelGrid + ix + iy * quantised_x;
1004        if (memchr(test, 1, width)) continue;
1005
1006        x += 3;
1007        y -= GetFontSize() / 2;
1008        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
1009
1010        if (iy > QUANTISE_FACTOR) iy = QUANTISE_FACTOR;
1011        test -= quantised_x * iy;
1012        iy += 4;
1013        while (--iy && test < m_LabelGrid + buffer_size) {
1014            memset(test, 1, width);
1015            test += quantised_x;
1016        }
1017    }
1018}
1019
1020void GfxCore::SimpleDrawNames()
1021{
1022    // Draw all station names, without worrying about overlaps
1023    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
1024    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
1025        if (!((m_Surface && (*label)->IsSurface()) ||
1026              (m_Legs && (*label)->IsUnderground()) ||
1027              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
1028            // if this station isn't to be displayed, skip to the next
1029            // (last case is for stns with no legs attached)
1030            continue;
1031        }
1032
1033        double x, y, z;
1034        Transform(**label, &x, &y, &z);
1035
1036        // Check if the label is behind us (in perspective view).
1037        if (z <= 0) continue;
1038
1039        x += 3;
1040        y -= GetFontSize() / 2;
1041        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
1042    }
1043}
1044
1045void GfxCore::DrawColourKey(int num_bands, const wxString & other, const wxString & units)
1046{
1047    int total_block_height =
1048        KEY_BLOCK_HEIGHT * (num_bands == 1 ? num_bands : num_bands - 1);
1049    if (!other.empty()) total_block_height += KEY_BLOCK_HEIGHT * 2;
1050    if (!units.empty()) total_block_height += KEY_BLOCK_HEIGHT;
1051
1052    const int bottom = -total_block_height;
1053
1054    int size = 0;
1055    if (!other.empty()) GetTextExtent(other, &size, NULL);
1056    int band;
1057    for (band = 0; band < num_bands; ++band) {
1058        int x;
1059        GetTextExtent(key_legends[band], &x, NULL);
1060        if (x > size) size = x;
1061    }
1062
1063    int left = -KEY_BLOCK_WIDTH - size;
1064
1065    key_lowerleft[m_ColourBy].x = left - KEY_EXTRA_LEFT_MARGIN;
1066    key_lowerleft[m_ColourBy].y = bottom;
1067
1068    int y = bottom;
1069    if (!units.empty()) y += KEY_BLOCK_HEIGHT;
1070
1071    if (!other.empty()) {
1072        DrawRectangle(NODATA_COLOUR, col_BLACK,
1073                      left, y,
1074                      KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1075        y += KEY_BLOCK_HEIGHT * 2;
1076    }
1077
1078    int start = y;
1079    if (num_bands == 1) {
1080        DrawShadedRectangle(GetPen(0), GetPen(0), left, y,
1081                            KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1082        y += KEY_BLOCK_HEIGHT;
1083    } else {
1084        for (band = 0; band < num_bands - 1; ++band) {
1085            DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
1086                                KEY_BLOCK_WIDTH, KEY_BLOCK_HEIGHT);
1087            y += KEY_BLOCK_HEIGHT;
1088        }
1089    }
1090
1091    SetColour(col_BLACK);
1092    BeginPolyline();
1093    PlaceIndicatorVertex(left, y);
1094    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, y);
1095    PlaceIndicatorVertex(left + KEY_BLOCK_WIDTH, start);
1096    PlaceIndicatorVertex(left, start);
1097    PlaceIndicatorVertex(left, y);
1098    EndPolyline();
1099
1100    SetColour(TEXT_COLOUR);
1101
1102    y = bottom;
1103    if (!units.empty()) {
1104        GetTextExtent(units, &size, NULL);
1105        DrawIndicatorText(left + (KEY_BLOCK_WIDTH - size) / 2, y, units);
1106        y += KEY_BLOCK_HEIGHT;
1107    }
1108    y -= GetFontSize() / 2;
1109    left += KEY_BLOCK_WIDTH + 5;
1110
1111    if (!other.empty()) {
1112        y += KEY_BLOCK_HEIGHT / 2;
1113        DrawIndicatorText(left, y, other);
1114        y += KEY_BLOCK_HEIGHT * 2 - KEY_BLOCK_HEIGHT / 2;
1115    }
1116
1117    if (num_bands == 1) {
1118        y += KEY_BLOCK_HEIGHT / 2;
1119        DrawIndicatorText(left, y, key_legends[0]);
1120    } else {
1121        for (band = 0; band < num_bands; ++band) {
1122            DrawIndicatorText(left, y, key_legends[band]);
1123            y += KEY_BLOCK_HEIGHT;
1124        }
1125    }
1126}
1127
1128void GfxCore::DrawDepthKey()
1129{
1130    Double z_ext = m_Parent->GetDepthExtent();
1131    int num_bands = 1;
1132    int sf = 0;
1133    if (z_ext > 0.0) {
1134        num_bands = GetNumColourBands();
1135        Double z_range = z_ext;
1136        if (!m_Metric) z_range /= METRES_PER_FOOT;
1137        sf = max(0, 1 - (int)floor(log10(z_range)));
1138    }
1139
1140    Double z_min = m_Parent->GetDepthMin() + m_Parent->GetOffset().GetZ();
1141    for (int band = 0; band < num_bands; ++band) {
1142        Double z = z_min;
1143        if (band)
1144            z += z_ext * band / (num_bands - 1);
1145
1146        if (!m_Metric)
1147            z /= METRES_PER_FOOT;
1148
1149        key_legends[band].Printf(wxT("%.*f"), sf, z);
1150    }
1151
1152    DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1153}
1154
1155void GfxCore::DrawDateKey()
1156{
1157    int num_bands;
1158    if (!HasDateInformation()) {
1159        num_bands = 0;
1160    } else {
1161        int date_ext = m_Parent->GetDateExtent();
1162        if (date_ext == 0) {
1163            num_bands = 1;
1164        } else {
1165            num_bands = GetNumColourBands();
1166        }
1167        for (int band = 0; band < num_bands; ++band) {
1168            int y, m, d;
1169            int days = m_Parent->GetDateMin();
1170            if (band)
1171                days += date_ext * band / (num_bands - 1);
1172            ymd_from_days_since_1900(days, &y, &m, &d);
1173            key_legends[band].Printf(wxT("%04d-%02d-%02d"), y, m, d);
1174        }
1175    }
1176
1177    wxString other;
1178    if (!m_Parent->HasCompleteDateInfo()) {
1179        /* TRANSLATORS: Used in the "colour key" for "colour by date" if there
1180         * are surveys without date information.  Try to keep this fairly short.
1181         */
1182        other = wmsg(/*Undated*/221);
1183    }
1184
1185    DrawColourKey(num_bands, other, wxString());
1186}
1187
1188void GfxCore::DrawErrorKey()
1189{
1190    int num_bands;
1191    if (HasErrorInformation()) {
1192        // Use fixed colours for each error factor so it's directly visually
1193        // comparable between surveys.
1194        num_bands = GetNumColourBands();
1195        for (int band = 0; band < num_bands; ++band) {
1196            double E = MAX_ERROR * band / (num_bands - 1);
1197            key_legends[band].Printf(wxT("%.2f"), E);
1198        }
1199    } else {
1200        num_bands = 0;
1201    }
1202
1203    // Always show the "Not in loop" legend for now (FIXME).
1204    /* TRANSLATORS: Used in the "colour key" for "colour by error" for surveys
1205     * which aren’t part of a loop and so have no error information. Try to keep
1206     * this fairly short. */
1207    DrawColourKey(num_bands, wmsg(/*Not in loop*/290), wxString());
1208}
1209
1210void GfxCore::DrawGradientKey()
1211{
1212    int num_bands;
1213    // Use fixed colours for each gradient so it's directly visually comparable
1214    // between surveys.
1215    num_bands = GetNumColourBands();
1216    wxString units = wmsg(m_Degrees ? /*°*/344 : /*ᵍ*/345);
1217    for (int band = 0; band < num_bands; ++band) {
1218        double gradient = double(band) / (num_bands - 1);
1219        if (m_Degrees) {
1220            gradient *= 90.0;
1221        } else {
1222            gradient *= 100.0;
1223        }
1224        key_legends[band].Printf(wxT("%.f%s"), gradient, units);
1225    }
1226
1227    DrawColourKey(num_bands, wxString(), wxString());
1228}
1229
1230void GfxCore::DrawLengthKey()
1231{
1232    int num_bands;
1233    // Use fixed colours for each length so it's directly visually comparable
1234    // between surveys.
1235    num_bands = GetNumColourBands();
1236    for (int band = 0; band < num_bands; ++band) {
1237        double len = pow(10, LOG_LEN_MAX * band / (num_bands - 1));
1238        if (!m_Metric) {
1239            len /= METRES_PER_FOOT;
1240        }
1241        key_legends[band].Printf(wxT("%.1f"), len);
1242    }
1243
1244    DrawColourKey(num_bands, wxString(), wmsg(m_Metric ? /*m*/424: /*ft*/428));
1245}
1246
1247void GfxCore::DrawScaleBar()
1248{
1249    // Calculate how many metres of survey are currently displayed across the
1250    // screen.
1251    Double across_screen = SurveyUnitsAcrossViewport();
1252
1253    double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / GetXSize();
1254    if (f > 0.75) {
1255        f = 0.75;
1256    } else if (f < 0.5) {
1257        // Stop it getting squeezed to nothing.
1258        // FIXME: In this case we should probably move the compass and clino up
1259        // to make room rather than letting stuff overlap.
1260        f = 0.5;
1261    }
1262
1263    // Convert to imperial measurements if required.
1264    Double multiplier = 1.0;
1265    if (!m_Metric) {
1266        across_screen /= METRES_PER_FOOT;
1267        multiplier = METRES_PER_FOOT;
1268        if (across_screen >= 5280.0 / f) {
1269            across_screen /= 5280.0;
1270            multiplier *= 5280.0;
1271        }
1272    }
1273
1274    // Calculate the length of the scale bar.
1275    Double size_snap = pow(10.0, floor(log10(f * across_screen)));
1276    Double t = across_screen * f / size_snap;
1277    if (t >= 5.0) {
1278        size_snap *= 5.0;
1279    } else if (t >= 2.0) {
1280        size_snap *= 2.0;
1281    }
1282
1283    if (!m_Metric) size_snap *= multiplier;
1284
1285    // Actual size of the thing in pixels:
1286    int size = int((size_snap / SurveyUnitsAcrossViewport()) * GetXSize());
1287    m_ScaleBarWidth = size;
1288
1289    // Draw it...
1290    const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
1291    int interval = size / 10;
1292
1293    gla_colour col = col_WHITE;
1294    for (int ix = 0; ix < 10; ix++) {
1295        int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
1296
1297        DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
1298
1299        col = (col == col_WHITE) ? col_GREY : col_WHITE;
1300    }
1301
1302    // Add labels.
1303    wxString str;
1304    int units;
1305    if (m_Metric) {
1306        Double km = size_snap * 1e-3;
1307        if (km >= 1.0) {
1308            size_snap = km;
1309            /* TRANSLATORS: abbreviation for "kilometres" (unit of length),
1310             * used e.g.  "5km".
1311             *
1312             * If there should be a space between the number and this, include
1313             * one in the translation. */
1314            units = /*km*/423;
1315        } else if (size_snap >= 1.0) {
1316            /* TRANSLATORS: abbreviation for "metres" (unit of length), used
1317             * e.g. "10m".
1318             *
1319             * If there should be a space between the number and this, include
1320             * one in the translation. */
1321            units = /*m*/424;
1322        } else {
1323            size_snap *= 1e2;
1324            /* TRANSLATORS: abbreviation for "centimetres" (unit of length),
1325             * used e.g.  "50cm".
1326             *
1327             * If there should be a space between the number and this, include
1328             * one in the translation. */
1329            units = /*cm*/425;
1330        }
1331    } else {
1332        size_snap /= METRES_PER_FOOT;
1333        Double miles = size_snap / 5280.0;
1334        if (miles >= 1.0) {
1335            size_snap = miles;
1336            if (size_snap >= 2.0) {
1337                /* TRANSLATORS: abbreviation for "miles" (unit of length,
1338                 * plural), used e.g.  "2 miles".
1339                 *
1340                 * If there should be a space between the number and this,
1341                 * include one in the translation. */
1342                units = /* miles*/426;
1343            } else {
1344                /* TRANSLATORS: abbreviation for "mile" (unit of length,
1345                 * singular), used e.g.  "1 mile".
1346                 *
1347                 * If there should be a space between the number and this,
1348                 * include one in the translation. */
1349                units = /* mile*/427;
1350            }
1351        } else if (size_snap >= 1.0) {
1352            /* TRANSLATORS: abbreviation for "feet" (unit of length), used e.g.
1353             * as "10ft".
1354             *
1355             * If there should be a space between the number and this, include
1356             * one in the translation. */
1357            units = /*ft*/428;
1358        } else {
1359            size_snap *= 12.0;
1360            /* TRANSLATORS: abbreviation for "inches" (unit of length), used
1361             * e.g. as "6in".
1362             *
1363             * If there should be a space between the number and this, include
1364             * one in the translation. */
1365            units = /*in*/429;
1366        }
1367    }
1368    if (size_snap >= 1.0) {
1369        str.Printf(wxT("%.f%s"), size_snap, wmsg(units).c_str());
1370    } else {
1371        int sf = -(int)floor(log10(size_snap));
1372        str.Printf(wxT("%.*f%s"), sf, size_snap, wmsg(units).c_str());
1373    }
1374
1375    int text_width, text_height;
1376    GetTextExtent(str, &text_width, &text_height);
1377    const int text_y = end_y - text_height + 1;
1378    SetColour(TEXT_COLOUR);
1379    DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
1380    DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
1381}
1382
1383bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
1384{
1385    if (Animating()) return false;
1386
1387    if (point.x < 0 || point.x >= GetXSize() ||
1388        point.y < 0 || point.y >= GetYSize()) {
1389        return false;
1390    }
1391
1392    SetDataTransform();
1393
1394    if (!m_HitTestGridValid) CreateHitTestGrid();
1395
1396    int grid_x = point.x * HITTEST_SIZE / (GetXSize() + 1);
1397    int grid_y = point.y * HITTEST_SIZE / (GetYSize() + 1);
1398
1399    LabelInfo *best = NULL;
1400    int dist_sqrd = sqrd_measure_threshold;
1401    int square = grid_x + grid_y * HITTEST_SIZE;
1402    list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
1403
1404    while (iter != m_PointGrid[square].end()) {
1405        LabelInfo *pt = *iter++;
1406
1407        double cx, cy, cz;
1408
1409        Transform(*pt, &cx, &cy, &cz);
1410
1411        cy = GetYSize() - cy;
1412
1413        int dx = point.x - int(cx);
1414        int ds = dx * dx;
1415        if (ds >= dist_sqrd) continue;
1416        int dy = point.y - int(cy);
1417
1418        ds += dy * dy;
1419        if (ds >= dist_sqrd) continue;
1420
1421        dist_sqrd = ds;
1422        best = pt;
1423
1424        if (ds == 0) break;
1425    }
1426
1427    if (best) {
1428        m_Parent->ShowInfo(best, m_there);
1429        if (centre) {
1430            // FIXME: allow Ctrl-Click to not set there or something?
1431            CentreOn(*best);
1432            WarpPointer(GetXSize() / 2, GetYSize() / 2);
1433            SetThere(best);
1434            m_Parent->SelectTreeItem(best);
1435        }
1436    } else {
1437        // Left-clicking not on a survey cancels the measuring line.
1438        if (centre) {
1439            ClearTreeSelection();
1440        } else {
1441            m_Parent->ShowInfo(best, m_there);
1442            double x, y, z;
1443            ReverseTransform(point.x, GetYSize() - point.y, &x, &y, &z);
1444            temp_here.assign(Vector3(x, y, z));
1445            SetHere(&temp_here);
1446        }
1447    }
1448
1449    return best;
1450}
1451
1452void GfxCore::OnSize(wxSizeEvent& event)
1453{
1454    // Handle a change in window size.
1455    wxSize size = event.GetSize();
1456
1457    if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
1458        // Before things are fully initialised, we sometimes get a bogus
1459        // resize message...
1460        // FIXME have changes in MainFrm cured this?  It still happens with
1461        // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1462        // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
1463        // is resized such that the GfxCore window isn't visible.
1464        //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
1465        return;
1466    }
1467
1468    event.Skip();
1469
1470    if (m_DoneFirstShow) {
1471        TryToFreeArrays();
1472
1473        m_HitTestGridValid = false;
1474
1475        ForceRefresh();
1476    }
1477}
1478
1479void GfxCore::DefaultParameters()
1480{
1481    // Set default viewing parameters.
1482
1483    m_Surface = false;
1484    if (!m_Parent->HasUndergroundLegs()) {
1485        if (m_Parent->HasSurfaceLegs()) {
1486            // If there are surface legs, but no underground legs, turn
1487            // surface surveys on.
1488            m_Surface = true;
1489        } else {
1490            // If there are no legs (e.g. after loading a .pos file), turn
1491            // crosses on.
1492            m_Crosses = true;
1493        }
1494    }
1495
1496    m_PanAngle = 0.0;
1497    if (m_Parent->IsExtendedElevation()) {
1498        m_TiltAngle = 0.0;
1499    } else {
1500        m_TiltAngle = -90.0;
1501    }
1502
1503    SetRotation(m_PanAngle, m_TiltAngle);
1504    SetTranslation(Vector3());
1505
1506    m_RotationStep = 30.0;
1507    m_Rotating = false;
1508    m_SwitchingTo = 0;
1509    m_Entrances = false;
1510    m_FixedPts = false;
1511    m_ExportedPts = false;
1512    m_Grid = false;
1513    m_BoundingBox = false;
1514    m_Tubes = false;
1515    if (!GetPerspective()) TogglePerspective();
1516
1517    // Set the initial scale.
1518    SetScale(initial_scale);
1519}
1520
1521void GfxCore::Defaults()
1522{
1523    // Restore default scale, rotation and translation parameters.
1524    DefaultParameters();
1525
1526    // Invalidate all the cached lists.
1527    GLACanvas::FirstShow();
1528
1529    ForceRefresh();
1530}
1531
1532void GfxCore::Animate()
1533{
1534    // Don't show pointer coordinates while animating.
1535    // FIXME : only do this when we *START* animating!  Use a static copy
1536    // of the value of "Animating()" last time we were here to track this?
1537    // MainFrm now checks if we're trying to clear already cleared labels
1538    // and just returns, but it might be simpler to check here!
1539    ClearCoords();
1540    m_Parent->ShowInfo();
1541
1542    long t;
1543    if (movie) {
1544        ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
1545        if (!movie->AddFrame()) {
1546            wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1547            delete movie;
1548            movie = NULL;
1549            presentation_mode = 0;
1550            return;
1551        }
1552        t = 1000 / 25; // 25 frames per second
1553    } else {
1554        static long t_prev = 0;
1555        t = timer.Time();
1556        // Avoid redrawing twice in the same frame.
1557        long delta_t = (t_prev == 0 ? 1000 / MAX_FRAMERATE : t - t_prev);
1558        if (delta_t < 1000 / MAX_FRAMERATE)
1559            return;
1560        t_prev = t;
1561        if (presentation_mode == PLAYING && pres_speed != 0.0)
1562            t = delta_t;
1563    }
1564
1565    if (presentation_mode == PLAYING && pres_speed != 0.0) {
1566        // FIXME: It would probably be better to work relative to the time we
1567        // passed the last mark, but that's complicated by the speed
1568        // potentially changing (or even the direction of playback reversing)
1569        // at any point during playback.
1570        Double tick = t * 0.001 * fabs(pres_speed);
1571        while (tick >= next_mark_time) {
1572            tick -= next_mark_time;
1573            this_mark_total = 0;
1574            PresentationMark prev_mark = next_mark;
1575            if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1576            else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
1577            if (pres_reverse)
1578                next_mark = m_Parent->GetPresMark(MARK_PREV);
1579            else
1580                next_mark = m_Parent->GetPresMark(MARK_NEXT);
1581            if (!next_mark.is_valid()) {
1582                SetView(prev_mark);
1583                presentation_mode = 0;
1584                if (movie && !movie->Close()) {
1585                    wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1586                }
1587                delete movie;
1588                movie = NULL;
1589                break;
1590            }
1591
1592            double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1593            if (tmp > 0) {
1594                next_mark_time = tmp;
1595            } else {
1596                double d = (next_mark - prev_mark).magnitude();
1597                // FIXME: should ignore component of d which is unseen in
1598                // non-perspective mode?
1599                next_mark_time = sqrd(d / 30.0);
1600                double a = next_mark.angle - prev_mark.angle;
1601                if (a > 180.0) {
1602                    next_mark.angle -= 360.0;
1603                    a = 360.0 - a;
1604                } else if (a < -180.0) {
1605                    next_mark.angle += 360.0;
1606                    a += 360.0;
1607                } else {
1608                    a = fabs(a);
1609                }
1610                next_mark_time += sqrd(a / 60.0);
1611                double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1612                next_mark_time += sqrd(ta / 60.0);
1613                double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
1614                next_mark_time += sqrd(s / 2.0);
1615                next_mark_time = sqrt(next_mark_time);
1616                // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
1617                //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
1618                //       next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1619                if (tmp < 0) next_mark_time /= -tmp;
1620            }
1621        }
1622
1623        if (presentation_mode) {
1624            // Advance position towards next_mark
1625            double p = tick / next_mark_time;
1626            double q = 1 - p;
1627            PresentationMark here = GetView();
1628            if (next_mark.angle < 0) {
1629                if (here.angle >= next_mark.angle + 360.0)
1630                    here.angle -= 360.0;
1631            } else if (next_mark.angle >= 360.0) {
1632                if (here.angle <= next_mark.angle - 360.0)
1633                    here.angle += 360.0;
1634            }
1635            here.assign(q * here + p * next_mark);
1636            here.angle = q * here.angle + p * next_mark.angle;
1637            if (here.angle < 0) here.angle += 360.0;
1638            else if (here.angle >= 360.0) here.angle -= 360.0;
1639            here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
1640            here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
1641            SetView(here);
1642            this_mark_total += tick;
1643            next_mark_time -= tick;
1644        }
1645
1646        ForceRefresh();
1647        return;
1648    }
1649
1650    // When rotating...
1651    if (m_Rotating) {
1652        Double step = base_pan + (t - base_pan_time) * 1e-3 * m_RotationStep - m_PanAngle;
1653        TurnCave(step);
1654    }
1655
1656    if (m_SwitchingTo == PLAN) {
1657        // When switching to plan view...
1658        Double step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1659        TiltCave(step);
1660        if (m_TiltAngle == -90.0) {
1661            m_SwitchingTo = 0;
1662        }
1663    } else if (m_SwitchingTo == ELEVATION) {
1664        // When switching to elevation view...
1665        Double step;
1666        if (m_TiltAngle > 0.0) {
1667            step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1668        } else {
1669            step = base_tilt + (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1670        }
1671        if (fabs(step) >= fabs(m_TiltAngle)) {
1672            m_SwitchingTo = 0;
1673            step = -m_TiltAngle;
1674        }
1675        TiltCave(step);
1676    } else if (m_SwitchingTo) {
1677        // Rotate the shortest way around to the destination angle.  If we're
1678        // 180 off, we favour turning anticlockwise, as auto-rotation does by
1679        // default.
1680        Double target = (m_SwitchingTo - NORTH) * 90;
1681        Double diff = target - m_PanAngle;
1682        diff = fmod(diff, 360);
1683        if (diff <= -180)
1684            diff += 360;
1685        else if (diff > 180)
1686            diff -= 360;
1687        if (m_RotationStep < 0 && diff == 180.0)
1688            diff = -180.0;
1689        Double step = base_pan - m_PanAngle;
1690        Double delta = (t - base_pan_time) * 1e-3 * fabs(m_RotationStep);
1691        if (diff > 0) {
1692            step += delta;
1693        } else {
1694            step -= delta;
1695        }
1696        step = fmod(step, 360);
1697        if (step <= -180)
1698            step += 360;
1699        else if (step > 180)
1700            step -= 360;
1701        if (fabs(step) >= fabs(diff)) {
1702            m_SwitchingTo = 0;
1703            step = diff;
1704        }
1705        TurnCave(step);
1706    }
1707
1708    ForceRefresh();
1709}
1710
1711// How much to allow around the box - this is because of the ring shape
1712// at one end of the line.
1713static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1714#define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1715void GfxCore::RefreshLine(const Point *a, const Point *b, const Point *c)
1716{
1717#ifdef __WXMSW__
1718    (void)a;
1719    (void)b;
1720    (void)c;
1721    // FIXME: We get odd redraw artifacts if we just update the line, and
1722    // redrawing the whole scene doesn't actually seem to be measurably
1723    // slower.  That may not be true with software rendering though...
1724    ForceRefresh();
1725#else
1726    // Best of all might be to copy the window contents before we draw the
1727    // line, then replace each time we redraw.
1728
1729    // Calculate the minimum rectangle which includes the old and new
1730    // measuring lines to minimise the redraw time
1731    int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
1732    double X, Y, Z;
1733    if (a) {
1734        if (!Transform(*a, &X, &Y, &Z)) {
1735            printf("oops\n");
1736        } else {
1737            int x = int(X);
1738            int y = GetYSize() - 1 - int(Y);
1739            l = x;
1740            r = x;
1741            u = y;
1742            d = y;
1743        }
1744    }
1745    if (b) {
1746        if (!Transform(*b, &X, &Y, &Z)) {
1747            printf("oops\n");
1748        } else {
1749            int x = int(X);
1750            int y = GetYSize() - 1 - int(Y);
1751            l = min(l, x);
1752            r = max(r, x);
1753            u = max(u, y);
1754            d = min(d, y);
1755        }
1756    }
1757    if (c) {
1758        if (!Transform(*c, &X, &Y, &Z)) {
1759            printf("oops\n");
1760        } else {
1761            int x = int(X);
1762            int y = GetYSize() - 1 - int(Y);
1763            l = min(l, x);
1764            r = max(r, x);
1765            u = max(u, y);
1766            d = min(d, y);
1767        }
1768    }
1769    l -= MARGIN;
1770    r += MARGIN;
1771    u += MARGIN;
1772    d -= MARGIN;
1773    RefreshRect(wxRect(l, d, r - l, u - d), false);
1774#endif
1775}
1776
1777void GfxCore::SetHereFromTree(const LabelInfo * p)
1778{
1779    SetHere(p);
1780    m_Parent->ShowInfo(m_here, m_there);
1781}
1782
1783void GfxCore::SetHere(const LabelInfo *p)
1784{
1785    if (p == m_here) return;
1786    bool line_active = MeasuringLineActive();
1787    const LabelInfo * old = m_here;
1788    m_here = p;
1789    if (line_active || MeasuringLineActive())
1790        RefreshLine(old, m_there, m_here);
1791}
1792
1793void GfxCore::SetThere(const LabelInfo * p)
1794{
1795    if (p == m_there) return;
1796    const LabelInfo * old = m_there;
1797    m_there = p;
1798    RefreshLine(m_here, old, m_there);
1799}
1800
1801void GfxCore::CreateHitTestGrid()
1802{
1803    if (!m_PointGrid) {
1804        // Initialise hit-test grid.
1805        m_PointGrid = new list<LabelInfo*>[HITTEST_SIZE * HITTEST_SIZE];
1806    } else {
1807        // Clear hit-test grid.
1808        for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
1809            m_PointGrid[i].clear();
1810        }
1811    }
1812
1813    // Fill the grid.
1814    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1815    list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1816    while (pos != end) {
1817        LabelInfo* label = *pos++;
1818
1819        if (!((m_Surface && label->IsSurface()) ||
1820              (m_Legs && label->IsUnderground()) ||
1821              (!label->IsSurface() && !label->IsUnderground()))) {
1822            // if this station isn't to be displayed, skip to the next
1823            // (last case is for stns with no legs attached)
1824            continue;
1825        }
1826
1827        // Calculate screen coordinates.
1828        double cx, cy, cz;
1829        Transform(*label, &cx, &cy, &cz);
1830        if (cx < 0 || cx >= GetXSize()) continue;
1831        if (cy < 0 || cy >= GetYSize()) continue;
1832
1833        cy = GetYSize() - cy;
1834
1835        // On-screen, so add to hit-test grid...
1836        int grid_x = int(cx * HITTEST_SIZE / (GetXSize() + 1));
1837        int grid_y = int(cy * HITTEST_SIZE / (GetYSize() + 1));
1838
1839        m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
1840    }
1841
1842    m_HitTestGridValid = true;
1843}
1844
1845//
1846//  Methods for controlling the orientation of the survey
1847//
1848
1849void GfxCore::TurnCave(Double angle)
1850{
1851    // Turn the cave around its z-axis by a given angle.
1852
1853    m_PanAngle += angle;
1854    // Wrap to range [0, 360):
1855    m_PanAngle = fmod(m_PanAngle, 360.0);
1856    if (m_PanAngle < 0.0) {
1857        m_PanAngle += 360.0;
1858    }
1859
1860    m_HitTestGridValid = false;
1861    if (m_here && m_here == &temp_here) SetHere();
1862
1863    SetRotation(m_PanAngle, m_TiltAngle);
1864}
1865
1866void GfxCore::TurnCaveTo(Double angle)
1867{
1868    if (m_Rotating) {
1869        // If we're rotating, jump to the specified angle.
1870        TurnCave(angle - m_PanAngle);
1871        SetPanBase();
1872        return;
1873    }
1874
1875    int new_switching_to = ((int)angle) / 90 + NORTH;
1876    if (new_switching_to == m_SwitchingTo) {
1877        // A second order to switch takes us there right away
1878        TurnCave(angle - m_PanAngle);
1879        m_SwitchingTo = 0;
1880        ForceRefresh();
1881    } else {
1882        SetPanBase();
1883        m_SwitchingTo = new_switching_to;
1884    }
1885}
1886
1887void GfxCore::TiltCave(Double tilt_angle)
1888{
1889    // Tilt the cave by a given angle.
1890    if (m_TiltAngle + tilt_angle > 90.0) {
1891        m_TiltAngle = 90.0;
1892    } else if (m_TiltAngle + tilt_angle < -90.0) {
1893        m_TiltAngle = -90.0;
1894    } else {
1895        m_TiltAngle += tilt_angle;
1896    }
1897
1898    m_HitTestGridValid = false;
1899    if (m_here && m_here == &temp_here) SetHere();
1900
1901    SetRotation(m_PanAngle, m_TiltAngle);
1902}
1903
1904void GfxCore::TranslateCave(int dx, int dy)
1905{
1906    AddTranslationScreenCoordinates(dx, dy);
1907    m_HitTestGridValid = false;
1908
1909    if (m_here && m_here == &temp_here) SetHere();
1910
1911    ForceRefresh();
1912}
1913
1914void GfxCore::DragFinished()
1915{
1916    m_MouseOutsideCompass = m_MouseOutsideElev = false;
1917    ForceRefresh();
1918}
1919
1920void GfxCore::ClearCoords()
1921{
1922    m_Parent->ClearCoords();
1923}
1924
1925void GfxCore::SetCoords(wxPoint point)
1926{
1927    // We can't work out 2D coordinates from a perspective view, and it
1928    // doesn't really make sense to show coordinates while we're animating.
1929    if (GetPerspective() || Animating()) return;
1930
1931    // Update the coordinate or altitude display, given the (x, y) position in
1932    // window coordinates.  The relevant display is updated depending on
1933    // whether we're in plan or elevation view.
1934
1935    double cx, cy, cz;
1936
1937    SetDataTransform();
1938    ReverseTransform(point.x, GetYSize() - 1 - point.y, &cx, &cy, &cz);
1939
1940    if (ShowingPlan()) {
1941        m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
1942                            cy + m_Parent->GetOffset().GetY(),
1943                            m_there);
1944    } else if (ShowingElevation()) {
1945        m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ(),
1946                              m_there);
1947    } else {
1948        m_Parent->ClearCoords();
1949    }
1950}
1951
1952int GfxCore::GetCompassWidth() const
1953{
1954    static int result = 0;
1955    if (result == 0) {
1956        result = INDICATOR_BOX_SIZE;
1957        int width;
1958        const wxString & msg = wmsg(/*Facing*/203);
1959        GetTextExtent(msg, &width, NULL);
1960        if (width > result) result = width;
1961    }
1962    return result;
1963}
1964
1965int GfxCore::GetClinoWidth() const
1966{
1967    static int result = 0;
1968    if (result == 0) {
1969        result = INDICATOR_BOX_SIZE;
1970        int width;
1971        const wxString & msg1 = wmsg(/*Plan*/432);
1972        GetTextExtent(msg1, &width, NULL);
1973        if (width > result) result = width;
1974        const wxString & msg2 = wmsg(/*Kiwi Plan*/433);
1975        GetTextExtent(msg2, &width, NULL);
1976        if (width > result) result = width;
1977        const wxString & msg3 = wmsg(/*Elevation*/118);
1978        GetTextExtent(msg3, &width, NULL);
1979        if (width > result) result = width;
1980    }
1981    return result;
1982}
1983
1984int GfxCore::GetCompassXPosition() const
1985{
1986    // Return the x-coordinate of the centre of the compass in window
1987    // coordinates.
1988    return GetXSize() - INDICATOR_OFFSET_X - GetCompassWidth() / 2;
1989}
1990
1991int GfxCore::GetClinoXPosition() const
1992{
1993    // Return the x-coordinate of the centre of the compass in window
1994    // coordinates.
1995    return GetXSize() - GetClinoOffset() - GetClinoWidth() / 2;
1996}
1997
1998int GfxCore::GetIndicatorYPosition() const
1999{
2000    // Return the y-coordinate of the centre of the indicators in window
2001    // coordinates.
2002    return GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
2003}
2004
2005int GfxCore::GetIndicatorRadius() const
2006{
2007    // Return the radius of each indicator.
2008    return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
2009}
2010
2011bool GfxCore::PointWithinCompass(wxPoint point) const
2012{
2013    // Determine whether a point (in window coordinates) lies within the
2014    // compass.
2015    if (!ShowingCompass()) return false;
2016
2017    glaCoord dx = point.x - GetCompassXPosition();
2018    glaCoord dy = point.y - GetIndicatorYPosition();
2019    glaCoord radius = GetIndicatorRadius();
2020
2021    return (dx * dx + dy * dy <= radius * radius);
2022}
2023
2024bool GfxCore::PointWithinClino(wxPoint point) const
2025{
2026    // Determine whether a point (in window coordinates) lies within the clino.
2027    if (!ShowingClino()) return false;
2028
2029    glaCoord dx = point.x - GetClinoXPosition();
2030    glaCoord dy = point.y - GetIndicatorYPosition();
2031    glaCoord radius = GetIndicatorRadius();
2032
2033    return (dx * dx + dy * dy <= radius * radius);
2034}
2035
2036bool GfxCore::PointWithinScaleBar(wxPoint point) const
2037{
2038    // Determine whether a point (in window coordinates) lies within the scale
2039    // bar.
2040    if (!ShowingScaleBar()) return false;
2041
2042    return (point.x >= SCALE_BAR_OFFSET_X &&
2043            point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
2044            point.y <= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
2045            point.y >= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
2046}
2047
2048bool GfxCore::PointWithinColourKey(wxPoint point) const
2049{
2050    // Determine whether a point (in window coordinates) lies within the key.
2051    point.x -= GetXSize() - KEY_OFFSET_X;
2052    point.y = KEY_OFFSET_Y - point.y;
2053    return (point.x >= key_lowerleft[m_ColourBy].x && point.x <= 0 &&
2054            point.y >= key_lowerleft[m_ColourBy].y && point.y <= 0);
2055}
2056
2057void GfxCore::SetCompassFromPoint(wxPoint point)
2058{
2059    // Given a point in window coordinates, set the heading of the survey.  If
2060    // the point is outside the compass, it snaps to 45 degree intervals;
2061    // otherwise it operates as normal.
2062
2063    wxCoord dx = point.x - GetCompassXPosition();
2064    wxCoord dy = point.y - GetIndicatorYPosition();
2065    wxCoord radius = GetIndicatorRadius();
2066
2067    double angle = deg(atan2(double(dx), double(dy))) - 180.0;
2068    if (dx * dx + dy * dy <= radius * radius) {
2069        TurnCave(angle - m_PanAngle);
2070        m_MouseOutsideCompass = false;
2071    } else {
2072        TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
2073        m_MouseOutsideCompass = true;
2074    }
2075
2076    ForceRefresh();
2077}
2078
2079void GfxCore::SetClinoFromPoint(wxPoint point)
2080{
2081    // Given a point in window coordinates, set the elevation of the survey.
2082    // If the point is outside the clino, it snaps to 90 degree intervals;
2083    // otherwise it operates as normal.
2084
2085    glaCoord dx = point.x - GetClinoXPosition();
2086    glaCoord dy = point.y - GetIndicatorYPosition();
2087    glaCoord radius = GetIndicatorRadius();
2088
2089    if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
2090        TiltCave(-deg(atan2(double(dy), double(dx))) - m_TiltAngle);
2091        m_MouseOutsideElev = false;
2092    } else if (dy >= INDICATOR_MARGIN) {
2093        TiltCave(-90.0 - m_TiltAngle);
2094        m_MouseOutsideElev = true;
2095    } else if (dy <= -INDICATOR_MARGIN) {
2096        TiltCave(90.0 - m_TiltAngle);
2097        m_MouseOutsideElev = true;
2098    } else {
2099        TiltCave(-m_TiltAngle);
2100        m_MouseOutsideElev = true;
2101    }
2102
2103    ForceRefresh();
2104}
2105
2106void GfxCore::SetScaleBarFromOffset(wxCoord dx)
2107{
2108    // Set the scale of the survey, given an offset as to how much the mouse has
2109    // been dragged over the scalebar since the last scale change.
2110
2111    SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
2112    ForceRefresh();
2113}
2114
2115void GfxCore::RedrawIndicators()
2116{
2117    // Redraw the compass and clino indicators.
2118
2119    int total_width = GetCompassWidth() + INDICATOR_GAP + GetClinoWidth();
2120    RefreshRect(wxRect(GetXSize() - INDICATOR_OFFSET_X - total_width,
2121                       GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
2122                       total_width,
2123                       INDICATOR_BOX_SIZE), false);
2124}
2125
2126void GfxCore::StartRotation()
2127{
2128    // Start the survey rotating.
2129
2130    if (m_SwitchingTo >= NORTH)
2131        m_SwitchingTo = 0;
2132    m_Rotating = true;
2133    SetPanBase();
2134}
2135
2136void GfxCore::ToggleRotation()
2137{
2138    // Toggle the survey rotation on/off.
2139
2140    if (m_Rotating) {
2141        StopRotation();
2142    } else {
2143        StartRotation();
2144    }
2145}
2146
2147void GfxCore::StopRotation()
2148{
2149    // Stop the survey rotating.
2150
2151    m_Rotating = false;
2152    ForceRefresh();
2153}
2154
2155bool GfxCore::IsExtendedElevation() const
2156{
2157    return m_Parent->IsExtendedElevation();
2158}
2159
2160void GfxCore::ReverseRotation()
2161{
2162    // Reverse the direction of rotation.
2163
2164    m_RotationStep = -m_RotationStep;
2165    if (m_Rotating)
2166        SetPanBase();
2167}
2168
2169void GfxCore::RotateSlower(bool accel)
2170{
2171    // Decrease the speed of rotation, optionally by an increased amount.
2172    if (fabs(m_RotationStep) == 1.0)
2173        return;
2174
2175    m_RotationStep *= accel ? (1 / 1.44) : (1 / 1.2);
2176
2177    if (fabs(m_RotationStep) < 1.0) {
2178        m_RotationStep = (m_RotationStep > 0 ? 1.0 : -1.0);
2179    }
2180    if (m_Rotating)
2181        SetPanBase();
2182}
2183
2184void GfxCore::RotateFaster(bool accel)
2185{
2186    // Increase the speed of rotation, optionally by an increased amount.
2187    if (fabs(m_RotationStep) == 180.0)
2188        return;
2189
2190    m_RotationStep *= accel ? 1.44 : 1.2;
2191    if (fabs(m_RotationStep) > 180.0) {
2192        m_RotationStep = (m_RotationStep > 0 ? 180.0 : -180.0);
2193    }
2194    if (m_Rotating)
2195        SetPanBase();
2196}
2197
2198void GfxCore::SwitchToElevation()
2199{
2200    // Perform an animated switch to elevation view.
2201
2202    if (m_SwitchingTo != ELEVATION) {
2203        SetTiltBase();
2204        m_SwitchingTo = ELEVATION;
2205    } else {
2206        // A second order to switch takes us there right away
2207        TiltCave(-m_TiltAngle);
2208        m_SwitchingTo = 0;
2209        ForceRefresh();
2210    }
2211}
2212
2213void GfxCore::SwitchToPlan()
2214{
2215    // Perform an animated switch to plan view.
2216
2217    if (m_SwitchingTo != PLAN) {
2218        SetTiltBase();
2219        m_SwitchingTo = PLAN;
2220    } else {
2221        // A second order to switch takes us there right away
2222        TiltCave(-90.0 - m_TiltAngle);
2223        m_SwitchingTo = 0;
2224        ForceRefresh();
2225    }
2226}
2227
2228void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
2229{
2230
2231    SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
2232    Double scale = HUGE_VAL;
2233    const Vector3 ext = m_Parent->GetExtent();
2234    if (xmax > xmin) {
2235        Double s = ext.GetX() / (xmax - xmin);
2236        if (s < scale) scale = s;
2237    }
2238    if (ymax > ymin) {
2239        Double s = ext.GetY() / (ymax - ymin);
2240        if (s < scale) scale = s;
2241    }
2242    if (!ShowingPlan() && zmax > zmin) {
2243        Double s = ext.GetZ() / (zmax - zmin);
2244        if (s < scale) scale = s;
2245    }
2246    if (scale != HUGE_VAL) SetScale(scale);
2247    ForceRefresh();
2248}
2249
2250bool GfxCore::CanRaiseViewpoint() const
2251{
2252    // Determine if the survey can be viewed from a higher angle of elevation.
2253
2254    return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
2255}
2256
2257bool GfxCore::CanLowerViewpoint() const
2258{
2259    // Determine if the survey can be viewed from a lower angle of elevation.
2260
2261    return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
2262}
2263
2264bool GfxCore::HasDepth() const
2265{
2266    return m_Parent->GetDepthExtent() == 0.0;
2267}
2268
2269bool GfxCore::HasErrorInformation() const
2270{
2271    return m_Parent->HasErrorInformation();
2272}
2273
2274bool GfxCore::HasDateInformation() const
2275{
2276    return m_Parent->GetDateMin() >= 0;
2277}
2278
2279bool GfxCore::ShowingPlan() const
2280{
2281    // Determine if the survey is in plan view.
2282
2283    return (m_TiltAngle == -90.0);
2284}
2285
2286bool GfxCore::ShowingElevation() const
2287{
2288    // Determine if the survey is in elevation view.
2289
2290    return (m_TiltAngle == 0.0);
2291}
2292
2293bool GfxCore::ShowingMeasuringLine() const
2294{
2295    // Determine if the measuring line is being shown.  Only check if "there"
2296    // is valid, since that means the measuring line anchor is out.
2297
2298    return m_there;
2299}
2300
2301void GfxCore::ToggleFlag(bool* flag, int update)
2302{
2303    *flag = !*flag;
2304    if (update == UPDATE_BLOBS) {
2305        UpdateBlobs();
2306    } else if (update == UPDATE_BLOBS_AND_CROSSES) {
2307        UpdateBlobs();
2308        InvalidateList(LIST_CROSSES);
2309        m_HitTestGridValid = false;
2310    }
2311    ForceRefresh();
2312}
2313
2314int GfxCore::GetNumEntrances() const
2315{
2316    return m_Parent->GetNumEntrances();
2317}
2318
2319int GfxCore::GetNumFixedPts() const
2320{
2321    return m_Parent->GetNumFixedPts();
2322}
2323
2324int GfxCore::GetNumExportedPts() const
2325{
2326    return m_Parent->GetNumExportedPts();
2327}
2328
2329void GfxCore::ToggleTerrain()
2330{
2331    if (!m_Terrain && !dem) {
2332        // OnOpenTerrain() calls us if a file is selected.
2333        wxCommandEvent dummy;
2334        m_Parent->OnOpenTerrain(dummy);
2335        return;
2336    }
2337    ToggleFlag(&m_Terrain);
2338}
2339
2340void GfxCore::ToggleFatFinger()
2341{
2342    if (sqrd_measure_threshold == sqrd(MEASURE_THRESHOLD)) {
2343        sqrd_measure_threshold = sqrd(5 * MEASURE_THRESHOLD);
2344        wxMessageBox(wxT("Fat finger enabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2345    } else {
2346        sqrd_measure_threshold = sqrd(MEASURE_THRESHOLD);
2347        wxMessageBox(wxT("Fat finger disabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2348    }
2349}
2350
2351void GfxCore::ClearTreeSelection()
2352{
2353    m_Parent->ClearTreeSelection();
2354}
2355
2356void GfxCore::CentreOn(const Point &p)
2357{
2358    SetTranslation(-p);
2359    m_HitTestGridValid = false;
2360
2361    ForceRefresh();
2362}
2363
2364void GfxCore::ForceRefresh()
2365{
2366    Refresh(false);
2367}
2368
2369void GfxCore::GenerateList(unsigned int l)
2370{
2371    assert(m_HaveData);
2372
2373    switch (l) {
2374        case LIST_COMPASS:
2375            DrawCompass();
2376            break;
2377        case LIST_CLINO:
2378            DrawClino();
2379            break;
2380        case LIST_CLINO_BACK:
2381            DrawClinoBack();
2382            break;
2383        case LIST_SCALE_BAR:
2384            DrawScaleBar();
2385            break;
2386        case LIST_DEPTH_KEY:
2387            DrawDepthKey();
2388            break;
2389        case LIST_DATE_KEY:
2390            DrawDateKey();
2391            break;
2392        case LIST_ERROR_KEY:
2393            DrawErrorKey();
2394            break;
2395        case LIST_GRADIENT_KEY:
2396            DrawGradientKey();
2397            break;
2398        case LIST_LENGTH_KEY:
2399            DrawLengthKey();
2400            break;
2401        case LIST_UNDERGROUND_LEGS:
2402            GenerateDisplayList(false);
2403            break;
2404        case LIST_TUBES:
2405            GenerateDisplayListTubes();
2406            break;
2407        case LIST_SURFACE_LEGS:
2408            GenerateDisplayList(true);
2409            break;
2410        case LIST_BLOBS:
2411            GenerateBlobsDisplayList();
2412            break;
2413        case LIST_CROSSES: {
2414            BeginCrosses();
2415            SetColour(col_LIGHT_GREY);
2416            list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2417            while (pos != m_Parent->GetLabelsEnd()) {
2418                const LabelInfo* label = *pos++;
2419
2420                if ((m_Surface && label->IsSurface()) ||
2421                    (m_Legs && label->IsUnderground()) ||
2422                    (!label->IsSurface() && !label->IsUnderground())) {
2423                    // Check if this station should be displayed
2424                    // (last case is for stns with no legs attached)
2425                    DrawCross(label->GetX(), label->GetY(), label->GetZ());
2426                }
2427            }
2428            EndCrosses();
2429            break;
2430        }
2431        case LIST_GRID:
2432            DrawGrid();
2433            break;
2434        case LIST_SHADOW:
2435            GenerateDisplayListShadow();
2436            break;
2437        case LIST_TERRAIN:
2438            DrawTerrain();
2439            break;
2440        default:
2441            assert(false);
2442            break;
2443    }
2444}
2445
2446void GfxCore::ToggleSmoothShading()
2447{
2448    GLACanvas::ToggleSmoothShading();
2449    InvalidateList(LIST_TUBES);
2450    ForceRefresh();
2451}
2452
2453void GfxCore::GenerateDisplayList(bool surface)
2454{
2455    unsigned surf_or_not = surface ? img_FLAG_SURFACE : 0;
2456    // Generate the display list for the surface or underground legs.
2457    for (int f = 0; f != 8; ++f) {
2458        if ((f & img_FLAG_SURFACE) != surf_or_not) continue;
2459        const unsigned SHOW_DASHED_AND_FADED = unsigned(-1);
2460        unsigned style = SHOW_NORMAL;
2461        if ((f & img_FLAG_SPLAY) && m_Splays != SHOW_NORMAL) {
2462            style = m_Splays;
2463        } else if (f & img_FLAG_DUPLICATE) {
2464            style = m_Dupes;
2465        }
2466        if (f & img_FLAG_SURFACE) {
2467            if (style == SHOW_FADED) {
2468                style = SHOW_DASHED_AND_FADED;
2469            } else {
2470                style = SHOW_DASHED;
2471            }
2472        }
2473
2474        switch (style) {
2475            case SHOW_HIDE:
2476                continue;
2477            case SHOW_FADED:
2478                SetAlpha(0.4);
2479                break;
2480            case SHOW_DASHED:
2481                EnableDashedLines();
2482                break;
2483            case SHOW_DASHED_AND_FADED:
2484                SetAlpha(0.4);
2485                EnableDashedLines();
2486                break;
2487        }
2488
2489        void (GfxCore::* add_poly)(const traverse&);
2490        if (surface) {
2491            if (m_ColourBy == COLOUR_BY_ERROR) {
2492                add_poly = &GfxCore::AddPolylineError;
2493            } else {
2494                add_poly = &GfxCore::AddPolyline;
2495            }
2496        } else {
2497            add_poly = AddPoly;
2498        }
2499
2500        list<traverse>::const_iterator trav = m_Parent->traverses_begin(f);
2501        list<traverse>::const_iterator tend = m_Parent->traverses_end(f);
2502        while (trav != tend) {
2503            (this->*add_poly)(*trav);
2504            ++trav;
2505        }
2506
2507        switch (style) {
2508            case SHOW_FADED:
2509                SetAlpha(1.0);
2510                break;
2511            case SHOW_DASHED:
2512                DisableDashedLines();
2513                break;
2514            case SHOW_DASHED_AND_FADED:
2515                DisableDashedLines();
2516                SetAlpha(1.0);
2517                break;
2518        }
2519    }
2520}
2521
2522void GfxCore::GenerateDisplayListTubes()
2523{
2524    // Generate the display list for the tubes.
2525    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
2526    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
2527    while (trav != tend) {
2528        SkinPassage(*trav);
2529        ++trav;
2530    }
2531}
2532
2533void GfxCore::GenerateDisplayListShadow()
2534{
2535    SetColour(col_BLACK);
2536    for (int f = 0; f != 8; ++f) {
2537        // Only include underground legs in the shadow.
2538        if ((f & img_FLAG_SURFACE) != 0) continue;
2539        list<traverse>::const_iterator trav = m_Parent->traverses_begin(f);
2540        list<traverse>::const_iterator tend = m_Parent->traverses_end(f);
2541        while (trav != tend) {
2542            AddPolylineShadow(*trav);
2543            ++trav;
2544        }
2545    }
2546}
2547
2548void
2549GfxCore::parse_hgt_filename(const wxString & lc_name)
2550{
2551    char * leaf = leaf_from_fnm(lc_name.utf8_str());
2552    const char * p = leaf;
2553    char * q;
2554    char dirn = *p++;
2555    o_y = strtoul(p, &q, 10);
2556    p = q;
2557    if (dirn == 's')
2558        o_y = -o_y;
2559    ++o_y;
2560    dirn = *p++;
2561    o_x = strtoul(p, &q, 10);
2562    if (dirn == 'w')
2563        o_x = -o_x;
2564    bigendian = true;
2565    nodata_value = -32768;
2566    osfree(leaf);
2567}
2568
2569size_t
2570GfxCore::parse_hdr(wxInputStream & is, unsigned long & skipbytes)
2571{
2572    // ESRI docs say NBITS defaults to 8.
2573    unsigned long nbits = 8;
2574    // ESRI docs say NBANDS defaults to 1.
2575    unsigned long nbands = 1;
2576    unsigned long bandrowbytes = 0;
2577    unsigned long totalrowbytes = 0;
2578    // ESRI docs say ULXMAP defaults to 0.
2579    o_x = 0.0;
2580    // ESRI docs say ULYMAP defaults to NROWS - 1.
2581    o_y = HUGE_VAL;
2582    // ESRI docs say XDIM and YDIM default to 1.
2583    step_x = step_y = 1.0;
2584    while (!is.Eof()) {
2585        wxString line;
2586        int ch;
2587        while ((ch = is.GetC()) != wxEOF) {
2588            if (ch == '\n' || ch == '\r') break;
2589            line += wxChar(ch);
2590        }
2591#define CHECK(X, COND) \
2592} else if (line.StartsWith(wxT(X " "))) { \
2593size_t v = line.find_first_not_of(wxT(' '), sizeof(X)); \
2594if (v == line.npos || !(COND)) { \
2595err += wxT("Unexpected value for " X); \
2596}
2597        wxString err;
2598        if (false) {
2599        // I = little-endian; M = big-endian
2600        CHECK("BYTEORDER", (bigendian = (line[v] == 'M')) || line[v] == 'I')
2601        // ESRI docs say LAYOUT defaults to BIL if not specified.
2602        CHECK("LAYOUT", line.substr(v) == wxT("BIL"))
2603        CHECK("NROWS", line.substr(v).ToCULong(&dem_height))
2604        CHECK("NCOLS", line.substr(v).ToCULong(&dem_width))
2605        // ESRI docs say NBANDS defaults to 1 if not specified.
2606        CHECK("NBANDS", line.substr(v).ToCULong(&nbands) && nbands == 1)
2607        CHECK("NBITS", line.substr(v).ToCULong(&nbits) && nbits == 16)
2608        CHECK("BANDROWBYTES", line.substr(v).ToCULong(&bandrowbytes))
2609        CHECK("TOTALROWBYTES", line.substr(v).ToCULong(&totalrowbytes))
2610        // PIXELTYPE is a GDAL extension, so may not be present.
2611        CHECK("PIXELTYPE", line.substr(v) == wxT("SIGNEDINT"))
2612        CHECK("ULXMAP", line.substr(v).ToCDouble(&o_x))
2613        CHECK("ULYMAP", line.substr(v).ToCDouble(&o_y))
2614        CHECK("XDIM", line.substr(v).ToCDouble(&step_x))
2615        CHECK("YDIM", line.substr(v).ToCDouble(&step_y))
2616        CHECK("NODATA", line.substr(v).ToCLong(&nodata_value))
2617        CHECK("SKIPBYTES", line.substr(v).ToCULong(&skipbytes))
2618        }
2619        if (!err.empty()) {
2620            wxMessageBox(err);
2621        }
2622    }
2623    if (o_y == HUGE_VAL) {
2624        o_y = dem_height - 1;
2625    }
2626    if (bandrowbytes != 0) {
2627        if (nbits * dem_width != bandrowbytes * 8) {
2628            wxMessageBox("BANDROWBYTES setting indicates unused bits after each band - not currently supported");
2629        }
2630    }
2631    if (totalrowbytes != 0) {
2632        // This is the ESRI default for BIL, for BIP it would be
2633        // nbands * bandrowbytes.
2634        if (nbands * nbits * dem_width != totalrowbytes * 8) {
2635            wxMessageBox("TOTALROWBYTES setting indicates unused bits after "
2636                         "each row - not currently supported");
2637        }
2638    }
2639    return ((nbits * dem_width + 7) / 8) * dem_height;
2640}
2641
2642bool
2643GfxCore::read_bil(wxInputStream & is, size_t size, unsigned long skipbytes)
2644{
2645    bool know_size = true;
2646    if (!size) {
2647        // If the stream doesn't know its size, GetSize() returns 0.
2648        size = is.GetSize();
2649        if (!size) {
2650            size = DEFAULT_HGT_SIZE;
2651            know_size = false;
2652        }
2653    }
2654    dem = new unsigned short[size / 2];
2655    if (skipbytes) {
2656        if (is.SeekI(skipbytes, wxFromStart) == ::wxInvalidOffset) {
2657            while (skipbytes) {
2658                unsigned long to_read = skipbytes;
2659                if (size < to_read) to_read = size;
2660                is.Read(reinterpret_cast<char *>(dem), to_read);
2661                size_t c = is.LastRead();
2662                if (c == 0) {
2663                    wxMessageBox(wxT("Failed to skip terrain data header"));
2664                    break;
2665                }
2666                skipbytes -= c;
2667            }
2668        }
2669    }
2670
2671#if wxCHECK_VERSION(2,9,5)
2672    if (!is.ReadAll(dem, size)) {
2673        if (know_size) {
2674            // FIXME: On __WXMSW__ currently we fail to
2675            // read any data from files in zips.
2676            delete [] dem;
2677            dem = NULL;
2678            wxMessageBox(wxT("Failed to read terrain data"));
2679            return false;
2680        }
2681        size = is.LastRead();
2682    }
2683#else
2684    char * p = reinterpret_cast<char *>(dem);
2685    while (size) {
2686        is.Read(p, size);
2687        size_t c = is.LastRead();
2688        if (c == 0) {
2689            if (!know_size) {
2690                size = DEFAULT_HGT_SIZE - size;
2691                if (size)
2692                    break;
2693            }
2694            delete [] dem;
2695            dem = NULL;
2696            wxMessageBox(wxT("Failed to read terrain data"));
2697            return false;
2698        }
2699        p += c;
2700        size -= c;
2701    }
2702#endif
2703
2704    if (dem_width == 0 && dem_height == 0) {
2705        dem_width = dem_height = sqrt(size / 2);
2706        if (dem_width * dem_height * 2 != size) {
2707            delete [] dem;
2708            dem = NULL;
2709            wxMessageBox(wxT("HGT format data doesn't form a square"));
2710            return false;
2711        }
2712        step_x = step_y = 1.0 / dem_width;
2713    }
2714
2715    return true;
2716}
2717
2718bool GfxCore::LoadDEM(const wxString & file)
2719{
2720    if (m_Parent->GetCSProj().empty()) {
2721        wxMessageBox(wxT("No coordinate system specified in survey data"));
2722        return false;
2723    }
2724
2725    delete [] dem;
2726    dem = NULL;
2727
2728    size_t size = 0;
2729    // Default is to not skip any bytes.
2730    unsigned long skipbytes = 0;
2731    // For .hgt files, default to using filesize to determine.
2732    dem_width = dem_height = 0;
2733    // ESRI say "The default byte order is the same as that of the host machine
2734    // executing the software", but that's stupid so we default to
2735    // little-endian.
2736    bigendian = false;
2737
2738    wxFileInputStream fs(file);
2739    if (!fs.IsOk()) {
2740        wxMessageBox(wxT("Failed to open DEM file"));
2741        return false;
2742    }
2743
2744    const wxString & lc_file = file.Lower();
2745    if (lc_file.EndsWith(wxT(".hgt"))) {
2746        parse_hgt_filename(lc_file);
2747        read_bil(fs, size, skipbytes);
2748    } else if (lc_file.EndsWith(wxT(".bil"))) {
2749        wxString hdr_file = file;
2750        hdr_file.replace(file.size() - 4, 4, wxT(".hdr"));
2751        wxFileInputStream hdr_is(hdr_file);
2752        if (!hdr_is.IsOk()) {
2753            wxMessageBox(wxT("Failed to open HDR file '") + hdr_file + wxT("'"));
2754            return false;
2755        }
2756        size = parse_hdr(hdr_is, skipbytes);
2757        read_bil(fs, size, skipbytes);
2758    } else if (lc_file.EndsWith(wxT(".zip"))) {
2759        wxZipEntry * ze_data = NULL;
2760        wxZipInputStream zs(fs);
2761        wxZipEntry * ze;
2762        while ((ze = zs.GetNextEntry()) != NULL) {
2763            if (!ze->IsDir()) {
2764                const wxString & lc_name = ze->GetName().Lower();
2765                if (!ze_data && lc_name.EndsWith(wxT(".hgt"))) {
2766                    // SRTM .hgt files are raw binary data, with the filename
2767                    // encoding the coordinates.
2768                    parse_hgt_filename(lc_name);
2769                    read_bil(zs, size, skipbytes);
2770                    delete ze;
2771                    break;
2772                }
2773
2774                if (!ze_data && lc_name.EndsWith(wxT(".bil"))) {
2775                    if (size) {
2776                        read_bil(zs, size, skipbytes);
2777                        break;
2778                    }
2779                    ze_data = ze;
2780                    continue;
2781                }
2782
2783                if (lc_name.EndsWith(wxT(".hdr"))) {
2784                    size = parse_hdr(zs, skipbytes);
2785                    if (ze_data) {
2786                        if (!zs.OpenEntry(*ze_data)) {
2787                            wxMessageBox(wxT("Couldn't read DEM data from .zip file"));
2788                            break;
2789                        }
2790                        read_bil(zs, size, skipbytes);
2791                    }
2792                } else if (lc_name.EndsWith(wxT(".prj"))) {
2793                    //FIXME: check this matches the datum string we use
2794                    //Projection    GEOGRAPHIC
2795                    //Datum         WGS84
2796                    //Zunits        METERS
2797                    //Units         DD
2798                    //Spheroid      WGS84
2799                    //Xshift        0.0000000000
2800                    //Yshift        0.0000000000
2801                    //Parameters
2802                }
2803            }
2804            delete ze;
2805        }
2806        delete ze_data;
2807    }
2808
2809    if (!dem) {
2810        return false;
2811    }
2812
2813    InvalidateList(LIST_TERRAIN);
2814    ForceRefresh();
2815    return true;
2816}
2817
2818void GfxCore::DrawTerrainTriangle(const Vector3 & a, const Vector3 & b, const Vector3 & c)
2819{
2820    Vector3 n = (b - a) * (c - a);
2821    n.normalise();
2822    Double factor = dot(n, light) * .95 + .05;
2823    SetColour(col_WHITE, factor);
2824    PlaceVertex(a);
2825    PlaceVertex(b);
2826    PlaceVertex(c);
2827    ++n_tris;
2828}
2829
2830// Like wxBusyCursor, but you can cancel it early.
2831class AvenBusyCursor {
2832    bool active;
2833
2834  public:
2835    AvenBusyCursor() : active(true) {
2836        wxBeginBusyCursor();
2837    }
2838
2839    void stop() {
2840        if (active) {
2841            active = false;
2842            wxEndBusyCursor();
2843        }
2844    }
2845
2846    ~AvenBusyCursor() {
2847        stop();
2848    }
2849};
2850
2851void GfxCore::DrawTerrain()
2852{
2853    if (!dem) return;
2854
2855    AvenBusyCursor hourglass;
2856
2857    // Draw terrain to twice the extent, or at least 1km.
2858    double r_sqrd = sqrd(max(m_Parent->GetExtent().magnitude(), 1000.0));
2859#define WGS84_DATUM_STRING "+proj=longlat +ellps=WGS84 +datum=WGS84"
2860    static projPJ pj_in = pj_init_plus(WGS84_DATUM_STRING);
2861    if (!pj_in) {
2862        ToggleTerrain();
2863        delete [] dem;
2864        dem = NULL;
2865        hourglass.stop();
2866        error(/*Failed to initialise input coordinate system “%s”*/287, WGS84_DATUM_STRING);
2867        return;
2868    }
2869    static projPJ pj_out = pj_init_plus(m_Parent->GetCSProj().c_str());
2870    if (!pj_out) {
2871        ToggleTerrain();
2872        delete [] dem;
2873        dem = NULL;
2874        hourglass.stop();
2875        error(/*Failed to initialise output coordinate system “%s”*/288, (const char *)m_Parent->GetCSProj().c_str());
2876        return;
2877    }
2878    n_tris = 0;
2879    SetAlpha(0.3);
2880    BeginTriangles();
2881    const Vector3 & off = m_Parent->GetOffset();
2882    vector<Vector3> prevcol(dem_height + 1);
2883    for (size_t x = 0; x < dem_width; ++x) {
2884        double X_ = (o_x + x * step_x) * DEG_TO_RAD;
2885        Vector3 prev;
2886        for (size_t y = 0; y < dem_height; ++y) {
2887            unsigned short elev = dem[x + y * dem_width];
2888#ifdef WORDS_BIGENDIAN
2889            const bool MACHINE_BIGENDIAN = true;
2890#else
2891            const bool MACHINE_BIGENDIAN = false;
2892#endif
2893            if (bigendian != MACHINE_BIGENDIAN) {
2894#if defined __GNUC__ && (__GNUC__ * 100 + __GNUC_MINOR__ >= 408)
2895                elev = __builtin_bswap16(elev);
2896#else
2897                elev = (elev >> 8) | (elev << 8);
2898#endif
2899            }
2900            double Z = (short)elev;
2901            Vector3 pt;
2902            if (Z == nodata_value) {
2903                pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2904            } else {
2905                double X = X_;
2906                double Y = (o_y - y * step_y) * DEG_TO_RAD;
2907                pj_transform(pj_in, pj_out, 1, 1, &X, &Y, &Z);
2908                pt = Vector3(X, Y, Z) - off;
2909                double dist_2 = sqrd(pt.GetX()) + sqrd(pt.GetY());
2910                if (dist_2 > r_sqrd) {
2911                    pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2912                }
2913            }
2914            if (x > 0 && y > 0) {
2915                const Vector3 & a = prevcol[y - 1];
2916                const Vector3 & b = prevcol[y];
2917                // If all points are valid, split the quadrilateral into
2918                // triangles along the shorter 3D diagonal, which typically
2919                // looks better:
2920                //
2921                //               ----->
2922                //     prev---a    x     prev---a
2923                //   |   |P  /|            |\  S|
2924                // y |   |  / |    or      | \  |
2925                //   V   | /  |            |  \ |
2926                //       |/  Q|            |R  \|
2927                //       b----pt           b----pt
2928                //
2929                //       FORWARD           BACKWARD
2930                enum { NONE = 0, P = 1, Q = 2, R = 4, S = 8, ALL = P|Q|R|S };
2931                int valid =
2932                    ((prev.GetZ() != DBL_MAX)) |
2933                    ((a.GetZ() != DBL_MAX) << 1) |
2934                    ((b.GetZ() != DBL_MAX) << 2) |
2935                    ((pt.GetZ() != DBL_MAX) << 3);
2936                static const int tris_map[16] = {
2937                    NONE, // nothing valid
2938                    NONE, // prev
2939                    NONE, // a
2940                    NONE, // a, prev
2941                    NONE, // b
2942                    NONE, // b, prev
2943                    NONE, // b, a
2944                    P, // b, a, prev
2945                    NONE, // pt
2946                    NONE, // pt, prev
2947                    NONE, // pt, a
2948                    S, // pt, a, prev
2949                    NONE, // pt, b
2950                    R, // pt, b, prev
2951                    Q, // pt, b, a
2952                    ALL, // pt, b, a, prev
2953                };
2954                int tris = tris_map[valid];
2955                if (tris == ALL) {
2956                    // All points valid.
2957                    if ((a - b).magnitude() < (prev - pt).magnitude()) {
2958                        tris = P | Q;
2959                    } else {
2960                        tris = R | S;
2961                    }
2962                }
2963                if (tris & P)
2964                    DrawTerrainTriangle(a, prev, b);
2965                if (tris & Q)
2966                    DrawTerrainTriangle(a, b, pt);
2967                if (tris & R)
2968                    DrawTerrainTriangle(pt, prev, b);
2969                if (tris & S)
2970                    DrawTerrainTriangle(a, prev, pt);
2971            }
2972            prev = prevcol[y];
2973            prevcol[y].assign(pt);
2974        }
2975    }
2976    EndTriangles();
2977    SetAlpha(1.0);
2978    if (n_tris == 0) {
2979        ToggleTerrain();
2980        delete [] dem;
2981        dem = NULL;
2982        hourglass.stop();
2983        /* TRANSLATORS: Aven shows a circle of terrain covering the area
2984         * of the survey plus a bit, but the terrain data file didn't
2985         * contain any data inside that circle.
2986         */
2987        error(/*No terrain data near area of survey*/161);
2988    }
2989}
2990
2991// Plot blobs.
2992void GfxCore::GenerateBlobsDisplayList()
2993{
2994    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2995          m_Parent->GetNumHighlightedPts()))
2996        return;
2997
2998    // Plot blobs.
2999    gla_colour prev_col = col_BLACK; // not a colour used for blobs
3000    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
3001    BeginBlobs();
3002    while (pos != m_Parent->GetLabelsEnd()) {
3003        const LabelInfo* label = *pos++;
3004
3005        // When more than one flag is set on a point:
3006        // search results take priority over entrance highlighting
3007        // which takes priority over fixed point
3008        // highlighting, which in turn takes priority over exported
3009        // point highlighting.
3010
3011        if (!((m_Surface && label->IsSurface()) ||
3012              (m_Legs && label->IsUnderground()) ||
3013              (!label->IsSurface() && !label->IsUnderground()))) {
3014            // if this station isn't to be displayed, skip to the next
3015            // (last case is for stns with no legs attached)
3016            continue;
3017        }
3018
3019        gla_colour col;
3020
3021        if (label->IsHighLighted()) {
3022            col = col_YELLOW;
3023        } else if (m_Entrances && label->IsEntrance()) {
3024            col = col_GREEN;
3025        } else if (m_FixedPts && label->IsFixedPt()) {
3026            col = col_RED;
3027        } else if (m_ExportedPts && label->IsExportedPt()) {
3028            col = col_TURQUOISE;
3029        } else {
3030            continue;
3031        }
3032
3033        // Stations are sorted by blob type, so colour changes are infrequent.
3034        if (col != prev_col) {
3035            SetColour(col);
3036            prev_col = col;
3037        }
3038        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
3039    }
3040    EndBlobs();
3041}
3042
3043void GfxCore::DrawIndicators()
3044{
3045    // Draw colour key.
3046    if (m_ColourKey) {
3047        drawing_list key_list = LIST_LIMIT_;
3048        switch (m_ColourBy) {
3049            case COLOUR_BY_DEPTH:
3050                key_list = LIST_DEPTH_KEY; break;
3051            case COLOUR_BY_DATE:
3052                key_list = LIST_DATE_KEY; break;
3053            case COLOUR_BY_ERROR:
3054                key_list = LIST_ERROR_KEY; break;
3055            case COLOUR_BY_GRADIENT:
3056                key_list = LIST_GRADIENT_KEY; break;
3057            case COLOUR_BY_LENGTH:
3058                key_list = LIST_LENGTH_KEY; break;
3059        }
3060        if (key_list != LIST_LIMIT_) {
3061            DrawList2D(key_list, GetXSize() - KEY_OFFSET_X,
3062                       GetYSize() - KEY_OFFSET_Y, 0);
3063        }
3064    }
3065
3066    // Draw compass or elevation/heading indicators.
3067    if (m_Compass || m_Clino) {
3068        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
3069    }
3070
3071    // Draw scalebar.
3072    if (m_Scalebar && !GetPerspective()) {
3073        DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
3074    }
3075}
3076
3077void GfxCore::PlaceVertexWithColour(const Vector3 & v,
3078                                    glaTexCoord tex_x, glaTexCoord tex_y,
3079                                    Double factor)
3080{
3081    SetColour(col_WHITE, factor);
3082    PlaceVertex(v, tex_x, tex_y);
3083}
3084
3085void GfxCore::SetDepthColour(Double z, Double factor) {
3086    // Set the drawing colour based on the altitude.
3087    Double z_ext = m_Parent->GetDepthExtent();
3088
3089    z -= m_Parent->GetDepthMin();
3090    // points arising from tubes may be slightly outside the limits...
3091    if (z < 0) z = 0;
3092    if (z > z_ext) z = z_ext;
3093
3094    if (z == 0) {
3095        SetColour(GetPen(0), factor);
3096        return;
3097    }
3098
3099    assert(z_ext > 0.0);
3100    Double how_far = z / z_ext;
3101    assert(how_far >= 0.0);
3102    assert(how_far <= 1.0);
3103
3104    int band = int(floor(how_far * (GetNumColourBands() - 1)));
3105    GLAPen pen1 = GetPen(band);
3106    if (band < GetNumColourBands() - 1) {
3107        const GLAPen& pen2 = GetPen(band + 1);
3108
3109        Double interval = z_ext / (GetNumColourBands() - 1);
3110        Double into_band = z / interval - band;
3111
3112//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
3113//             z_offset, interval, band);
3114        // FIXME: why do we need to clamp here?  Is it because the walls can
3115        // extend further up/down than the centre-line?
3116        if (into_band < 0.0) into_band = 0.0;
3117        if (into_band > 1.0) into_band = 1.0;
3118        assert(into_band >= 0.0);
3119        assert(into_band <= 1.0);
3120
3121        pen1.Interpolate(pen2, into_band);
3122    }
3123    SetColour(pen1, factor);
3124}
3125
3126void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
3127{
3128    SetDepthColour(v.GetZ(), factor);
3129    PlaceVertex(v);
3130}
3131
3132void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
3133                                         glaTexCoord tex_x, glaTexCoord tex_y,
3134                                         Double factor)
3135{
3136    SetDepthColour(v.GetZ(), factor);
3137    PlaceVertex(v, tex_x, tex_y);
3138}
3139
3140void GfxCore::SplitLineAcrossBands(int band, int band2,
3141                                   const Vector3 &p, const Vector3 &q,
3142                                   Double factor)
3143{
3144    const int step = (band < band2) ? 1 : -1;
3145    for (int i = band; i != band2; i += step) {
3146        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
3147
3148        // Find the intersection point of the line p -> q
3149        // with the plane parallel to the xy-plane with z-axis intersection z.
3150        assert(q.GetZ() - p.GetZ() != 0.0);
3151
3152        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
3153//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
3154
3155        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
3156        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
3157
3158        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
3159    }
3160}
3161
3162void GfxCore::SplitPolyAcrossBands(vector<vector<Split> >& splits,
3163                                   int band, int band2,
3164                                   const Vector3 &p, const Vector3 &q,
3165                                   glaTexCoord ptx, glaTexCoord pty,
3166                                   glaTexCoord w, glaTexCoord h)
3167{
3168    const int step = (band < band2) ? 1 : -1;
3169    for (int i = band; i != band2; i += step) {
3170        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
3171
3172        // Find the intersection point of the line p -> q
3173        // with the plane parallel to the xy-plane with z-axis intersection z.
3174        assert(q.GetZ() - p.GetZ() != 0.0);
3175
3176        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
3177//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
3178
3179        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
3180        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
3181        glaTexCoord tx = ptx, ty = pty;
3182        if (w) tx += t * w;
3183        if (h) ty += t * h;
3184
3185        splits[i].push_back(Split(Vector3(x, y, z), tx, ty));
3186        splits[i + step].push_back(Split(Vector3(x, y, z), tx, ty));
3187    }
3188}
3189
3190int GfxCore::GetDepthColour(Double z) const
3191{
3192    // Return the (0-based) depth colour band index for a z-coordinate.
3193    Double z_ext = m_Parent->GetDepthExtent();
3194    z -= m_Parent->GetDepthMin();
3195    // We seem to get rounding differences causing z to sometimes be slightly
3196    // less than GetDepthMin() here, and it can certainly be true for passage
3197    // tubes, so just clamp the value to 0.
3198    if (z <= 0) return 0;
3199    // We seem to get rounding differences causing z to sometimes exceed z_ext
3200    // by a small amount here (see: https://trac.survex.com/ticket/26) and it
3201    // can certainly be true for passage tubes, so just clamp the value.
3202    if (z >= z_ext) return GetNumColourBands() - 1;
3203    return int(z / z_ext * (GetNumColourBands() - 1));
3204}
3205
3206Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
3207{
3208    // Return the z-coordinate of the depth colour boundary between
3209    // two adjacent depth colour bands (specified by 0-based indices).
3210
3211    assert((a == b - 1) || (a == b + 1));
3212    if (GetNumColourBands() == 1) return 0;
3213
3214    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
3215    Double z_ext = m_Parent->GetDepthExtent();
3216    return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
3217}
3218
3219void GfxCore::AddPolyline(const traverse & centreline)
3220{
3221    BeginPolyline();
3222    SetColour(col_WHITE);
3223    vector<PointInfo>::const_iterator i = centreline.begin();
3224    PlaceVertex(*i);
3225    ++i;
3226    while (i != centreline.end()) {
3227        PlaceVertex(*i);
3228        ++i;
3229    }
3230    EndPolyline();
3231}
3232
3233void GfxCore::AddPolylineShadow(const traverse & centreline)
3234{
3235    BeginPolyline();
3236    const double z = -0.5 * m_Parent->GetExtent().GetZ();
3237    vector<PointInfo>::const_iterator i = centreline.begin();
3238    PlaceVertex(i->GetX(), i->GetY(), z);
3239    ++i;
3240    while (i != centreline.end()) {
3241        PlaceVertex(i->GetX(), i->GetY(), z);
3242        ++i;
3243    }
3244    EndPolyline();
3245}
3246
3247void GfxCore::AddPolylineDepth(const traverse & centreline)
3248{
3249    BeginPolyline();
3250    vector<PointInfo>::const_iterator i, prev_i;
3251    i = centreline.begin();
3252    int band0 = GetDepthColour(i->GetZ());
3253    PlaceVertexWithDepthColour(*i);
3254    prev_i = i;
3255    ++i;
3256    while (i != centreline.end()) {
3257        int band = GetDepthColour(i->GetZ());
3258        if (band != band0) {
3259            SplitLineAcrossBands(band0, band, *prev_i, *i);
3260            band0 = band;
3261        }
3262        PlaceVertexWithDepthColour(*i);
3263        prev_i = i;
3264        ++i;
3265    }
3266    EndPolyline();
3267}
3268
3269void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
3270                               const Vector3 &c, const Vector3 &d)
3271{
3272    Vector3 normal = (a - c) * (d - b);
3273    normal.normalise();
3274    Double factor = dot(normal, light) * .3 + .7;
3275    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3276    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3277    // FIXME: should plot triangles instead to avoid rendering glitches.
3278    BeginQuadrilaterals();
3279    PlaceVertexWithColour(a, 0, 0, factor);
3280    PlaceVertexWithColour(b, w, 0, factor);
3281    PlaceVertexWithColour(c, w, h, factor);
3282    PlaceVertexWithColour(d, 0, h, factor);
3283    EndQuadrilaterals();
3284}
3285
3286void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
3287                                    const Vector3 &c, const Vector3 &d)
3288{
3289    Vector3 normal = (a - c) * (d - b);
3290    normal.normalise();
3291    Double factor = dot(normal, light) * .3 + .7;
3292    int a_band, b_band, c_band, d_band;
3293    a_band = GetDepthColour(a.GetZ());
3294    a_band = min(max(a_band, 0), GetNumColourBands());
3295    b_band = GetDepthColour(b.GetZ());
3296    b_band = min(max(b_band, 0), GetNumColourBands());
3297    c_band = GetDepthColour(c.GetZ());
3298    c_band = min(max(c_band, 0), GetNumColourBands());
3299    d_band = GetDepthColour(d.GetZ());
3300    d_band = min(max(d_band, 0), GetNumColourBands());
3301    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3302    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3303    int min_band = min(min(a_band, b_band), min(c_band, d_band));
3304    int max_band = max(max(a_band, b_band), max(c_band, d_band));
3305    if (min_band == max_band) {
3306        // Simple case - the polygon is entirely within one band.
3307        BeginPolygon();
3308////    PlaceNormal(normal);
3309        PlaceVertexWithDepthColour(a, 0, 0, factor);
3310        PlaceVertexWithDepthColour(b, w, 0, factor);
3311        PlaceVertexWithDepthColour(c, w, h, factor);
3312        PlaceVertexWithDepthColour(d, 0, h, factor);
3313        EndPolygon();
3314    } else {
3315        // We need to make a separate polygon for each depth band...
3316        vector<vector<Split> > splits;
3317        splits.resize(max_band + 1);
3318        splits[a_band].push_back(Split(a, 0, 0));
3319        if (a_band != b_band) {
3320            SplitPolyAcrossBands(splits, a_band, b_band, a, b, 0, 0, w, 0);
3321        }
3322        splits[b_band].push_back(Split(b, w, 0));
3323        if (b_band != c_band) {
3324            SplitPolyAcrossBands(splits, b_band, c_band, b, c, w, 0, 0, h);
3325        }
3326        splits[c_band].push_back(Split(c, w, h));
3327        if (c_band != d_band) {
3328            SplitPolyAcrossBands(splits, c_band, d_band, c, d, w, h, -w, 0);
3329        }
3330        splits[d_band].push_back(Split(d, 0, h));
3331        if (d_band != a_band) {
3332            SplitPolyAcrossBands(splits, d_band, a_band, d, a, 0, h, 0, -h);
3333        }
3334        for (int band = min_band; band <= max_band; ++band) {
3335            BeginPolygon();
3336            for (auto&& item : splits[band]) {
3337                PlaceVertexWithDepthColour(item.vec, item.tx, item.ty, factor);
3338            }
3339            EndPolygon();
3340        }
3341    }
3342}
3343
3344void GfxCore::SetColourFromDate(int date, Double factor)
3345{
3346    // Set the drawing colour based on a date.
3347
3348    if (date == -1) {
3349        // Undated.
3350        SetColour(NODATA_COLOUR, factor);
3351        return;
3352    }
3353
3354    int date_offset = date - m_Parent->GetDateMin();
3355    if (date_offset == 0) {
3356        // Earliest date - handle as a special case for the single date case.
3357        SetColour(GetPen(0), factor);
3358        return;
3359    }
3360
3361    int date_ext = m_Parent->GetDateExtent();
3362    Double how_far = (Double)date_offset / date_ext;
3363    assert(how_far >= 0.0);
3364    assert(how_far <= 1.0);
3365    SetColourFrom01(how_far, factor);
3366}
3367
3368void GfxCore::AddPolylineDate(const traverse & centreline)
3369{
3370    BeginPolyline();
3371    vector<PointInfo>::const_iterator i, prev_i;
3372    i = centreline.begin();
3373    int date = i->GetDate();
3374    SetColourFromDate(date, 1.0);
3375    PlaceVertex(*i);
3376    prev_i = i;
3377    while (++i != centreline.end()) {
3378        int newdate = i->GetDate();
3379        if (newdate != date) {
3380            EndPolyline();
3381            BeginPolyline();
3382            date = newdate;
3383            SetColourFromDate(date, 1.0);
3384            PlaceVertex(*prev_i);
3385        }
3386        PlaceVertex(*i);
3387        prev_i = i;
3388    }
3389    EndPolyline();
3390}
3391
3392static int static_date_hack; // FIXME
3393
3394void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
3395                                   const Vector3 &c, const Vector3 &d)
3396{
3397    Vector3 normal = (a - c) * (d - b);
3398    normal.normalise();
3399    Double factor = dot(normal, light) * .3 + .7;
3400    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3401    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3402    // FIXME: should plot triangles instead to avoid rendering glitches.
3403    BeginQuadrilaterals();
3404////    PlaceNormal(normal);
3405    SetColourFromDate(static_date_hack, factor);
3406    PlaceVertex(a, 0, 0);
3407    PlaceVertex(b, w, 0);
3408    PlaceVertex(c, w, h);
3409    PlaceVertex(d, 0, h);
3410    EndQuadrilaterals();
3411}
3412
3413static double static_E_hack; // FIXME
3414
3415void GfxCore::SetColourFromError(double E, Double factor)
3416{
3417    // Set the drawing colour based on an error value.
3418
3419    if (E < 0) {
3420        SetColour(NODATA_COLOUR, factor);
3421        return;
3422    }
3423
3424    Double how_far = E / MAX_ERROR;
3425    assert(how_far >= 0.0);
3426    if (how_far > 1.0) how_far = 1.0;
3427    SetColourFrom01(how_far, factor);
3428}
3429
3430void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
3431                                    const Vector3 &c, const Vector3 &d)
3432{
3433    Vector3 normal = (a - c) * (d - b);
3434    normal.normalise();
3435    Double factor = dot(normal, light) * .3 + .7;
3436    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3437    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3438    // FIXME: should plot triangles instead to avoid rendering glitches.
3439    BeginQuadrilaterals();
3440////    PlaceNormal(normal);
3441    SetColourFromError(static_E_hack, factor);
3442    PlaceVertex(a, 0, 0);
3443    PlaceVertex(b, w, 0);
3444    PlaceVertex(c, w, h);
3445    PlaceVertex(d, 0, h);
3446    EndQuadrilaterals();
3447}
3448
3449void GfxCore::AddPolylineError(const traverse & centreline)
3450{
3451    BeginPolyline();
3452    SetColourFromError(centreline.E, 1.0);
3453    vector<PointInfo>::const_iterator i;
3454    for(i = centreline.begin(); i != centreline.end(); ++i) {
3455        PlaceVertex(*i);
3456    }
3457    EndPolyline();
3458}
3459
3460// gradient is in *radians*.
3461void GfxCore::SetColourFromGradient(double gradient, Double factor)
3462{
3463    // Set the drawing colour based on the gradient of the leg.
3464
3465    const Double GRADIENT_MAX = M_PI_2;
3466    gradient = fabs(gradient);
3467    Double how_far = gradient / GRADIENT_MAX;
3468    SetColourFrom01(how_far, factor);
3469}
3470
3471void GfxCore::AddPolylineGradient(const traverse & centreline)
3472{
3473    vector<PointInfo>::const_iterator i, prev_i;
3474    i = centreline.begin();
3475    prev_i = i;
3476    while (++i != centreline.end()) {
3477        BeginPolyline();
3478        SetColourFromGradient((*i - *prev_i).gradient(), 1.0);
3479        PlaceVertex(*prev_i);
3480        PlaceVertex(*i);
3481        prev_i = i;
3482        EndPolyline();
3483    }
3484}
3485
3486static double static_gradient_hack; // FIXME
3487
3488void GfxCore::AddQuadrilateralGradient(const Vector3 &a, const Vector3 &b,
3489                                       const Vector3 &c, const Vector3 &d)
3490{
3491    Vector3 normal = (a - c) * (d - b);
3492    normal.normalise();
3493    Double factor = dot(normal, light) * .3 + .7;
3494    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3495    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3496    // FIXME: should plot triangles instead to avoid rendering glitches.
3497    BeginQuadrilaterals();
3498////    PlaceNormal(normal);
3499    SetColourFromGradient(static_gradient_hack, factor);
3500    PlaceVertex(a, 0, 0);
3501    PlaceVertex(b, w, 0);
3502    PlaceVertex(c, w, h);
3503    PlaceVertex(d, 0, h);
3504    EndQuadrilaterals();
3505}
3506
3507void GfxCore::SetColourFromLength(double length, Double factor)
3508{
3509    // Set the drawing colour based on log(length_of_leg).
3510
3511    Double log_len = log10(length);
3512    Double how_far = log_len / LOG_LEN_MAX;
3513    how_far = max(how_far, 0.0);
3514    how_far = min(how_far, 1.0);
3515    SetColourFrom01(how_far, factor);
3516}
3517
3518void GfxCore::SetColourFrom01(double how_far, Double factor)
3519{
3520    double b;
3521    double into_band = modf(how_far * (GetNumColourBands() - 1), &b);
3522    int band(b);
3523    GLAPen pen1 = GetPen(band);
3524    // With 24bit colour, interpolating by less than this can have no effect.
3525    if (into_band >= 1.0 / 512.0) {
3526        const GLAPen& pen2 = GetPen(band + 1);
3527        pen1.Interpolate(pen2, into_band);
3528    }
3529    SetColour(pen1, factor);
3530}
3531
3532void GfxCore::AddPolylineLength(const traverse & centreline)
3533{
3534    vector<PointInfo>::const_iterator i, prev_i;
3535    i = centreline.begin();
3536    prev_i = i;
3537    while (++i != centreline.end()) {
3538        BeginPolyline();
3539        SetColourFromLength((*i - *prev_i).magnitude(), 1.0);
3540        PlaceVertex(*prev_i);
3541        PlaceVertex(*i);
3542        prev_i = i;
3543        EndPolyline();
3544    }
3545}
3546
3547static double static_length_hack; // FIXME
3548
3549void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
3550                                     const Vector3 &c, const Vector3 &d)
3551{
3552    Vector3 normal = (a - c) * (d - b);
3553    normal.normalise();
3554    Double factor = dot(normal, light) * .3 + .7;
3555    glaTexCoord w(((b - a).magnitude() + (d - c).magnitude()) * .5);
3556    glaTexCoord h(((b - c).magnitude() + (d - a).magnitude()) * .5);
3557    // FIXME: should plot triangles instead to avoid rendering glitches.
3558    BeginQuadrilaterals();
3559////    PlaceNormal(normal);
3560    SetColourFromLength(static_length_hack, factor);
3561    PlaceVertex(a, 0, 0);
3562    PlaceVertex(b, w, 0);
3563    PlaceVertex(c, w, h);
3564    PlaceVertex(d, 0, h);
3565    EndQuadrilaterals();
3566}
3567
3568void
3569GfxCore::SkinPassage(vector<XSect> & centreline, bool draw)
3570{
3571    assert(centreline.size() > 1);
3572    Vector3 U[4];
3573    XSect prev_pt_v;
3574    Vector3 last_right(1.0, 0.0, 0.0);
3575
3576//  FIXME: it's not simple to set the colour of a tube based on error...
3577//    static_E_hack = something...
3578    vector<XSect>::iterator i = centreline.begin();
3579    vector<XSect>::size_type segment = 0;
3580    while (i != centreline.end()) {
3581        // get the coordinates of this vertex
3582        XSect & pt_v = *i++;
3583
3584        bool cover_end = false;
3585
3586        Vector3 right, up;
3587
3588        const Vector3 up_v(0.0, 0.0, 1.0);
3589
3590        if (segment == 0) {
3591            assert(i != centreline.end());
3592            // first segment
3593
3594            // get the coordinates of the next vertex
3595            const XSect & next_pt_v = *i;
3596
3597            // calculate vector from this pt to the next one
3598            Vector3 leg_v = next_pt_v - pt_v;
3599
3600            // obtain a vector in the LRUD plane
3601            right = leg_v * up_v;
3602            if (right.magnitude() == 0) {
3603                right = last_right;
3604                // Obtain a second vector in the LRUD plane,
3605                // perpendicular to the first.
3606                //up = right * leg_v;
3607                up = up_v;
3608            } else {
3609                last_right = right;
3610                up = up_v;
3611            }
3612
3613            cover_end = true;
3614            static_date_hack = next_pt_v.GetDate();
3615        } else if (segment + 1 == centreline.size()) {
3616            // last segment
3617
3618            // Calculate vector from the previous pt to this one.
3619            Vector3 leg_v = pt_v - prev_pt_v;
3620
3621            // Obtain a horizontal vector in the LRUD plane.
3622            right = leg_v * up_v;
3623            if (right.magnitude() == 0) {
3624                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
3625                // Obtain a second vector in the LRUD plane,
3626                // perpendicular to the first.
3627                //up = right * leg_v;
3628                up = up_v;
3629            } else {
3630                last_right = right;
3631                up = up_v;
3632            }
3633
3634            cover_end = true;
3635            static_date_hack = pt_v.GetDate();
3636        } else {
3637            assert(i != centreline.end());
3638            // Intermediate segment.
3639
3640            // Get the coordinates of the next vertex.
3641            const XSect & next_pt_v = *i;
3642
3643            // Calculate vectors from this vertex to the
3644            // next vertex, and from the previous vertex to
3645            // this one.
3646            Vector3 leg1_v = pt_v - prev_pt_v;
3647            Vector3 leg2_v = next_pt_v - pt_v;
3648
3649            // Obtain horizontal vectors perpendicular to
3650            // both legs, then normalise and average to get
3651            // a horizontal bisector.
3652            Vector3 r1 = leg1_v * up_v;
3653            Vector3 r2 = leg2_v * up_v;
3654            r1.normalise();
3655            r2.normalise();
3656            right = r1 + r2;
3657            if (right.magnitude() == 0) {
3658                // This is the "mid-pitch" case...
3659                right = last_right;
3660            }
3661            if (r1.magnitude() == 0) {
3662                up = up_v;
3663
3664                // Rotate pitch section to minimise the
3665                // "tortional stress" - FIXME: use
3666                // triangles instead of rectangles?
3667                int shift = 0;
3668                Double maxdotp = 0;
3669
3670                // Scale to unit vectors in the LRUD plane.
3671                right.normalise();
3672                up.normalise();
3673                Vector3 vec = up - right;
3674                for (int orient = 0; orient <= 3; ++orient) {
3675                    Vector3 tmp = U[orient] - prev_pt_v;
3676                    tmp.normalise();
3677                    Double dotp = dot(vec, tmp);
3678                    if (dotp > maxdotp) {
3679                        maxdotp = dotp;
3680                        shift = orient;
3681                    }
3682                }
3683                if (shift) {
3684                    if (shift != 2) {
3685                        Vector3 temp(U[0]);
3686                        U[0] = U[shift];
3687                        U[shift] = U[2];
3688                        U[2] = U[shift ^ 2];
3689                        U[shift ^ 2] = temp;
3690                    } else {
3691                        swap(U[0], U[2]);
3692                        swap(U[1], U[3]);
3693                    }
3694                }
3695#if 0
3696                // Check that the above code actually permuted
3697                // the vertices correctly.
3698                shift = 0;
3699                maxdotp = 0;
3700                for (int j = 0; j <= 3; ++j) {
3701                    Vector3 tmp = U[j] - prev_pt_v;
3702                    tmp.normalise();
3703                    Double dotp = dot(vec, tmp);
3704                    if (dotp > maxdotp) {
3705                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
3706                        shift = j;
3707                    }
3708                }
3709                if (shift) {
3710                    printf("New shift = %d!\n", shift);
3711                    shift = 0;
3712                    maxdotp = 0;
3713                    for (int j = 0; j <= 3; ++j) {
3714                        Vector3 tmp = U[j] - prev_pt_v;
3715                        tmp.normalise();
3716                        Double dotp = dot(vec, tmp);
3717                        printf("    %d : %.8f\n", j, dotp);
3718                    }
3719                }
3720#endif
3721            } else {
3722                up = up_v;
3723            }
3724            last_right = right;
3725            static_date_hack = pt_v.GetDate();
3726        }
3727
3728        // Scale to unit vectors in the LRUD plane.
3729        right.normalise();
3730        up.normalise();
3731
3732        Double l = fabs(pt_v.GetL());
3733        Double r = fabs(pt_v.GetR());
3734        Double u = fabs(pt_v.GetU());
3735        Double d = fabs(pt_v.GetD());
3736
3737        // Produce coordinates of the corners of the LRUD "plane".
3738        Vector3 v[4];
3739        v[0] = pt_v - right * l + up * u;
3740        v[1] = pt_v + right * r + up * u;
3741        v[2] = pt_v + right * r - up * d;
3742        v[3] = pt_v - right * l - up * d;
3743
3744        if (draw) {
3745            const Vector3 & delta = pt_v - prev_pt_v;
3746            static_length_hack = delta.magnitude();
3747            static_gradient_hack = delta.gradient();
3748            if (segment > 0) {
3749                (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3750                (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3751                (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3752                (this->*AddQuad)(v[3], v[0], U[0], U[3]);
3753            }
3754
3755            if (cover_end) {
3756                if (segment == 0) {
3757                    (this->*AddQuad)(v[0], v[1], v[2], v[3]);
3758                } else {
3759                    (this->*AddQuad)(v[3], v[2], v[1], v[0]);
3760                }
3761            }
3762        }
3763
3764        prev_pt_v = pt_v;
3765        U[0] = v[0];
3766        U[1] = v[1];
3767        U[2] = v[2];
3768        U[3] = v[3];
3769
3770        pt_v.set_right_bearing(deg(atan2(right.GetY(), right.GetX())));
3771
3772        ++segment;
3773    }
3774}
3775
3776void GfxCore::FullScreenMode()
3777{
3778    m_Parent->ViewFullScreen();
3779}
3780
3781bool GfxCore::IsFullScreen() const
3782{
3783    return m_Parent->IsFullScreen();
3784}
3785
3786bool GfxCore::FullScreenModeShowingMenus() const
3787{
3788    return m_Parent->FullScreenModeShowingMenus();
3789}
3790
3791void GfxCore::FullScreenModeShowMenus(bool show)
3792{
3793    m_Parent->FullScreenModeShowMenus(show);
3794}
3795
3796void
3797GfxCore::MoveViewer(double forward, double up, double right)
3798{
3799    double cT = cos(rad(m_TiltAngle));
3800    double sT = sin(rad(m_TiltAngle));
3801    double cP = cos(rad(m_PanAngle));
3802    double sP = sin(rad(m_PanAngle));
3803    Vector3 v_forward(cT * sP, cT * cP, sT);
3804    Vector3 v_up(sT * sP, sT * cP, -cT);
3805    Vector3 v_right(-cP, sP, 0);
3806    assert(fabs(dot(v_forward, v_up)) < 1e-6);
3807    assert(fabs(dot(v_forward, v_right)) < 1e-6);
3808    assert(fabs(dot(v_right, v_up)) < 1e-6);
3809    Vector3 move = v_forward * forward + v_up * up + v_right * right;
3810    AddTranslation(-move);
3811    // Show current position.
3812    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
3813    ForceRefresh();
3814}
3815
3816PresentationMark GfxCore::GetView() const
3817{
3818    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
3819                            m_PanAngle, -m_TiltAngle, m_Scale);
3820}
3821
3822void GfxCore::SetView(const PresentationMark & p)
3823{
3824    m_SwitchingTo = 0;
3825    SetTranslation(p - m_Parent->GetOffset());
3826    m_PanAngle = p.angle;
3827    m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
3828    SetRotation(m_PanAngle, m_TiltAngle);
3829    SetScale(p.scale);
3830    ForceRefresh();
3831}
3832
3833void GfxCore::PlayPres(double speed, bool change_speed) {
3834    if (!change_speed || presentation_mode == 0) {
3835        if (speed == 0.0) {
3836            presentation_mode = 0;
3837            return;
3838        }
3839        presentation_mode = PLAYING;
3840        next_mark = m_Parent->GetPresMark(MARK_FIRST);
3841        SetView(next_mark);
3842        next_mark_time = 0; // There already!
3843        this_mark_total = 0;
3844        pres_reverse = (speed < 0);
3845    }
3846
3847    if (change_speed) pres_speed = speed;
3848
3849    if (speed != 0.0) {
3850        bool new_pres_reverse = (speed < 0);
3851        if (new_pres_reverse != pres_reverse) {
3852            pres_reverse = new_pres_reverse;
3853            if (pres_reverse) {
3854                next_mark = m_Parent->GetPresMark(MARK_PREV);
3855            } else {
3856                next_mark = m_Parent->GetPresMark(MARK_NEXT);
3857            }
3858            swap(this_mark_total, next_mark_time);
3859        }
3860    }
3861}
3862
3863void GfxCore::SetColourBy(int colour_by) {
3864    m_ColourBy = colour_by;
3865    switch (colour_by) {
3866        case COLOUR_BY_DEPTH:
3867            AddQuad = &GfxCore::AddQuadrilateralDepth;
3868            AddPoly = &GfxCore::AddPolylineDepth;
3869            break;
3870        case COLOUR_BY_DATE:
3871            AddQuad = &GfxCore::AddQuadrilateralDate;
3872            AddPoly = &GfxCore::AddPolylineDate;
3873            break;
3874        case COLOUR_BY_ERROR:
3875            AddQuad = &GfxCore::AddQuadrilateralError;
3876            AddPoly = &GfxCore::AddPolylineError;
3877            break;
3878        case COLOUR_BY_GRADIENT:
3879            AddQuad = &GfxCore::AddQuadrilateralGradient;
3880            AddPoly = &GfxCore::AddPolylineGradient;
3881            break;
3882        case COLOUR_BY_LENGTH:
3883            AddQuad = &GfxCore::AddQuadrilateralLength;
3884            AddPoly = &GfxCore::AddPolylineLength;
3885            break;
3886        default: // case COLOUR_BY_NONE:
3887            AddQuad = &GfxCore::AddQuadrilateral;
3888            AddPoly = &GfxCore::AddPolyline;
3889            break;
3890    }
3891
3892    InvalidateList(LIST_UNDERGROUND_LEGS);
3893    InvalidateList(LIST_SURFACE_LEGS);
3894    InvalidateList(LIST_TUBES);
3895
3896    ForceRefresh();
3897}
3898
3899bool GfxCore::ExportMovie(const wxString & fnm)
3900{
3901    FILE* fh = wxFopen(fnm.fn_str(), wxT("wb"));
3902    if (fh == NULL) {
3903        wxGetApp().ReportError(wxString::Format(wmsg(/*Failed to open output file “%s”*/47), fnm.c_str()));
3904        return false;
3905    }
3906
3907    wxString ext;
3908    wxFileName::SplitPath(fnm, NULL, NULL, NULL, &ext, wxPATH_NATIVE);
3909
3910    int width;
3911    int height;
3912    GetSize(&width, &height);
3913    // Round up to next multiple of 2 (required by ffmpeg).
3914    width += (width & 1);
3915    height += (height & 1);
3916
3917    movie = new MovieMaker();
3918
3919    // movie takes ownership of fh.
3920    if (!movie->Open(fh, ext.utf8_str(), width, height)) {
3921        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
3922        delete movie;
3923        movie = NULL;
3924        return false;
3925    }
3926
3927    PlayPres(1);
3928    return true;
3929}
3930
3931void
3932GfxCore::OnPrint(const wxString &filename, const wxString &title,
3933                 const wxString &datestamp,
3934                 bool close_after_print)
3935{
3936    svxPrintDlg * p;
3937    p = new svxPrintDlg(m_Parent, filename, title, datestamp,
3938                        m_PanAngle, m_TiltAngle,
3939                        m_Names, m_Crosses, m_Legs, m_Surface, m_Splays,
3940                        m_Tubes, m_Entrances, m_FixedPts, m_ExportedPts,
3941                        true, close_after_print);
3942    p->Show(true);
3943}
3944
3945void
3946GfxCore::OnExport(const wxString &filename, const wxString &title,
3947                  const wxString &datestamp)
3948{
3949    // Fill in "right_bearing" for each cross-section.
3950    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
3951    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
3952    while (trav != tend) {
3953        SkinPassage(*trav, false);
3954        ++trav;
3955    }
3956
3957    svxPrintDlg * p;
3958    p = new svxPrintDlg(m_Parent, filename, title, datestamp,
3959                        m_PanAngle, m_TiltAngle,
3960                        m_Names, m_Crosses, m_Legs, m_Surface, m_Splays,
3961                        m_Tubes, m_Entrances, m_FixedPts, m_ExportedPts,
3962                        false);
3963    p->Show(true);
3964}
3965
3966static wxCursor
3967make_cursor(const unsigned char * bits, const unsigned char * mask,
3968            int hotx, int hoty)
3969{
3970#if defined __WXGTK__ && !defined __WXGTK3__
3971    // Use this code for GTK < 3 only - it doesn't work properly with GTK3
3972    // (reported and should be fixed in wxWidgets 3.0.4 and 3.1.1, see:
3973    // https://trac.wxwidgets.org/ticket/17916)
3974    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
3975                    (const char *)mask, wxBLACK, wxWHITE);
3976#else
3977# ifdef __WXMAC__
3978    // The default Mac cursor is black with a white edge, so
3979    // invert our custom cursors to match.
3980    char b[128];
3981    for (int i = 0; i < 128; ++i)
3982        b[i] = bits[i] ^ 0xff;
3983# else
3984    const char * b = reinterpret_cast<const char *>(bits);
3985# endif
3986    wxBitmap cursor_bitmap(b, 32, 32);
3987    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
3988    cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
3989    wxImage cursor_image = cursor_bitmap.ConvertToImage();
3990    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
3991    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
3992    return wxCursor(cursor_image);
3993#endif
3994}
3995
3996const
3997#include "hand.xbm"
3998const
3999#include "handmask.xbm"
4000
4001const
4002#include "brotate.xbm"
4003const
4004#include "brotatemask.xbm"
4005
4006const
4007#include "vrotate.xbm"
4008const
4009#include "vrotatemask.xbm"
4010
4011const
4012#include "rotate.xbm"
4013const
4014#include "rotatemask.xbm"
4015
4016const
4017#include "rotatezoom.xbm"
4018const
4019#include "rotatezoommask.xbm"
4020
4021void
4022GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
4023{
4024    // Check if we're already showing that cursor.
4025    if (current_cursor == new_cursor) return;
4026
4027    current_cursor = new_cursor;
4028    switch (current_cursor) {
4029        case GfxCore::CURSOR_DEFAULT:
4030            GLACanvas::SetCursor(wxNullCursor);
4031            break;
4032        case GfxCore::CURSOR_POINTING_HAND:
4033            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
4034            break;
4035        case GfxCore::CURSOR_DRAGGING_HAND:
4036            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
4037            break;
4038        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
4039            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
4040            break;
4041        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
4042            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
4043            break;
4044        case GfxCore::CURSOR_ROTATE_VERTICALLY:
4045            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
4046            break;
4047        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
4048            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
4049            break;
4050        case GfxCore::CURSOR_ZOOM:
4051            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
4052            break;
4053        case GfxCore::CURSOR_ZOOM_ROTATE:
4054            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
4055            break;
4056    }
4057}
4058
4059bool GfxCore::MeasuringLineActive() const
4060{
4061    if (Animating()) return false;
4062    return HereIsReal() || m_there;
4063}
4064
4065bool GfxCore::HandleRClick(wxPoint point)
4066{
4067    if (PointWithinCompass(point)) {
4068        // Pop up menu.
4069        wxMenu menu;
4070        /* TRANSLATORS: View *looking* North */
4071        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
4072        /* TRANSLATORS: View *looking* East */
4073        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
4074        /* TRANSLATORS: View *looking* South */
4075        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
4076        /* TRANSLATORS: View *looking* West */
4077        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
4078        menu.AppendSeparator();
4079        /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
4080        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
4081        /* TRANSLATORS: tickable menu item in View menu.
4082         *
4083         * Degrees are the angular measurement where there are 360 in a full
4084         * circle. */
4085        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
4086        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4087        PopupMenu(&menu);
4088        return true;
4089    }
4090
4091    if (PointWithinClino(point)) {
4092        // Pop up menu.
4093        wxMenu menu;
4094        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
4095        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
4096        menu.AppendSeparator();
4097        /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
4098        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
4099        /* TRANSLATORS: tickable menu item in View menu.
4100         *
4101         * Degrees are the angular measurement where there are 360 in a full
4102         * circle. */
4103        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
4104        /* TRANSLATORS: tickable menu item in View menu.
4105         *
4106         * Show the tilt of the survey as a percentage gradient (100% = 45
4107         * degrees = 50 grad). */
4108        menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
4109        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4110        PopupMenu(&menu);
4111        return true;
4112    }
4113
4114    if (PointWithinScaleBar(point)) {
4115        // Pop up menu.
4116        wxMenu menu;
4117        /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
4118        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
4119        /* TRANSLATORS: tickable menu item in View menu.
4120         *
4121         * "Metric" here means metres, km, etc (rather than feet, miles, etc)
4122         */
4123        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
4124        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4125        PopupMenu(&menu);
4126        return true;
4127    }
4128
4129    if (PointWithinColourKey(point)) {
4130        // Pop up menu.
4131        wxMenu menu;
4132        menu.AppendCheckItem(menu_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
4133        menu.AppendCheckItem(menu_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
4134        menu.AppendCheckItem(menu_COLOUR_BY_ERROR, wmsg(/*Colour by &Error*/289));
4135        menu.AppendCheckItem(menu_COLOUR_BY_GRADIENT, wmsg(/*Colour by &Gradient*/85));
4136        menu.AppendCheckItem(menu_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
4137        menu.AppendSeparator();
4138        /* TRANSLATORS: Menu item which turns off the colour key.
4139         * The "Colour Key" is the thing in aven showing which colour
4140         * corresponds to which depth, date, survey closure error, etc. */
4141        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
4142        if (m_ColourBy == COLOUR_BY_DEPTH || m_ColourBy == COLOUR_BY_LENGTH)
4143            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
4144        else if (m_ColourBy == COLOUR_BY_GRADIENT)
4145            menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
4146        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
4147        PopupMenu(&menu);
4148        return true;
4149    }
4150
4151    return false;
4152}
4153
4154void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
4155{
4156    if (centred) {
4157        p1.x = p2.x + (p1.x - p2.x) * 2;
4158        p1.y = p2.y + (p1.y - p2.y) * 2;
4159    }
4160    if (aspect) {
4161#if 0 // FIXME: This needs more work.
4162        int sx = GetXSize();
4163        int sy = GetYSize();
4164        int dx = p1.x - p2.x;
4165        int dy = p1.y - p2.y;
4166        int dy_new = dx * sy / sx;
4167        if (abs(dy_new) >= abs(dy)) {
4168            p1.y += (dy_new - dy) / 2;
4169            p2.y -= (dy_new - dy) / 2;
4170        } else {
4171            int dx_new = dy * sx / sy;
4172            p1.x += (dx_new - dx) / 2;
4173            p2.x -= (dx_new - dx) / 2;
4174        }
4175#endif
4176    }
4177    zoombox.set(p1, p2);
4178    ForceRefresh();
4179}
4180
4181void GfxCore::ZoomBoxGo()
4182{
4183    if (!zoombox.active()) return;
4184
4185    int width = GetXSize();
4186    int height = GetYSize();
4187
4188    TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
4189                  -0.5 * (zoombox.y1 + zoombox.y2 - height));
4190    int box_w = abs(zoombox.x1 - zoombox.x2);
4191    int box_h = abs(zoombox.y1 - zoombox.y2);
4192
4193    double factor = min(double(width) / box_w, double(height) / box_h);
4194
4195    zoombox.unset();
4196
4197    SetScale(GetScale() * factor);
4198}
Note: See TracBrowser for help on using the repository browser.