source: git/src/gfxcore.cc @ 236a1b1

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

Add --stereo option

Supports arguments "buffers" (OpenGL stereo buffers), "anaglyph"
(for use with coloured glasses) and "2up" (suitable for use with
a "cardboard" headset).

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