source: git/src/gfxcore.cc @ 0b8c321

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 0b8c321 was 0b8c321, checked in by Olly Betts <olly@…>, 9 years ago

lib/survex.pot,src/: Add more TRANSLATOR comments.

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