source: git/src/gfxcore.cc @ 36da3f6

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

Merge branch 'master' into stereo

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