source: git/src/gfxcore.cc @ 54fbad8

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

src/gfxcore.cc: Fix printf format/type mismatch.

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