source: git/src/gfxcore.cc @ 0642381

RELEASE/1.2debug-cidebug-ci-sanitiserswalls-data
Last change on this file since 0642381 was 0642381, checked in by Olly Betts <olly@…>, 6 years ago

Highlight surveys on survey tree mouseover

This is cleaner than running a search to highlight them, and means
we can restore "double-click survey in tree to zoom".

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