source: git/src/gfxcore.cc @ 672459c

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-datawalls-data-hanging-as-warning
Last change on this file since 672459c was 672459c, checked in by Olly Betts <olly@…>, 6 years ago

Hook up multi-select in survey tree

Filtering works for everthing except exporting.

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