source: git/src/gfxcore.cc @ 36da3f6

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

Merge branch 'master' into stereo

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