source: git/src/gfxcore.cc @ 47c62d04

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

src/gfxcore.cc: Refactor code to dispatch drawing of the colour key.

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