source: git/src/gfxcore.cc @ 415cbe4

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

Fix defaulting to perspective view

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