source: git/src/gfxcore.cc @ 68fb07a

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

Add basic "Colour by Survey"

Colours aren't currently controllable.

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