source: git/src/gfxcore.cc @ 7ab01e7

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

Eliminate 3 MainFrm? methods

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