source: git/src/gfxcore.cc @ af50685

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

lib/survex.pot,src/: Add "Colour by Length".

  • Property mode set to 100644
File size: 93.5 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        int units = /*m*/424;
1089        if (!m_Metric) {
1090            len /= METRES_PER_FOOT;
1091            units = /*ft*/428;
1092        }
1093        key_legends[band].Printf(wxT("%.2f%s"), len, wmsg(units));
1094    }
1095
1096    DrawColourKey(num_bands, wxString(), wxString());
1097}
1098
[9c37beb]1099void GfxCore::DrawScaleBar()
[5809313]1100{
[84cab34]1101    // Draw the scalebar.
[eef68f9]1102    if (GetPerspective()) return;
[5809313]1103
[37bc1f5]1104    // Calculate how many metres of survey are currently displayed across the
1105    // screen.
[087bc72]1106    Double across_screen = SurveyUnitsAcrossViewport();
[156dc16]1107
[90430f2]1108    double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / GetXSize();
[5f50488]1109    if (f > 0.75) {
1110        f = 0.75;
1111    } else if (f < 0.5) {
1112        // Stop it getting squeezed to nothing.
1113        // FIXME: In this case we should probably move the compass and clino up
1114        // to make room rather than letting stuff overlap.
1115        f = 0.5;
1116    }
1117
[087bc72]1118    // Convert to imperial measurements if required.
[7a89dc2]1119    Double multiplier = 1.0;
1120    if (!m_Metric) {
[429465a]1121        across_screen /= METRES_PER_FOOT;
1122        multiplier = METRES_PER_FOOT;
[5f50488]1123        if (across_screen >= 5280.0 / f) {
[429465a]1124            across_screen /= 5280.0;
1125            multiplier *= 5280.0;
1126        }
[7a89dc2]1127    }
[5757725]1128
[7a89dc2]1129    // Calculate the length of the scale bar.
[5f50488]1130    Double size_snap = pow(10.0, floor(log10(f * across_screen)));
1131    Double t = across_screen * f / size_snap;
[98860c5]1132    if (t >= 5.0) {
[429465a]1133        size_snap *= 5.0;
[7a89dc2]1134    } else if (t >= 2.0) {
[429465a]1135        size_snap *= 2.0;
[98860c5]1136    }
1137
[7a89dc2]1138    if (!m_Metric) size_snap *= multiplier;
1139
[84cab34]1140    // Actual size of the thing in pixels:
[90430f2]1141    int size = int((size_snap / SurveyUnitsAcrossViewport()) * GetXSize());
[e2c1671]1142    m_ScaleBarWidth = size;
[421b7d2]1143
[5809313]1144    // Draw it...
[e2c1671]1145    const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
[5809313]1146    int interval = size / 10;
1147
[aa048c3]1148    gla_colour col = col_WHITE;
[5809313]1149    for (int ix = 0; ix < 10; ix++) {
[e2c1671]1150        int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
[421b7d2]1151
[e2c1671]1152        DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
[421b7d2]1153
[aa048c3]1154        col = (col == col_WHITE) ? col_GREY : col_WHITE;
[5809313]1155    }
1156
[84cab34]1157    // Add labels.
[825bdff]1158    wxString str;
[ccb83b7]1159    int units;
[825bdff]1160    if (m_Metric) {
[ccb83b7]1161        Double km = size_snap * 1e-3;
1162        if (km >= 1.0) {
1163            size_snap = km;
[736f7df]1164            /* TRANSLATORS: abbreviation for "kilometres" (unit of length),
1165             * used e.g.  "5km".
1166             *
1167             * If there should be a space between the number and this, include
1168             * one in the translation. */
[ccb83b7]1169            units = /*km*/423;
[825bdff]1170        } else if (size_snap >= 1.0) {
[736f7df]1171            /* TRANSLATORS: abbreviation for "metres" (unit of length), used
1172             * e.g. "10m".
1173             *
1174             * If there should be a space between the number and this, include
1175             * one in the translation. */
[ccb83b7]1176            units = /*m*/424;
[825bdff]1177        } else {
[ccb83b7]1178            size_snap *= 1e2;
[736f7df]1179            /* TRANSLATORS: abbreviation for "centimetres" (unit of length),
1180             * used e.g.  "50cm".
1181             *
1182             * If there should be a space between the number and this, include
1183             * one in the translation. */
[ccb83b7]1184            units = /*cm*/425;
[825bdff]1185        }
1186    } else {
1187        size_snap /= METRES_PER_FOOT;
1188        Double miles = size_snap / 5280.0;
[ccb83b7]1189        if (miles >= 1.0) {
1190            size_snap = miles;
1191            if (size_snap >= 2.0) {
[736f7df]1192                /* TRANSLATORS: abbreviation for "miles" (unit of length,
1193                 * plural), used e.g.  "2 miles".
1194                 *
1195                 * If there should be a space between the number and this,
1196                 * include one in the translation. */
[ccb83b7]1197                units = /* miles*/426;
[825bdff]1198            } else {
[736f7df]1199                /* TRANSLATORS: abbreviation for "mile" (unit of length,
1200                 * singular), used e.g.  "1 mile".
1201                 *
1202                 * If there should be a space between the number and this,
1203                 * include one in the translation. */
[ccb83b7]1204                units = /* mile*/427;
[825bdff]1205            }
[ccb83b7]1206        } else if (size_snap >= 1.0) {
[736f7df]1207            /* TRANSLATORS: abbreviation for "feet" (unit of length), used e.g.
1208             * as "10ft".
1209             *
1210             * If there should be a space between the number and this, include
1211             * one in the translation. */
[ccb83b7]1212            units = /*ft*/428;
1213        } else {
1214            size_snap *= 12.0;
[736f7df]1215            /* TRANSLATORS: abbreviation for "inches" (unit of length), used
1216             * e.g. as "6in".
1217             *
1218             * If there should be a space between the number and this, include
1219             * one in the translation. */
[ccb83b7]1220            units = /*in*/429;
[825bdff]1221        }
1222    }
[ccb83b7]1223    if (size_snap >= 1.0) {
1224        str.Printf(wxT("%.f%s"), size_snap, wmsg(units).c_str());
1225    } else {
1226        int sf = -(int)floor(log10(size_snap));
1227        str.Printf(wxT("%.*f%s"), sf, size_snap, wmsg(units).c_str());
1228    }
[84cab34]1229
[1eeb55a]1230    int text_width, text_height;
[56da40e]1231    GetTextExtent(str, &text_width, &text_height);
[8bd480e]1232    const int text_y = end_y - text_height + 1;
1233    SetColour(TEXT_COLOUR);
[5627cbb]1234    DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
[8bd480e]1235    DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
[5809313]1236}
[56da40e]1237
[2072157]1238bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
[2effbf1]1239{
[0874c07e]1240    if (Animating()) return false;
1241
[90430f2]1242    if (point.x < 0 || point.x >= GetXSize() ||
1243        point.y < 0 || point.y >= GetYSize()) {
[429465a]1244        return false;
[137e31b]1245    }
[421b7d2]1246
[156f645]1247    SetDataTransform();
[00a68e0]1248
[69463a0]1249    if (!m_HitTestGridValid) CreateHitTestGrid();
[fa42426]1250
[0b0520c]1251    int grid_x = point.x * HITTEST_SIZE / (GetXSize() + 1);
1252    int grid_y = point.y * HITTEST_SIZE / (GetYSize() + 1);
[137e31b]1253
[fa42426]1254    LabelInfo *best = NULL;
[d96c95c]1255    int dist_sqrd = sqrd_measure_threshold;
[2effbf1]1256    int square = grid_x + grid_y * HITTEST_SIZE;
[fa42426]1257    list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
[00a68e0]1258
[fa42426]1259    while (iter != m_PointGrid[square].end()) {
[429465a]1260        LabelInfo *pt = *iter++;
[fa42426]1261
[f6d8375]1262        double cx, cy, cz;
[00a68e0]1263
[d67450e]1264        Transform(*pt, &cx, &cy, &cz);
[00a68e0]1265
[90430f2]1266        cy = GetYSize() - cy;
[00a68e0]1267
[429465a]1268        int dx = point.x - int(cx);
1269        int ds = dx * dx;
1270        if (ds >= dist_sqrd) continue;
1271        int dy = point.y - int(cy);
[fa42426]1272
[429465a]1273        ds += dy * dy;
1274        if (ds >= dist_sqrd) continue;
[f433fda]1275
[429465a]1276        dist_sqrd = ds;
1277        best = pt;
[f433fda]1278
[429465a]1279        if (ds == 0) break;
[2effbf1]1280    }
[f433fda]1281
[fa42426]1282    if (best) {
[381ae6e]1283        m_Parent->ShowInfo(best, m_there);
[429465a]1284        if (centre) {
[e67ed1b]1285            // FIXME: allow Ctrl-Click to not set there or something?
[82c3731]1286            CentreOn(*best);
[90430f2]1287            WarpPointer(GetXSize() / 2, GetYSize() / 2);
[381ae6e]1288            SetThere(best);
[429465a]1289            m_Parent->SelectTreeItem(best);
1290        }
[e67ed1b]1291    } else {
1292        // Left-clicking not on a survey cancels the measuring line.
[0633bcc]1293        if (centre) {
1294            ClearTreeSelection();
1295        } else {
[381ae6e]1296            m_Parent->ShowInfo(best, m_there);
[f6d8375]1297            double x, y, z;
[90430f2]1298            ReverseTransform(point.x, GetYSize() - point.y, &x, &y, &z);
[381ae6e]1299            temp_here.assign(Vector3(x, y, z));
1300            SetHere(&temp_here);
[0633bcc]1301        }
[2effbf1]1302    }
[203d2a7]1303
1304    return best;
[2effbf1]1305}
1306
[5876fcb]1307void GfxCore::OnSize(wxSizeEvent& event)
[5809313]1308{
[5876fcb]1309    // Handle a change in window size.
1310    wxSize size = event.GetSize();
[5809313]1311
[78beaf1]1312    if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
[0580c6a]1313        // Before things are fully initialised, we sometimes get a bogus
1314        // resize message...
[6ef8bd73]1315        // FIXME have changes in MainFrm cured this?  It still happens with
[880b954]1316        // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1317        // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
[78beaf1]1318        // is resized such that the GfxCore window isn't visible.
1319        //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
[0580c6a]1320        return;
1321    }
[b72f4b5]1322
[9071cf5]1323    event.Skip();
[39e460c9]1324
[5876fcb]1325    if (m_DoneFirstShow) {
[81f1266]1326        TryToFreeArrays();
[6ebc0ce]1327
[69463a0]1328        m_HitTestGridValid = false;
[33b2094]1329
[d67450e]1330        ForceRefresh();
[5809313]1331    }
1332}
1333
[de7a879]1334void GfxCore::DefaultParameters()
[5809313]1335{
[33b2094]1336    // Set default viewing parameters.
[b462168]1337
[f433fda]1338    m_Surface = false;
1339    if (!m_Parent->HasUndergroundLegs()) {
1340        if (m_Parent->HasSurfaceLegs()) {
1341            // If there are surface legs, but no underground legs, turn
1342            // surface surveys on.
1343            m_Surface = true;
1344        } else {
1345            // If there are no legs (e.g. after loading a .pos file), turn
1346            // crosses on.
1347            m_Crosses = true;
1348        }
[b462168]1349    }
1350
[714daae]1351    m_PanAngle = 0.0;
[eef68f9]1352    if (m_Parent->IsExtendedElevation()) {
1353        m_TiltAngle = 0.0;
1354    } else {
[7a57dc7]1355        m_TiltAngle = -90.0;
[b462168]1356    }
[714daae]1357
[08253d9]1358    SetRotation(m_PanAngle, m_TiltAngle);
[d67450e]1359    SetTranslation(Vector3());
[33b2094]1360
[e577f89]1361    m_RotationStep = 30.0;
[5809313]1362    m_Rotating = false;
[3d00693]1363    m_SwitchingTo = 0;
[fe444b8]1364    m_Entrances = false;
1365    m_FixedPts = false;
1366    m_ExportedPts = false;
[c1cf79d]1367    m_Grid = false;
[f4c5932]1368    m_BoundingBox = false;
[33b2094]1369    m_Tubes = false;
[1eeb55a]1370    if (GetPerspective()) TogglePerspective();
[de7a879]1371}
[5809313]1372
[de7a879]1373void GfxCore::Defaults()
1374{
1375    // Restore default scale, rotation and translation parameters.
1376    DefaultParameters();
[8b0d57f]1377    SetScale(1.0);
[ba358fc]1378
1379    // Invalidate all the cached lists.
1380    GLACanvas::FirstShow();
1381
[fa42426]1382    ForceRefresh();
[5809313]1383}
[84cab34]1384
[5455bb2]1385void GfxCore::Animate()
[5809313]1386{
[2a3d328]1387    // Don't show pointer coordinates while animating.
[4b031c0]1388    // FIXME : only do this when we *START* animating!  Use a static copy
1389    // of the value of "Animating()" last time we were here to track this?
1390    // MainFrm now checks if we're trying to clear already cleared labels
1391    // and just returns, but it might be simpler to check here!
[2a3d328]1392    ClearCoords();
[381ae6e]1393    m_Parent->ShowInfo();
[5809313]1394
[5455bb2]1395    long t;
[75d4a2b]1396    if (movie) {
[aea4f8b]1397        ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
[98fd937]1398        if (!movie->AddFrame()) {
1399            wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1400            delete movie;
1401            movie = NULL;
1402            presentation_mode = 0;
[5455bb2]1403            return;
[98fd937]1404        }
[5455bb2]1405        t = 1000 / 25; // 25 frames per second
[6a4cdcb6]1406    } else {
[5455bb2]1407        static long t_prev = 0;
1408        t = timer.Time();
1409        // Avoid redrawing twice in the same frame.
[ff1601e]1410        long delta_t = (t_prev == 0 ? 1000 / MAX_FRAMERATE : t - t_prev);
1411        if (delta_t < 1000 / MAX_FRAMERATE)
[6987d2a]1412            return;
[5455bb2]1413        t_prev = t;
[6987d2a]1414        if (presentation_mode == PLAYING && pres_speed != 0.0)
1415            t = delta_t;
[6a4cdcb6]1416    }
[5809313]1417
[128fac4]1418    if (presentation_mode == PLAYING && pres_speed != 0.0) {
[6987d2a]1419        // FIXME: It would probably be better to work relative to the time we
1420        // passed the last mark, but that's complicated by the speed
1421        // potentially changing (or even the direction of playback reversing)
1422        // at any point during playback.
1423        Double tick = t * 0.001 * fabs(pres_speed);
1424        while (tick >= next_mark_time) {
1425            tick -= next_mark_time;
[128fac4]1426            this_mark_total = 0;
[58dfdd21]1427            PresentationMark prev_mark = next_mark;
[e577f89]1428            if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1429            else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
[128fac4]1430            if (pres_reverse)
1431                next_mark = m_Parent->GetPresMark(MARK_PREV);
1432            else
1433                next_mark = m_Parent->GetPresMark(MARK_NEXT);
[1690fa9]1434            if (!next_mark.is_valid()) {
[128fac4]1435                SetView(prev_mark);
[1690fa9]1436                presentation_mode = 0;
[387babf]1437                if (movie && !movie->Close()) {
[98fd937]1438                    wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
1439                }
[81f1266]1440                delete movie;
1441                movie = NULL;
[1690fa9]1442                break;
1443            }
[58dfdd21]1444
[128fac4]1445            double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1446            if (tmp > 0) {
1447                next_mark_time = tmp;
[58dfdd21]1448            } else {
[d67450e]1449                double d = (next_mark - prev_mark).magnitude();
[49ce5b0]1450                // FIXME: should ignore component of d which is unseen in
1451                // non-perspective mode?
[8674eea]1452                next_mark_time = sqrd(d / 30.0);
[49ce5b0]1453                double a = next_mark.angle - prev_mark.angle;
1454                if (a > 180.0) {
1455                    next_mark.angle -= 360.0;
1456                    a = 360.0 - a;
1457                } else if (a < -180.0) {
1458                    next_mark.angle += 360.0;
1459                    a += 360.0;
1460                } else {
1461                    a = fabs(a);
1462                }
1463                next_mark_time += sqrd(a / 60.0);
1464                double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1465                next_mark_time += sqrd(ta / 60.0);
1466                double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
[8674eea]1467                next_mark_time += sqrd(s / 2.0);
[49ce5b0]1468                next_mark_time = sqrt(next_mark_time);
[8674eea]1469                // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
[49ce5b0]1470                //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
[8674eea]1471                //       next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1472                if (tmp < 0) next_mark_time /= -tmp;
[58dfdd21]1473            }
[1690fa9]1474        }
1475
1476        if (presentation_mode) {
1477            // Advance position towards next_mark
[6987d2a]1478            double p = tick / next_mark_time;
[1690fa9]1479            double q = 1 - p;
1480            PresentationMark here = GetView();
[d877aa2]1481            if (next_mark.angle < 0) {
[e577f89]1482                if (here.angle >= next_mark.angle + 360.0)
1483                    here.angle -= 360.0;
1484            } else if (next_mark.angle >= 360.0) {
1485                if (here.angle <= next_mark.angle - 360.0)
1486                    here.angle += 360.0;
[d877aa2]1487            }
[8674eea]1488            here.assign(q * here + p * next_mark);
[1690fa9]1489            here.angle = q * here.angle + p * next_mark.angle;
[e577f89]1490            if (here.angle < 0) here.angle += 360.0;
1491            else if (here.angle >= 360.0) here.angle -= 360.0;
[1690fa9]1492            here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
[58dfdd21]1493            here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
[1690fa9]1494            SetView(here);
[6987d2a]1495            this_mark_total += tick;
1496            next_mark_time -= tick;
[1690fa9]1497        }
[6987d2a]1498
1499        ForceRefresh();
1500        return;
[1690fa9]1501    }
1502
[5876fcb]1503    // When rotating...
1504    if (m_Rotating) {
[5455bb2]1505        Double step = base_pan + (t - base_pan_time) * 1e-3 * m_RotationStep - m_PanAngle;
1506        TurnCave(step);
[5876fcb]1507    }
[5809313]1508
[5876fcb]1509    if (m_SwitchingTo == PLAN) {
[429465a]1510        // When switching to plan view...
[5455bb2]1511        Double step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
1512        TiltCave(step);
[7a57dc7]1513        if (m_TiltAngle == -90.0) {
[429465a]1514            m_SwitchingTo = 0;
1515        }
[1690fa9]1516    } else if (m_SwitchingTo == ELEVATION) {
[429465a]1517        // When switching to elevation view...
[5455bb2]1518        Double step;
1519        if (m_TiltAngle > 0.0) {
1520            step = base_tilt - (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
[7a57dc7]1521        } else {
[5455bb2]1522            step = base_tilt + (t - base_tilt_time) * 1e-3 * 90.0 - m_TiltAngle;
[429465a]1523        }
[5455bb2]1524        if (fabs(step) >= fabs(m_TiltAngle)) {
[3ddd351]1525            m_SwitchingTo = 0;
[5455bb2]1526            step = -m_TiltAngle;
1527        }
1528        TiltCave(step);
1529    } else if (m_SwitchingTo) {
1530        // Rotate the shortest way around to the destination angle.  If we're
1531        // 180 off, we favour turning anticlockwise, as auto-rotation does by
1532        // default.
1533        Double target = (m_SwitchingTo - NORTH) * 90;
1534        Double diff = target - m_PanAngle;
1535        diff = fmod(diff, 360);
1536        if (diff <= -180)
1537            diff += 360;
1538        else if (diff > 180)
1539            diff -= 360;
1540        if (m_RotationStep < 0 && diff == 180.0)
1541            diff = -180.0;
1542        Double step = base_pan - m_PanAngle;
1543        Double delta = (t - base_pan_time) * 1e-3 * fabs(m_RotationStep);
1544        if (diff > 0) {
1545            step += delta;
[3ddd351]1546        } else {
[5455bb2]1547            step -= delta;
[3ddd351]1548        }
[5455bb2]1549        step = fmod(step, 360);
1550        if (step <= -180)
1551            step += 360;
1552        else if (step > 180)
1553            step -= 360;
1554        if (fabs(step) >= fabs(diff)) {
1555            m_SwitchingTo = 0;
1556            step = diff;
1557        }
1558        TurnCave(step);
[5876fcb]1559    }
[5809313]1560
[5455bb2]1561    ForceRefresh();
[5809313]1562}
[84cab34]1563
[0580c6a]1564// How much to allow around the box - this is because of the ring shape
1565// at one end of the line.
1566static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1567#define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
[381ae6e]1568void GfxCore::RefreshLine(const Point *a, const Point *b, const Point *c)
[7a89dc2]1569{
[0f86024]1570#ifdef __WXMSW__
1571    (void)a;
1572    (void)b;
1573    (void)c;
1574    // FIXME: We get odd redraw artifacts if we just update the line, and
1575    // redrawing the whole scene doesn't actually seem to be measurably
1576    // slower.  That may not be true with software rendering though...
1577    ForceRefresh();
1578#else
[06d367d]1579    // Best of all might be to copy the window contents before we draw the
1580    // line, then replace each time we redraw.
[796d7bf]1581
[5876fcb]1582    // Calculate the minimum rectangle which includes the old and new
1583    // measuring lines to minimise the redraw time
1584    int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
[f6d8375]1585    double X, Y, Z;
[381ae6e]1586    if (a) {
1587        if (!Transform(*a, &X, &Y, &Z)) {
[796d7bf]1588            printf("oops\n");
1589        } else {
1590            int x = int(X);
[90430f2]1591            int y = GetYSize() - 1 - int(Y);
[1c448e1]1592            l = x;
1593            r = x;
1594            u = y;
1595            d = y;
[796d7bf]1596        }
[5876fcb]1597    }
[381ae6e]1598    if (b) {
1599        if (!Transform(*b, &X, &Y, &Z)) {
[796d7bf]1600            printf("oops\n");
1601        } else {
1602            int x = int(X);
[90430f2]1603            int y = GetYSize() - 1 - int(Y);
[1c448e1]1604            l = min(l, x);
1605            r = max(r, x);
1606            u = max(u, y);
1607            d = min(d, y);
[796d7bf]1608        }
[5876fcb]1609    }
[381ae6e]1610    if (c) {
1611        if (!Transform(*c, &X, &Y, &Z)) {
[796d7bf]1612            printf("oops\n");
1613        } else {
1614            int x = int(X);
[90430f2]1615            int y = GetYSize() - 1 - int(Y);
[1c448e1]1616            l = min(l, x);
1617            r = max(r, x);
1618            u = max(u, y);
1619            d = min(d, y);
[796d7bf]1620        }
[5876fcb]1621    }
[1c448e1]1622    l -= MARGIN;
1623    r += MARGIN;
1624    u += MARGIN;
1625    d -= MARGIN;
[0ca8fe0]1626    RefreshRect(wxRect(l, d, r - l, u - d), false);
[0f86024]1627#endif
[7a89dc2]1628}
1629
[381ae6e]1630void GfxCore::SetHereFromTree(const LabelInfo * p)
1631{
1632    SetHere(p);
1633    m_Parent->ShowInfo(m_here, m_there);
1634}
1635
[5876fcb]1636void GfxCore::SetHere()
[7a89dc2]1637{
[381ae6e]1638    if (!m_here) return;
[6b061db]1639    bool line_active = MeasuringLineActive();
[381ae6e]1640    const LabelInfo * old = m_here;
1641    m_here = NULL;
[6b061db]1642    if (line_active || MeasuringLineActive())
1643        RefreshLine(old, m_there, m_here);
[7a89dc2]1644}
1645
[381ae6e]1646void GfxCore::SetHere(const LabelInfo *p)
[c6d95d8]1647{
[6b061db]1648    bool line_active = MeasuringLineActive();
[381ae6e]1649    const LabelInfo * old = m_here;
[82c3731]1650    m_here = p;
[6b061db]1651    if (line_active || MeasuringLineActive())
1652        RefreshLine(old, m_there, m_here);
[156dc16]1653}
1654
[5876fcb]1655void GfxCore::SetThere()
[156dc16]1656{
[381ae6e]1657    if (!m_there) return;
1658    const LabelInfo * old = m_there;
1659    m_there = NULL;
[0580c6a]1660    RefreshLine(m_here, old, m_there);
[156dc16]1661}
1662
[381ae6e]1663void GfxCore::SetThere(const LabelInfo * p)
[156dc16]1664{
[381ae6e]1665    const LabelInfo * old = m_there;
[82c3731]1666    m_there = p;
[0580c6a]1667    RefreshLine(m_here, old, m_there);
[156dc16]1668}
1669
[5876fcb]1670void GfxCore::CreateHitTestGrid()
[156dc16]1671{
[7171240]1672    if (!m_PointGrid) {
1673        // Initialise hit-test grid.
1674        m_PointGrid = new list<LabelInfo*>[HITTEST_SIZE * HITTEST_SIZE];
1675    } else {
1676        // Clear hit-test grid.
1677        for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
1678            m_PointGrid[i].clear();
1679        }
[5876fcb]1680    }
[156dc16]1681
[5876fcb]1682    // Fill the grid.
1683    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1684    list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1685    while (pos != end) {
[429465a]1686        LabelInfo* label = *pos++;
[33b2094]1687
[429465a]1688        if (!((m_Surface && label->IsSurface()) ||
[dc42b8e]1689              (m_Legs && label->IsUnderground()) ||
1690              (!label->IsSurface() && !label->IsUnderground()))) {
1691            // if this station isn't to be displayed, skip to the next
1692            // (last case is for stns with no legs attached)
[429465a]1693            continue;
1694        }
[33b2094]1695
[429465a]1696        // Calculate screen coordinates.
[f6d8375]1697        double cx, cy, cz;
[d67450e]1698        Transform(*label, &cx, &cy, &cz);
[90430f2]1699        if (cx < 0 || cx >= GetXSize()) continue;
1700        if (cy < 0 || cy >= GetYSize()) continue;
[33b2094]1701
[90430f2]1702        cy = GetYSize() - cy;
[00a68e0]1703
[429465a]1704        // On-screen, so add to hit-test grid...
[0b0520c]1705        int grid_x = int(cx * HITTEST_SIZE / (GetXSize() + 1));
1706        int grid_y = int(cy * HITTEST_SIZE / (GetYSize() + 1));
[33b2094]1707
[429465a]1708        m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
[33b2094]1709    }
1710
[00a68e0]1711    m_HitTestGridValid = true;
[33b2094]1712}
[c6d95d8]1713
[2a02de2]1714//
[5876fcb]1715//  Methods for controlling the orientation of the survey
[2a02de2]1716//
1717
[5876fcb]1718void GfxCore::TurnCave(Double angle)
[156dc16]1719{
[5876fcb]1720    // Turn the cave around its z-axis by a given angle.
[156dc16]1721
[5876fcb]1722    m_PanAngle += angle;
[5a7597a]1723    // Wrap to range [0, 360):
1724    m_PanAngle = fmod(m_PanAngle, 360.0);
1725    if (m_PanAngle < 0.0) {
[e577f89]1726        m_PanAngle += 360.0;
[156dc16]1727    }
[33b2094]1728
[00a68e0]1729    m_HitTestGridValid = false;
[381ae6e]1730    if (m_here && m_here == &temp_here) SetHere();
[00a68e0]1731
[08253d9]1732    SetRotation(m_PanAngle, m_TiltAngle);
[156dc16]1733}
1734
[5876fcb]1735void GfxCore::TurnCaveTo(Double angle)
[d80805e]1736{
[5455bb2]1737    if (m_Rotating) {
1738        // If we're rotating, jump to the specified angle.
1739        TurnCave(angle - m_PanAngle);
1740        SetPanBase();
1741        return;
1742    }
1743
[3ddd351]1744    int new_switching_to = ((int)angle) / 90 + NORTH;
1745    if (new_switching_to == m_SwitchingTo) {
1746        // A second order to switch takes us there right away
1747        TurnCave(angle - m_PanAngle);
1748        m_SwitchingTo = 0;
1749        ForceRefresh();
1750    } else {
[5455bb2]1751        SetPanBase();
[3ddd351]1752        m_SwitchingTo = new_switching_to;
1753    }
[d80805e]1754}
1755
[5876fcb]1756void GfxCore::TiltCave(Double tilt_angle)
[156dc16]1757{
[5876fcb]1758    // Tilt the cave by a given angle.
[e577f89]1759    if (m_TiltAngle + tilt_angle > 90.0) {
[08253d9]1760        m_TiltAngle = 90.0;
[e577f89]1761    } else if (m_TiltAngle + tilt_angle < -90.0) {
[08253d9]1762        m_TiltAngle = -90.0;
1763    } else {
1764        m_TiltAngle += tilt_angle;
[d80805e]1765    }
1766
[00a68e0]1767    m_HitTestGridValid = false;
[381ae6e]1768    if (m_here && m_here == &temp_here) SetHere();
[00a68e0]1769
[08253d9]1770    SetRotation(m_PanAngle, m_TiltAngle);
[5ffa439]1771}
1772
[5876fcb]1773void GfxCore::TranslateCave(int dx, int dy)
[5ffa439]1774{
[33b2094]1775    AddTranslationScreenCoordinates(dx, dy);
[00a68e0]1776    m_HitTestGridValid = false;
1777
[381ae6e]1778    if (m_here && m_here == &temp_here) SetHere();
[c00c6713]1779
[33b2094]1780    ForceRefresh();
1781}
[5876fcb]1782
[33b2094]1783void GfxCore::DragFinished()
1784{
[76dd228]1785    m_MouseOutsideCompass = m_MouseOutsideElev = false;
[5876fcb]1786    ForceRefresh();
[2173dbd]1787}
1788
[d877aa2]1789void GfxCore::ClearCoords()
1790{
1791    m_Parent->ClearCoords();
1792}
1793
[5876fcb]1794void GfxCore::SetCoords(wxPoint point)
[fd6e0d5]1795{
[0874c07e]1796    // We can't work out 2D coordinates from a perspective view, and it
1797    // doesn't really make sense to show coordinates while we're animating.
1798    if (GetPerspective() || Animating()) return;
[0a811ab]1799
[5876fcb]1800    // Update the coordinate or altitude display, given the (x, y) position in
1801    // window coordinates.  The relevant display is updated depending on
1802    // whether we're in plan or elevation view.
1803
[f6d8375]1804    double cx, cy, cz;
[5876fcb]1805
[a2b3d62]1806    SetDataTransform();
[90430f2]1807    ReverseTransform(point.x, GetYSize() - 1 - point.y, &cx, &cy, &cz);
[5876fcb]1808
[0633bcc]1809    if (ShowingPlan()) {
[d67450e]1810        m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
[381ae6e]1811                            cy + m_Parent->GetOffset().GetY(),
1812                            m_there);
[0633bcc]1813    } else if (ShowingElevation()) {
[381ae6e]1814        m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ(),
1815                              m_there);
[d479c15]1816    } else {
[429465a]1817        m_Parent->ClearCoords();
[a2b3d62]1818    }
[fd6e0d5]1819}
1820
[1eeb55a]1821int GfxCore::GetCompassXPosition() const
[1fd2edb]1822{
[f433fda]1823    // Return the x-coordinate of the centre of the compass in window
1824    // coordinates.
[90430f2]1825    return GetXSize() - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE / 2;
[1fd2edb]1826}
1827
[1eeb55a]1828int GfxCore::GetClinoXPosition() const
[1fd2edb]1829{
[f433fda]1830    // Return the x-coordinate of the centre of the compass in window
1831    // coordinates.
[90430f2]1832    return GetXSize() - GetClinoOffset() - INDICATOR_BOX_SIZE / 2;
[1fd2edb]1833}
1834
[1eeb55a]1835int GfxCore::GetIndicatorYPosition() const
[dfe4454c]1836{
[f433fda]1837    // Return the y-coordinate of the centre of the indicators in window
1838    // coordinates.
[90430f2]1839    return GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
[5876fcb]1840}
[fa42426]1841
[1eeb55a]1842int GfxCore::GetIndicatorRadius() const
[5876fcb]1843{
1844    // Return the radius of each indicator.
[1eeb55a]1845    return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
[5876fcb]1846}
[dfe4454c]1847
[14acdae]1848bool GfxCore::PointWithinCompass(wxPoint point) const
[5876fcb]1849{
[f433fda]1850    // Determine whether a point (in window coordinates) lies within the
1851    // compass.
[e2c1671]1852    if (!ShowingCompass()) return false;
1853
[33b2094]1854    glaCoord dx = point.x - GetCompassXPosition();
1855    glaCoord dy = point.y - GetIndicatorYPosition();
1856    glaCoord radius = GetIndicatorRadius();
[f433fda]1857
[5876fcb]1858    return (dx * dx + dy * dy <= radius * radius);
1859}
[fa42426]1860
[14acdae]1861bool GfxCore::PointWithinClino(wxPoint point) const
[5876fcb]1862{
1863    // Determine whether a point (in window coordinates) lies within the clino.
[e2c1671]1864    if (!ShowingClino()) return false;
1865
[33b2094]1866    glaCoord dx = point.x - GetClinoXPosition();
1867    glaCoord dy = point.y - GetIndicatorYPosition();
1868    glaCoord radius = GetIndicatorRadius();
[f433fda]1869
[5876fcb]1870    return (dx * dx + dy * dy <= radius * radius);
[dfe4454c]1871}
[8000d8f]1872
[14acdae]1873bool GfxCore::PointWithinScaleBar(wxPoint point) const
[5876fcb]1874{
[e2c1671]1875    // Determine whether a point (in window coordinates) lies within the scale
1876    // bar.
1877    if (!ShowingScaleBar()) return false;
[8000d8f]1878
[e2c1671]1879    return (point.x >= SCALE_BAR_OFFSET_X &&
1880            point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
[90430f2]1881            point.y <= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
1882            point.y >= GetYSize() - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
[5876fcb]1883}
[8000d8f]1884
[d43fa84]1885bool GfxCore::PointWithinColourKey(wxPoint point) const
1886{
1887    // Determine whether a point (in window coordinates) lies within the key.
[62da267]1888    point.x -= GetXSize() - KEY_OFFSET_X;
1889    point.y = KEY_OFFSET_Y - point.y;
[fcc3741]1890    return (point.x >= key_lowerleft[m_ColourBy].x && point.x <= 0 &&
1891            point.y >= key_lowerleft[m_ColourBy].y && point.y <= 0);
[d43fa84]1892}
1893
[5876fcb]1894void GfxCore::SetCompassFromPoint(wxPoint point)
[8000d8f]1895{
[d877aa2]1896    // Given a point in window coordinates, set the heading of the survey.  If
1897    // the point is outside the compass, it snaps to 45 degree intervals;
1898    // otherwise it operates as normal.
[8000d8f]1899
[5876fcb]1900    wxCoord dx = point.x - GetCompassXPosition();
1901    wxCoord dy = point.y - GetIndicatorYPosition();
1902    wxCoord radius = GetIndicatorRadius();
[7aa15c0]1903
[0580c6a]1904    double angle = deg(atan2(double(dx), double(dy))) - 180.0;
[5876fcb]1905    if (dx * dx + dy * dy <= radius * radius) {
[3ddd351]1906        TurnCave(angle - m_PanAngle);
[429465a]1907        m_MouseOutsideCompass = false;
[e577f89]1908    } else {
[3ddd351]1909        TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
[429465a]1910        m_MouseOutsideCompass = true;
[7aa15c0]1911    }
[8000d8f]1912
[5876fcb]1913    ForceRefresh();
1914}
1915
1916void GfxCore::SetClinoFromPoint(wxPoint point)
1917{
[d877aa2]1918    // Given a point in window coordinates, set the elevation of the survey.
1919    // If the point is outside the clino, it snaps to 90 degree intervals;
1920    // otherwise it operates as normal.
[8000d8f]1921
[33b2094]1922    glaCoord dx = point.x - GetClinoXPosition();
1923    glaCoord dy = point.y - GetIndicatorYPosition();
1924    glaCoord radius = GetIndicatorRadius();
[f433fda]1925
[5876fcb]1926    if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
[7a57dc7]1927        TiltCave(-deg(atan2(double(dy), double(dx))) - m_TiltAngle);
[429465a]1928        m_MouseOutsideElev = false;
[e577f89]1929    } else if (dy >= INDICATOR_MARGIN) {
[7a57dc7]1930        TiltCave(-90.0 - m_TiltAngle);
[429465a]1931        m_MouseOutsideElev = true;
[e577f89]1932    } else if (dy <= -INDICATOR_MARGIN) {
[7a57dc7]1933        TiltCave(90.0 - m_TiltAngle);
[429465a]1934        m_MouseOutsideElev = true;
[e577f89]1935    } else {
[429465a]1936        TiltCave(-m_TiltAngle);
1937        m_MouseOutsideElev = true;
[5876fcb]1938    }
[8000d8f]1939
[5876fcb]1940    ForceRefresh();
[8000d8f]1941}
1942
[5876fcb]1943void GfxCore::SetScaleBarFromOffset(wxCoord dx)
[8000d8f]1944{
[5876fcb]1945    // Set the scale of the survey, given an offset as to how much the mouse has
1946    // been dragged over the scalebar since the last scale change.
[8000d8f]1947
[5b7164d]1948    SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
[5876fcb]1949    ForceRefresh();
1950}
[8000d8f]1951
[5876fcb]1952void GfxCore::RedrawIndicators()
1953{
1954    // Redraw the compass and clino indicators.
[8000d8f]1955
[e24b7fb]1956    RefreshRect(wxRect(GetXSize() - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE*2 -
1957                       INDICATOR_GAP,
1958                       GetYSize() - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
1959                       INDICATOR_BOX_SIZE*2 + INDICATOR_GAP,
1960                       INDICATOR_BOX_SIZE), false);
[8000d8f]1961}
1962
[5876fcb]1963void GfxCore::StartRotation()
[8000d8f]1964{
[5876fcb]1965    // Start the survey rotating.
[f433fda]1966
[5455bb2]1967    if (m_SwitchingTo >= NORTH)
1968        m_SwitchingTo = 0;
[5876fcb]1969    m_Rotating = true;
[5455bb2]1970    SetPanBase();
[5876fcb]1971}
[8000d8f]1972
[5876fcb]1973void GfxCore::ToggleRotation()
1974{
1975    // Toggle the survey rotation on/off.
[f433fda]1976
[5876fcb]1977    if (m_Rotating) {
[2a3d328]1978        StopRotation();
1979    } else {
1980        StartRotation();
[5876fcb]1981    }
1982}
[8000d8f]1983
[5876fcb]1984void GfxCore::StopRotation()
1985{
1986    // Stop the survey rotating.
[8000d8f]1987
[5876fcb]1988    m_Rotating = false;
[33b2094]1989    ForceRefresh();
[5876fcb]1990}
[8000d8f]1991
[eef68f9]1992bool GfxCore::IsExtendedElevation() const
[5876fcb]1993{
[eef68f9]1994    return m_Parent->IsExtendedElevation();
[5876fcb]1995}
[8000d8f]1996
[5876fcb]1997void GfxCore::ReverseRotation()
1998{
1999    // Reverse the direction of rotation.
[8000d8f]2000
[5876fcb]2001    m_RotationStep = -m_RotationStep;
[5455bb2]2002    if (m_Rotating)
2003        SetPanBase();
[5876fcb]2004}
[8000d8f]2005
[5876fcb]2006void GfxCore::RotateSlower(bool accel)
2007{
2008    // Decrease the speed of rotation, optionally by an increased amount.
[5455bb2]2009    if (fabs(m_RotationStep) == 1.0)
2010        return;
[8000d8f]2011
[5455bb2]2012    m_RotationStep *= accel ? (1 / 1.44) : (1 / 1.2);
2013
2014    if (fabs(m_RotationStep) < 1.0) {
2015        m_RotationStep = (m_RotationStep > 0 ? 1.0 : -1.0);
[1690fa9]2016    }
[5455bb2]2017    if (m_Rotating)
2018        SetPanBase();
[8000d8f]2019}
2020
[5876fcb]2021void GfxCore::RotateFaster(bool accel)
2022{
2023    // Increase the speed of rotation, optionally by an increased amount.
[5455bb2]2024    if (fabs(m_RotationStep) == 180.0)
2025        return;
[5876fcb]2026
2027    m_RotationStep *= accel ? 1.44 : 1.2;
[5455bb2]2028    if (fabs(m_RotationStep) > 180.0) {
2029        m_RotationStep = (m_RotationStep > 0 ? 180.0 : -180.0);
[1690fa9]2030    }
[5455bb2]2031    if (m_Rotating)
2032        SetPanBase();
[5876fcb]2033}
[8000d8f]2034
[5876fcb]2035void GfxCore::SwitchToElevation()
[8000d8f]2036{
[5876fcb]2037    // Perform an animated switch to elevation view.
[8000d8f]2038
[5455bb2]2039    if (m_SwitchingTo != ELEVATION) {
2040        SetTiltBase();
2041        m_SwitchingTo = ELEVATION;
2042    } else {
2043        // A second order to switch takes us there right away
2044        TiltCave(-m_TiltAngle);
2045        m_SwitchingTo = 0;
2046        ForceRefresh();
[5876fcb]2047    }
[8000d8f]2048}
2049
[5876fcb]2050void GfxCore::SwitchToPlan()
[8000d8f]2051{
[5876fcb]2052    // Perform an animated switch to plan view.
[8000d8f]2053
[5455bb2]2054    if (m_SwitchingTo != PLAN) {
2055        SetTiltBase();
2056        m_SwitchingTo = PLAN;
2057    } else {
2058        // A second order to switch takes us there right away
2059        TiltCave(-90.0 - m_TiltAngle);
2060        m_SwitchingTo = 0;
2061        ForceRefresh();
[8000d8f]2062    }
[5876fcb]2063}
[8000d8f]2064
[d1628e8e]2065void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
2066{
2067
2068    SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
[d0f5918]2069    Double scale = HUGE_VAL;
[d1628e8e]2070    const Vector3 ext = m_Parent->GetExtent();
2071    if (xmax > xmin) {
2072        Double s = ext.GetX() / (xmax - xmin);
2073        if (s < scale) scale = s;
2074    }
2075    if (ymax > ymin) {
2076        Double s = ext.GetY() / (ymax - ymin);
2077        if (s < scale) scale = s;
2078    }
2079    if (!ShowingPlan() && zmax > zmin) {
2080        Double s = ext.GetZ() / (zmax - zmin);
2081        if (s < scale) scale = s;
2082    }
[d0f5918]2083    if (scale != HUGE_VAL) SetScale(scale);
[d1628e8e]2084    ForceRefresh();
2085}
2086
[14acdae]2087bool GfxCore::CanRaiseViewpoint() const
[5876fcb]2088{
2089    // Determine if the survey can be viewed from a higher angle of elevation.
[f433fda]2090
[7a57dc7]2091    return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
[8000d8f]2092}
2093
[14acdae]2094bool GfxCore::CanLowerViewpoint() const
[2effbf1]2095{
[5876fcb]2096    // Determine if the survey can be viewed from a lower angle of elevation.
[2effbf1]2097
[7a57dc7]2098    return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
[5876fcb]2099}
[2effbf1]2100
[78c67a6]2101bool GfxCore::HasDepth() const
[bd21214]2102{
[78c67a6]2103    return m_Parent->GetDepthExtent() == 0.0;
[bd21214]2104}
2105
[843ee7b]2106bool GfxCore::HasErrorInformation() const
[d4650b3]2107{
[843ee7b]2108    return m_Parent->HasErrorInformation();
[d4650b3]2109}
2110
[843ee7b]2111bool GfxCore::HasDateInformation() const
[c61aa79]2112{
[843ee7b]2113    return m_Parent->GetDateMin() >= 0;
[c61aa79]2114}
2115
[14acdae]2116bool GfxCore::ShowingPlan() const
[5876fcb]2117{
2118    // Determine if the survey is in plan view.
[f433fda]2119
[7a57dc7]2120    return (m_TiltAngle == -90.0);
[2effbf1]2121}
2122
[14acdae]2123bool GfxCore::ShowingElevation() const
[8000d8f]2124{
[5876fcb]2125    // Determine if the survey is in elevation view.
[f433fda]2126
[5876fcb]2127    return (m_TiltAngle == 0.0);
[8000d8f]2128}
2129
[14acdae]2130bool GfxCore::ShowingMeasuringLine() const
[8000d8f]2131{
[0afefe6]2132    // Determine if the measuring line is being shown.  Only check if "there"
2133    // is valid, since that means the measuring line anchor is out.
[f433fda]2134
[381ae6e]2135    return m_there;
[8000d8f]2136}
2137
[eff44b9]2138void GfxCore::ToggleFlag(bool* flag, int update)
[5876fcb]2139{
2140    *flag = !*flag;
[6747314]2141    if (update == UPDATE_BLOBS) {
[eff44b9]2142        UpdateBlobs();
[ef1870d]2143    } else if (update == UPDATE_BLOBS_AND_CROSSES) {
2144        UpdateBlobs();
2145        InvalidateList(LIST_CROSSES);
[de43be7]2146        m_HitTestGridValid = false;
[6cd6bbe]2147    }
[eff44b9]2148    ForceRefresh();
[5876fcb]2149}
[93744a5]2150
[14acdae]2151int GfxCore::GetNumEntrances() const
[4b1fc48]2152{
[5876fcb]2153    return m_Parent->GetNumEntrances();
2154}
[bd7a61b]2155
[14acdae]2156int GfxCore::GetNumFixedPts() const
[5876fcb]2157{
2158    return m_Parent->GetNumFixedPts();
2159}
[7757a4ed]2160
[14acdae]2161int GfxCore::GetNumExportedPts() const
[5876fcb]2162{
2163    return m_Parent->GetNumExportedPts();
2164}
2165
[d96c95c]2166void GfxCore::ToggleFatFinger()
2167{
2168    if (sqrd_measure_threshold == sqrd(MEASURE_THRESHOLD)) {
2169        sqrd_measure_threshold = sqrd(5 * MEASURE_THRESHOLD);
[7b9b700]2170        wxMessageBox(wxT("Fat finger enabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
[d96c95c]2171    } else {
2172        sqrd_measure_threshold = sqrd(MEASURE_THRESHOLD);
[7b9b700]2173        wxMessageBox(wxT("Fat finger disabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
[d96c95c]2174    }
2175}
2176
[5876fcb]2177void GfxCore::ClearTreeSelection()
2178{
2179    m_Parent->ClearTreeSelection();
2180}
2181
[82c3731]2182void GfxCore::CentreOn(const Point &p)
[5876fcb]2183{
[d67450e]2184    SetTranslation(-p);
[00a68e0]2185    m_HitTestGridValid = false;
[f433fda]2186
[5876fcb]2187    ForceRefresh();
[4b1fc48]2188}
[5876fcb]2189
[33b2094]2190void GfxCore::ForceRefresh()
2191{
2192    Refresh(false);
2193}
2194
[d2fcc9b]2195void GfxCore::GenerateList(unsigned int l)
[33b2094]2196{
[9eb58d0]2197    assert(m_HaveData);
[3ddcad8]2198
[d2fcc9b]2199    switch (l) {
[fe665c4]2200        case LIST_COMPASS:
2201            DrawCompass();
2202            break;
2203        case LIST_CLINO:
2204            DrawClino();
2205            break;
2206        case LIST_CLINO_BACK:
2207            DrawClinoBack();
2208            break;
[9c37beb]2209        case LIST_SCALE_BAR:
2210            DrawScaleBar();
2211            break;
[e2ea75a]2212        case LIST_DEPTH_KEY:
2213            DrawDepthKey();
[252d759]2214            break;
[e2ea75a]2215        case LIST_DATE_KEY:
2216            DrawDateKey();
[d4650b3]2217            break;
[e2ea75a]2218        case LIST_ERROR_KEY:
2219            DrawErrorKey();
[c61aa79]2220            break;
[af50685]2221        case LIST_LENGTH_KEY:
2222            DrawLengthKey();
2223            break;
[d2fcc9b]2224        case LIST_UNDERGROUND_LEGS:
2225            GenerateDisplayList();
2226            break;
2227        case LIST_TUBES:
2228            GenerateDisplayListTubes();
2229            break;
2230        case LIST_SURFACE_LEGS:
2231            GenerateDisplayListSurface();
2232            break;
[86fe6e4]2233        case LIST_BLOBS:
2234            GenerateBlobsDisplayList();
[37d7084]2235            break;
[86fe6e4]2236        case LIST_CROSSES: {
2237            BeginCrosses();
2238            SetColour(col_LIGHT_GREY);
2239            list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2240            while (pos != m_Parent->GetLabelsEnd()) {
2241                const LabelInfo* label = *pos++;
2242
2243                if ((m_Surface && label->IsSurface()) ||
2244                    (m_Legs && label->IsUnderground()) ||
2245                    (!label->IsSurface() && !label->IsUnderground())) {
2246                    // Check if this station should be displayed
2247                    // (last case is for stns with no legs attached)
2248                    DrawCross(label->GetX(), label->GetY(), label->GetZ());
2249                }
2250            }
2251            EndCrosses();
2252            break;
2253        }
[37d7084]2254        case LIST_GRID:
2255            DrawGrid();
[d2fcc9b]2256            break;
[86fe6e4]2257        case LIST_SHADOW:
2258            GenerateDisplayListShadow();
[d2fcc9b]2259            break;
2260        default:
2261            assert(false);
2262            break;
2263    }
2264}
2265
[d67450e]2266void GfxCore::ToggleSmoothShading()
2267{
2268    GLACanvas::ToggleSmoothShading();
2269    InvalidateList(LIST_TUBES);
2270    ForceRefresh();
2271}
2272
[d2fcc9b]2273void GfxCore::GenerateDisplayList()
2274{
2275    // Generate the display list for the underground legs.
[c61aa79]2276    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2277    list<traverse>::const_iterator tend = m_Parent->traverses_end();
[8666fc7]2278
[ad661cc]2279    if (m_Splays == SPLAYS_SHOW_FADED) {
[bd77a6a]2280        SetAlpha(0.4);
[ad661cc]2281        while (trav != tend) {
2282            if ((*trav).isSplay)
2283                (this->*AddPoly)(*trav);
2284            ++trav;
2285        }
[4a1cede]2286        SetAlpha(1.0);
[ad661cc]2287        trav = m_Parent->traverses_begin();
[8666fc7]2288    }
2289
[3ddcad8]2290    while (trav != tend) {
[ad661cc]2291        if (m_Splays == SPLAYS_SHOW_NORMAL || !(*trav).isSplay)
[8666fc7]2292            (this->*AddPoly)(*trav);
[3ddcad8]2293        ++trav;
2294    }
[33b2094]2295}
2296
[9eb58d0]2297void GfxCore::GenerateDisplayListTubes()
[33b2094]2298{
[9eb58d0]2299    // Generate the display list for the tubes.
[fc68ad5]2300    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
2301    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
[3ddcad8]2302    while (trav != tend) {
2303        SkinPassage(*trav);
2304        ++trav;
2305    }
[9eb58d0]2306}
[33b2094]2307
[9eb58d0]2308void GfxCore::GenerateDisplayListSurface()
2309{
2310    // Generate the display list for the surface legs.
[3ddcad8]2311    EnableDashedLines();
[c61aa79]2312    list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2313    list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
[3ddcad8]2314    while (trav != tend) {
[c61aa79]2315        if (m_ColourBy == COLOUR_BY_ERROR) {
2316            AddPolylineError(*trav);
2317        } else {
2318            AddPolyline(*trav);
2319        }
[3ddcad8]2320        ++trav;
2321    }
2322    DisableDashedLines();
[d9b3270]2323}
[33b2094]2324
[37d7084]2325void GfxCore::GenerateDisplayListShadow()
[f4c5932]2326{
2327    SetColour(col_BLACK);
[c61aa79]2328    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2329    list<traverse>::const_iterator tend = m_Parent->traverses_end();
[f4c5932]2330    while (trav != tend) {
2331        AddPolylineShadow(*trav);
2332        ++trav;
2333    }
2334}
2335
[d2fcc9b]2336// Plot blobs.
[d9b3270]2337void GfxCore::GenerateBlobsDisplayList()
2338{
[e633bb1]2339    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2340          m_Parent->GetNumHighlightedPts()))
2341        return;
[429465a]2342
[e633bb1]2343    // Plot blobs.
2344    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2345    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2346    BeginBlobs();
2347    while (pos != m_Parent->GetLabelsEnd()) {
[429465a]2348        const LabelInfo* label = *pos++;
2349
2350        // When more than one flag is set on a point:
2351        // search results take priority over entrance highlighting
2352        // which takes priority over fixed point
2353        // highlighting, which in turn takes priority over exported
2354        // point highlighting.
2355
2356        if (!((m_Surface && label->IsSurface()) ||
2357              (m_Legs && label->IsUnderground()) ||
2358              (!label->IsSurface() && !label->IsUnderground()))) {
2359            // if this station isn't to be displayed, skip to the next
2360            // (last case is for stns with no legs attached)
2361            continue;
2362        }
2363
[e633bb1]2364        gla_colour col;
2365
[429465a]2366        if (label->IsHighLighted()) {
2367            col = col_YELLOW;
2368        } else if (m_Entrances && label->IsEntrance()) {
2369            col = col_GREEN;
2370        } else if (m_FixedPts && label->IsFixedPt()) {
2371            col = col_RED;
2372        } else if (m_ExportedPts && label->IsExportedPt()) {
2373            col = col_TURQUOISE;
2374        } else {
2375            continue;
2376        }
2377
[e633bb1]2378        // Stations are sorted by blob type, so colour changes are infrequent.
2379        if (col != prev_col) {
[aa048c3]2380            SetColour(col);
[e633bb1]2381            prev_col = col;
[429465a]2382        }
[e633bb1]2383        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
[d9b3270]2384    }
[e633bb1]2385    EndBlobs();
[33b2094]2386}
2387
[6747314]2388void GfxCore::DrawIndicators()
[33b2094]2389{
[97ea48d]2390    // Draw colour key.
2391    if (m_ColourKey) {
[62c5fc6]2392        if (m_ColourBy == COLOUR_BY_DEPTH) {
[62da267]2393            DrawList2D(LIST_DEPTH_KEY, GetXSize() - KEY_OFFSET_X,
2394                       GetYSize() - KEY_OFFSET_Y, 0);
[62c5fc6]2395        } else if (m_ColourBy == COLOUR_BY_DATE) {
[62da267]2396            DrawList2D(LIST_DATE_KEY, GetXSize() - KEY_OFFSET_X,
2397                       GetYSize() - KEY_OFFSET_Y, 0);
[62c5fc6]2398        } else if (m_ColourBy == COLOUR_BY_ERROR) {
[62da267]2399            DrawList2D(LIST_ERROR_KEY, GetXSize() - KEY_OFFSET_X,
2400                       GetYSize() - KEY_OFFSET_Y, 0);
[af50685]2401        } else if (m_ColourBy == COLOUR_BY_LENGTH) {
2402            DrawList2D(LIST_LENGTH_KEY, GetXSize() - KEY_OFFSET_X,
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);
2660
[97ea48d]2661    int band = int(floor(how_far * (GetNumColourBands() - 1)));
[d4650b3]2662    GLAPen pen1 = GetPen(band);
[97ea48d]2663    if (band < GetNumColourBands() - 1) {
[d4650b3]2664        const GLAPen& pen2 = GetPen(band + 1);
2665
[97ea48d]2666        Double interval = date_ext / (GetNumColourBands() - 1);
[d4650b3]2667        Double into_band = date_offset / interval - band;
2668
2669//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2670//             z_offset, interval, band);
2671        // FIXME: why do we need to clamp here?  Is it because the walls can
2672        // extend further up/down than the centre-line?
2673        if (into_band < 0.0) into_band = 0.0;
2674        if (into_band > 1.0) into_band = 1.0;
2675        assert(into_band >= 0.0);
2676        assert(into_band <= 1.0);
2677
2678        pen1.Interpolate(pen2, into_band);
2679    }
2680    SetColour(pen1, factor);
2681}
2682
[c61aa79]2683void GfxCore::AddPolylineDate(const traverse & centreline)
[d4650b3]2684{
2685    BeginPolyline();
2686    vector<PointInfo>::const_iterator i, prev_i;
2687    i = centreline.begin();
[1ee204e]2688    int date = i->GetDate();
[d4650b3]2689    SetColourFromDate(date, 1.0);
[d67450e]2690    PlaceVertex(*i);
[d4650b3]2691    prev_i = i;
2692    while (++i != centreline.end()) {
[1ee204e]2693        int newdate = i->GetDate();
[d4650b3]2694        if (newdate != date) {
2695            EndPolyline();
2696            BeginPolyline();
2697            date = newdate;
2698            SetColourFromDate(date, 1.0);
[d67450e]2699            PlaceVertex(*prev_i);
[d4650b3]2700        }
[d67450e]2701        PlaceVertex(*i);
[d4650b3]2702        prev_i = i;
2703    }
2704    EndPolyline();
2705}
2706
[1ee204e]2707static int static_date_hack; // FIXME
[d4650b3]2708
2709void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
2710                                   const Vector3 &c, const Vector3 &d)
2711{
2712    Vector3 normal = (a - c) * (d - b);
2713    normal.normalise();
2714    Double factor = dot(normal, light) * .3 + .7;
2715    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2716    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2717    // FIXME: should plot triangles instead to avoid rendering glitches.
[b839829]2718    BeginQuadrilaterals();
[d67450e]2719////    PlaceNormal(normal);
[d4650b3]2720    SetColourFromDate(static_date_hack, factor);
[b839829]2721    PlaceVertex(a, 0, 0);
2722    PlaceVertex(b, w, 0);
2723    PlaceVertex(c, w, h);
2724    PlaceVertex(d, 0, h);
2725    EndQuadrilaterals();
[d4650b3]2726}
2727
[c61aa79]2728static double static_E_hack; // FIXME
2729
2730void GfxCore::SetColourFromError(double E, Double factor)
2731{
2732    // Set the drawing colour based on an error value.
2733
2734    if (E < 0) {
[d1ce9bd]2735        SetColour(col_WHITE, factor);
[c61aa79]2736        return;
2737    }
2738
2739    Double how_far = E / MAX_ERROR;
2740    assert(how_far >= 0.0);
2741    if (how_far > 1.0) how_far = 1.0;
2742
[97ea48d]2743    int band = int(floor(how_far * (GetNumColourBands() - 1)));
[c61aa79]2744    GLAPen pen1 = GetPen(band);
[97ea48d]2745    if (band < GetNumColourBands() - 1) {
[c61aa79]2746        const GLAPen& pen2 = GetPen(band + 1);
2747
[97ea48d]2748        Double interval = MAX_ERROR / (GetNumColourBands() - 1);
[c61aa79]2749        Double into_band = E / interval - band;
2750
2751//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2752//             z_offset, interval, band);
2753        // FIXME: why do we need to clamp here?  Is it because the walls can
2754        // extend further up/down than the centre-line?
2755        if (into_band < 0.0) into_band = 0.0;
2756        if (into_band > 1.0) into_band = 1.0;
2757        assert(into_band >= 0.0);
2758        assert(into_band <= 1.0);
2759
2760        pen1.Interpolate(pen2, into_band);
2761    }
2762    SetColour(pen1, factor);
2763}
2764
2765void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
2766                                    const Vector3 &c, const Vector3 &d)
2767{
2768    Vector3 normal = (a - c) * (d - b);
2769    normal.normalise();
2770    Double factor = dot(normal, light) * .3 + .7;
2771    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2772    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2773    // FIXME: should plot triangles instead to avoid rendering glitches.
[b839829]2774    BeginQuadrilaterals();
[c61aa79]2775////    PlaceNormal(normal);
2776    SetColourFromError(static_E_hack, factor);
[b839829]2777    PlaceVertex(a, 0, 0);
2778    PlaceVertex(b, w, 0);
2779    PlaceVertex(c, w, h);
2780    PlaceVertex(d, 0, h);
2781    EndQuadrilaterals();
[c61aa79]2782}
2783
2784void GfxCore::AddPolylineError(const traverse & centreline)
2785{
2786    BeginPolyline();
2787    SetColourFromError(centreline.E, 1.0);
2788    vector<PointInfo>::const_iterator i;
2789    for(i = centreline.begin(); i != centreline.end(); ++i) {
2790        PlaceVertex(*i);
2791    }
2792    EndPolyline();
2793}
2794
[af50685]2795void GfxCore::SetColourFromLength(double length, Double factor)
2796{
2797    // Set the drawing colour based on log(length_of_leg).
2798
2799    Double log_len = log10(length);
2800    Double how_far = log_len / LOG_LEN_MAX;
2801    how_far = max(how_far, 0.0);
2802    how_far = min(how_far, 1.0);
2803
2804    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2805    GLAPen pen1 = GetPen(band);
2806    if (band < GetNumColourBands() - 1) {
2807        const GLAPen& pen2 = GetPen(band + 1);
2808
2809        Double interval = LOG_LEN_MAX / (GetNumColourBands() - 1);
2810        Double into_band = log_len / interval - band;
2811
2812        assert(into_band >= 0.0);
2813        assert(into_band <= 1.0);
2814
2815        pen1.Interpolate(pen2, into_band);
2816    }
2817    SetColour(pen1, factor);
2818}
2819
2820void GfxCore::AddPolylineLength(const traverse & centreline)
2821{
2822    vector<PointInfo>::const_iterator i, prev_i;
2823    i = centreline.begin();
2824    prev_i = i;
2825    while (++i != centreline.end()) {
2826        Double len = (*i - *prev_i).magnitude();
2827        BeginPolyline();
2828        SetColourFromLength(len, 1.0);
2829        PlaceVertex(*prev_i);
2830        PlaceVertex(*i);
2831        prev_i = i;
2832        EndPolyline();
2833    }
2834}
2835
2836static double static_length_hack; // FIXME
2837
2838void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
2839                                     const Vector3 &c, const Vector3 &d)
2840{
2841    Vector3 normal = (a - c) * (d - b);
2842    normal.normalise();
2843    Double factor = dot(normal, light) * .3 + .7;
2844    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2845    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2846    // FIXME: should plot triangles instead to avoid rendering glitches.
2847    BeginQuadrilaterals();
2848////    PlaceNormal(normal);
2849    SetColourFromLength(static_length_hack, factor);
2850    PlaceVertex(a, 0, 0);
2851    PlaceVertex(b, w, 0);
2852    PlaceVertex(c, w, h);
2853    PlaceVertex(d, 0, h);
2854    EndQuadrilaterals();
2855}
2856
[da6c802]2857void
[384534c]2858GfxCore::SkinPassage(vector<XSect> & centreline, bool draw)
[3ddcad8]2859{
[b3852b5]2860    assert(centreline.size() > 1);
[3ddcad8]2861    Vector3 U[4];
[ee05463]2862    XSect prev_pt_v;
[3ddcad8]2863    Vector3 last_right(1.0, 0.0, 0.0);
2864
[c61aa79]2865//  FIXME: it's not simple to set the colour of a tube based on error...
2866//    static_E_hack = something...
[fc68ad5]2867    vector<XSect>::iterator i = centreline.begin();
[ee05463]2868    vector<XSect>::size_type segment = 0;
[3ddcad8]2869    while (i != centreline.end()) {
2870        // get the coordinates of this vertex
[fc68ad5]2871        XSect & pt_v = *i++;
[3ddcad8]2872
2873        double z_pitch_adjust = 0.0;
2874        bool cover_end = false;
2875
2876        Vector3 right, up;
2877
2878        const Vector3 up_v(0.0, 0.0, 1.0);
2879
2880        if (segment == 0) {
2881            assert(i != centreline.end());
2882            // first segment
2883
2884            // get the coordinates of the next vertex
[ee05463]2885            const XSect & next_pt_v = *i;
[3ddcad8]2886
2887            // calculate vector from this pt to the next one
[d67450e]2888            Vector3 leg_v = next_pt_v - pt_v;
[3ddcad8]2889
2890            // obtain a vector in the LRUD plane
2891            right = leg_v * up_v;
2892            if (right.magnitude() == 0) {
2893                right = last_right;
2894                // Obtain a second vector in the LRUD plane,
2895                // perpendicular to the first.
[760ad29d]2896                //up = right * leg_v;
2897                up = up_v;
[3ddcad8]2898            } else {
2899                last_right = right;
2900                up = up_v;
[da6c802]2901            }
2902
[3ddcad8]2903            cover_end = true;
[d4650b3]2904            static_date_hack = next_pt_v.GetDate();
[3ddcad8]2905        } else if (segment + 1 == centreline.size()) {
2906            // last segment
2907
2908            // Calculate vector from the previous pt to this one.
[d67450e]2909            Vector3 leg_v = pt_v - prev_pt_v;
[3ddcad8]2910
2911            // Obtain a horizontal vector in the LRUD plane.
2912            right = leg_v * up_v;
2913            if (right.magnitude() == 0) {
[d67450e]2914                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
[3ddcad8]2915                // Obtain a second vector in the LRUD plane,
2916                // perpendicular to the first.
[760ad29d]2917                //up = right * leg_v;
2918                up = up_v;
[3ddcad8]2919            } else {
2920                last_right = right;
2921                up = up_v;
2922            }
[da6c802]2923
[3ddcad8]2924            cover_end = true;
[d4650b3]2925            static_date_hack = pt_v.GetDate();
[3ddcad8]2926        } else {
2927            assert(i != centreline.end());
2928            // Intermediate segment.
2929
2930            // Get the coordinates of the next vertex.
[ee05463]2931            const XSect & next_pt_v = *i;
[3ddcad8]2932
2933            // Calculate vectors from this vertex to the
2934            // next vertex, and from the previous vertex to
2935            // this one.
[d67450e]2936            Vector3 leg1_v = pt_v - prev_pt_v;
2937            Vector3 leg2_v = next_pt_v - pt_v;
[3ddcad8]2938
2939            // Obtain horizontal vectors perpendicular to
2940            // both legs, then normalise and average to get
2941            // a horizontal bisector.
2942            Vector3 r1 = leg1_v * up_v;
2943            Vector3 r2 = leg2_v * up_v;
2944            r1.normalise();
2945            r2.normalise();
2946            right = r1 + r2;
2947            if (right.magnitude() == 0) {
2948                // This is the "mid-pitch" case...
2949                right = last_right;
2950            }
2951            if (r1.magnitude() == 0) {
2952                Vector3 n = leg1_v;
2953                n.normalise();
[d67450e]2954                z_pitch_adjust = n.GetZ();
2955                //up = Vector3(0, 0, leg1_v.GetZ());
[760ad29d]2956                //up = right * up;
2957                up = up_v;
[3ddcad8]2958
2959                // Rotate pitch section to minimise the
2960                // "tortional stress" - FIXME: use
2961                // triangles instead of rectangles?
2962                int shift = 0;
2963                Double maxdotp = 0;
2964
2965                // Scale to unit vectors in the LRUD plane.
2966                right.normalise();
2967                up.normalise();
2968                Vector3 vec = up - right;
2969                for (int orient = 0; orient <= 3; ++orient) {
[d67450e]2970                    Vector3 tmp = U[orient] - prev_pt_v;
[3ddcad8]2971                    tmp.normalise();
2972                    Double dotp = dot(vec, tmp);
2973                    if (dotp > maxdotp) {
2974                        maxdotp = dotp;
2975                        shift = orient;
2976                    }
2977                }
2978                if (shift) {
2979                    if (shift != 2) {
2980                        Vector3 temp(U[0]);
[b3852b5]2981                        U[0] = U[shift];
2982                        U[shift] = U[2];
2983                        U[2] = U[shift ^ 2];
2984                        U[shift ^ 2] = temp;
[ee7af72]2985                    } else {
[3ddcad8]2986                        swap(U[0], U[2]);
2987                        swap(U[1], U[3]);
[ee7af72]2988                    }
[3ddcad8]2989                }
2990#if 0
2991                // Check that the above code actually permuted
2992                // the vertices correctly.
2993                shift = 0;
2994                maxdotp = 0;
[b3852b5]2995                for (int j = 0; j <= 3; ++j) {
[d67450e]2996                    Vector3 tmp = U[j] - prev_pt_v;
[3ddcad8]2997                    tmp.normalise();
2998                    Double dotp = dot(vec, tmp);
2999                    if (dotp > maxdotp) {
3000                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
[b3852b5]3001                        shift = j;
[da6c802]3002                    }
[3ddcad8]3003                }
3004                if (shift) {
3005                    printf("New shift = %d!\n", shift);
3006                    shift = 0;
3007                    maxdotp = 0;
[b3852b5]3008                    for (int j = 0; j <= 3; ++j) {
[d67450e]3009                        Vector3 tmp = U[j] - prev_pt_v;
[3ddcad8]3010                        tmp.normalise();
3011                        Double dotp = dot(vec, tmp);
[b3852b5]3012                        printf("    %d : %.8f\n", j, dotp);
[da6c802]3013                    }
3014                }
[3ddcad8]3015#endif
3016            } else if (r2.magnitude() == 0) {
3017                Vector3 n = leg2_v;
3018                n.normalise();
[d67450e]3019                z_pitch_adjust = n.GetZ();
3020                //up = Vector3(0, 0, leg2_v.GetZ());
[760ad29d]3021                //up = right * up;
3022                up = up_v;
[3ddcad8]3023            } else {
3024                up = up_v;
[da6c802]3025            }
[3ddcad8]3026            last_right = right;
[d4650b3]3027            static_date_hack = pt_v.GetDate();
[da6c802]3028        }
3029
[3ddcad8]3030        // Scale to unit vectors in the LRUD plane.
3031        right.normalise();
3032        up.normalise();
[33b2094]3033
[3ddcad8]3034        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
[ce2f3ce]3035
[57a3cd4]3036        Double l = fabs(pt_v.GetL());
3037        Double r = fabs(pt_v.GetR());
3038        Double u = fabs(pt_v.GetU());
3039        Double d = fabs(pt_v.GetD());
[3ddcad8]3040
3041        // Produce coordinates of the corners of the LRUD "plane".
3042        Vector3 v[4];
[d67450e]3043        v[0] = pt_v - right * l + up * u;
3044        v[1] = pt_v + right * r + up * u;
3045        v[2] = pt_v + right * r - up * d;
3046        v[3] = pt_v - right * l - up * d;
[3ddcad8]3047
[384534c]3048        if (draw) {
[af50685]3049            static_length_hack = (pt_v - prev_pt_v).magnitude();
[384534c]3050            if (segment > 0) {
3051                (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3052                (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3053                (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3054                (this->*AddQuad)(v[3], v[0], U[0], U[3]);
3055            }
[9eb58d0]3056
[384534c]3057            if (cover_end) {
3058                (this->*AddQuad)(v[3], v[2], v[1], v[0]);
3059            }
[3ddcad8]3060        }
[9eb58d0]3061
[3ddcad8]3062        prev_pt_v = pt_v;
3063        U[0] = v[0];
3064        U[1] = v[1];
3065        U[2] = v[2];
3066        U[3] = v[3];
[9eb58d0]3067
[fc68ad5]3068        pt_v.set_right_bearing(deg(atan2(right.GetY(), right.GetX())));
3069
[3ddcad8]3070        ++segment;
3071    }
[33b2094]3072}
[b13aee4]3073
3074void GfxCore::FullScreenMode()
3075{
[ea940373]3076    m_Parent->ViewFullScreen();
[b13aee4]3077}
[fdfa926]3078
3079bool GfxCore::IsFullScreen() const
3080{
3081    return m_Parent->IsFullScreen();
3082}
[1690fa9]3083
[b75a37d]3084bool GfxCore::FullScreenModeShowingMenus() const
3085{
3086    return m_Parent->FullScreenModeShowingMenus();
3087}
3088
3089void GfxCore::FullScreenModeShowMenus(bool show)
3090{
3091    m_Parent->FullScreenModeShowMenus(show);
3092}
3093
[46361bc]3094void
3095GfxCore::MoveViewer(double forward, double up, double right)
3096{
[e577f89]3097    double cT = cos(rad(m_TiltAngle));
3098    double sT = sin(rad(m_TiltAngle));
3099    double cP = cos(rad(m_PanAngle));
3100    double sP = sin(rad(m_PanAngle));
[7a57dc7]3101    Vector3 v_forward(cT * sP, cT * cP, sT);
3102    Vector3 v_up(sT * sP, sT * cP, -cT);
[867a1141]3103    Vector3 v_right(-cP, sP, 0);
[d4a5aaf]3104    assert(fabs(dot(v_forward, v_up)) < 1e-6);
3105    assert(fabs(dot(v_forward, v_right)) < 1e-6);
3106    assert(fabs(dot(v_right, v_up)) < 1e-6);
[46361bc]3107    Vector3 move = v_forward * forward + v_up * up + v_right * right;
[d67450e]3108    AddTranslation(-move);
[d877aa2]3109    // Show current position.
[d67450e]3110    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
[46361bc]3111    ForceRefresh();
3112}
3113
[1690fa9]3114PresentationMark GfxCore::GetView() const
3115{
[d67450e]3116    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
[7a57dc7]3117                            m_PanAngle, -m_TiltAngle, m_Scale);
[1690fa9]3118}
3119
3120void GfxCore::SetView(const PresentationMark & p)
3121{
3122    m_SwitchingTo = 0;
[d67450e]3123    SetTranslation(p - m_Parent->GetOffset());
[1690fa9]3124    m_PanAngle = p.angle;
[7a57dc7]3125    m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
[08253d9]3126    SetRotation(m_PanAngle, m_TiltAngle);
[1690fa9]3127    SetScale(p.scale);
3128    ForceRefresh();
3129}
3130
[128fac4]3131void GfxCore::PlayPres(double speed, bool change_speed) {
3132    if (!change_speed || presentation_mode == 0) {
3133        if (speed == 0.0) {
3134            presentation_mode = 0;
3135            return;
3136        }
3137        presentation_mode = PLAYING;
3138        next_mark = m_Parent->GetPresMark(MARK_FIRST);
3139        SetView(next_mark);
3140        next_mark_time = 0; // There already!
3141        this_mark_total = 0;
3142        pres_reverse = (speed < 0);
3143    }
3144
[d67450e]3145    if (change_speed) pres_speed = speed;
3146
[128fac4]3147    if (speed != 0.0) {
3148        bool new_pres_reverse = (speed < 0);
3149        if (new_pres_reverse != pres_reverse) {
3150            pres_reverse = new_pres_reverse;
3151            if (pres_reverse) {
3152                next_mark = m_Parent->GetPresMark(MARK_PREV);
3153            } else {
3154                next_mark = m_Parent->GetPresMark(MARK_NEXT);
3155            }
3156            swap(this_mark_total, next_mark_time);
3157        }
3158    }
[1690fa9]3159}
[6a4cdcb6]3160
[da6c802]3161void GfxCore::SetColourBy(int colour_by) {
3162    m_ColourBy = colour_by;
3163    switch (colour_by) {
3164        case COLOUR_BY_DEPTH:
3165            AddQuad = &GfxCore::AddQuadrilateralDepth;
3166            AddPoly = &GfxCore::AddPolylineDepth;
3167            break;
[d4650b3]3168        case COLOUR_BY_DATE:
3169            AddQuad = &GfxCore::AddQuadrilateralDate;
3170            AddPoly = &GfxCore::AddPolylineDate;
3171            break;
[c61aa79]3172        case COLOUR_BY_ERROR:
3173            AddQuad = &GfxCore::AddQuadrilateralError;
3174            AddPoly = &GfxCore::AddPolylineError;
3175            break;
[af50685]3176        case COLOUR_BY_LENGTH:
3177            AddQuad = &GfxCore::AddQuadrilateralLength;
3178            AddPoly = &GfxCore::AddPolylineLength;
3179            break;
[da6c802]3180        default: // case COLOUR_BY_NONE:
3181            AddQuad = &GfxCore::AddQuadrilateral;
3182            AddPoly = &GfxCore::AddPolyline;
3183            break;
3184    }
3185
[d2fcc9b]3186    InvalidateList(LIST_UNDERGROUND_LEGS);
[c61aa79]3187    InvalidateList(LIST_SURFACE_LEGS);
[d2fcc9b]3188    InvalidateList(LIST_TUBES);
[da6c802]3189
3190    ForceRefresh();
3191}
3192
[6a4cdcb6]3193bool GfxCore::ExportMovie(const wxString & fnm)
3194{
3195    int width;
3196    int height;
3197    GetSize(&width, &height);
[028829f]3198    // Round up to next multiple of 2 (required by ffmpeg).
3199    width += (width & 1);
[6a4cdcb6]3200    height += (height & 1);
3201
[75d4a2b]3202    movie = new MovieMaker();
[6a4cdcb6]3203
[98a3786]3204    // FIXME: This should really use fn_str() - currently we probably can't
3205    // save to a Unicode path on wxmsw.
[75d4a2b]3206    if (!movie->Open(fnm.mb_str(), width, height)) {
[091069f]3207        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
[75d4a2b]3208        delete movie;
[81f1266]3209        movie = NULL;
[6a4cdcb6]3210        return false;
3211    }
[f433fda]3212
[d10d369]3213    PlayPres(1);
[6a4cdcb6]3214    return true;
3215}
[223f1ad]3216
[ce403f1]3217void
3218GfxCore::OnPrint(const wxString &filename, const wxString &title,
[4ed8154]3219                 const wxString &datestamp, time_t datestamp_numeric,
[6d3938b]3220                 const wxString &cs_proj,
[4ed8154]3221                 bool close_after_print)
[ce403f1]3222{
3223    svxPrintDlg * p;
[6d3938b]3224    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
[f10cf8f]3225                        datestamp, datestamp_numeric,
[ce403f1]3226                        m_PanAngle, m_TiltAngle,
[5624403]3227                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
[fdea415]3228                        m_Entrances, m_FixedPts, m_ExportedPts,
[4ed8154]3229                        true, close_after_print);
[6d1bc83]3230    p->Show(true);
[ce403f1]3231}
3232
[5940815]3233void
[70462c8]3234GfxCore::OnExport(const wxString &filename, const wxString &title,
[6d3938b]3235                  const wxString &datestamp, time_t datestamp_numeric,
3236                  const wxString &cs_proj)
[223f1ad]3237{
[384534c]3238    // Fill in "right_bearing" for each cross-section.
3239    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
3240    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
3241    while (trav != tend) {
3242        SkinPassage(*trav, false);
3243        ++trav;
3244    }
3245
[5940815]3246    svxPrintDlg * p;
[6d3938b]3247    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
[f10cf8f]3248                        datestamp, datestamp_numeric,
[5940815]3249                        m_PanAngle, m_TiltAngle,
[5624403]3250                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
[fdea415]3251                        m_Entrances, m_FixedPts, m_ExportedPts,
[5940815]3252                        false);
[6d1bc83]3253    p->Show(true);
[223f1ad]3254}
[e2c1671]3255
3256static wxCursor
3257make_cursor(const unsigned char * bits, const unsigned char * mask,
3258            int hotx, int hoty)
3259{
[b72f4b5]3260#if defined __WXMSW__ || defined __WXMAC__
[60adbce]3261# ifdef __WXMAC__
3262    // The default Mac cursor is black with a white edge, so
3263    // invert our custom cursors to match.
3264    char b[128];
3265    for (int i = 0; i < 128; ++i)
3266        b[i] = bits[i] ^ 0xff;
3267# else
3268    const char * b = reinterpret_cast<const char *>(bits);
3269# endif
3270    wxBitmap cursor_bitmap(b, 32, 32);
[7f3fe6d]3271    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
[4dc4384]3272    cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
[e2c1671]3273    wxImage cursor_image = cursor_bitmap.ConvertToImage();
3274    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
3275    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
[7f3fe6d]3276    return wxCursor(cursor_image);
[e2c1671]3277#else
3278    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
[4dc4384]3279                    (const char *)mask, wxBLACK, wxWHITE);
[e2c1671]3280#endif
3281}
3282
3283const
3284#include "hand.xbm"
3285const
3286#include "handmask.xbm"
3287
3288const
3289#include "brotate.xbm"
3290const
3291#include "brotatemask.xbm"
3292
3293const
3294#include "vrotate.xbm"
3295const
3296#include "vrotatemask.xbm"
3297
3298const
3299#include "rotate.xbm"
3300const
3301#include "rotatemask.xbm"
3302
[ecf2d23]3303const
3304#include "rotatezoom.xbm"
3305const
3306#include "rotatezoommask.xbm"
3307
[e2c1671]3308void
[242cb07]3309GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
[e2c1671]3310{
3311    // Check if we're already showing that cursor.
3312    if (current_cursor == new_cursor) return;
3313
3314    current_cursor = new_cursor;
3315    switch (current_cursor) {
3316        case GfxCore::CURSOR_DEFAULT:
3317            GLACanvas::SetCursor(wxNullCursor);
3318            break;
3319        case GfxCore::CURSOR_POINTING_HAND:
3320            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
3321            break;
3322        case GfxCore::CURSOR_DRAGGING_HAND:
3323            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
3324            break;
3325        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
3326            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
3327            break;
3328        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
3329            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
3330            break;
3331        case GfxCore::CURSOR_ROTATE_VERTICALLY:
3332            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
3333            break;
3334        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
3335            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
3336            break;
3337        case GfxCore::CURSOR_ZOOM:
3338            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
3339            break;
[ecf2d23]3340        case GfxCore::CURSOR_ZOOM_ROTATE:
3341            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
3342            break;
[e2c1671]3343    }
3344}
[6b061db]3345
3346bool GfxCore::MeasuringLineActive() const
3347{
3348    if (Animating()) return false;
[381ae6e]3349    return HereIsReal() || m_there;
[6b061db]3350}
[acdb8aa]3351
3352bool GfxCore::HandleRClick(wxPoint point)
3353{
3354    if (PointWithinCompass(point)) {
3355        // Pop up menu.
3356        wxMenu menu;
[736f7df]3357        /* TRANSLATORS: View *looking* North */
[055bfc58]3358        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
[736f7df]3359        /* TRANSLATORS: View *looking* East */
[055bfc58]3360        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
[736f7df]3361        /* TRANSLATORS: View *looking* South */
[055bfc58]3362        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
[736f7df]3363        /* TRANSLATORS: View *looking* West */
[055bfc58]3364        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
3365        menu.AppendSeparator();
[736f7df]3366        /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
[4d2301e]3367        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
[0b8c321]3368        /* TRANSLATORS: tickable menu item in View menu.
3369         *
3370         * Degrees are the angular measurement where there are 360 in a full
3371         * circle. */
[acdb8aa]3372        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
[ee3e284]3373        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]3374        PopupMenu(&menu);
3375        return true;
3376    }
3377
3378    if (PointWithinClino(point)) {
3379        // Pop up menu.
3380        wxMenu menu;
[055bfc58]3381        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
3382        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
3383        menu.AppendSeparator();
[736f7df]3384        /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
[acdb8aa]3385        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
[736f7df]3386        /* TRANSLATORS: tickable menu item in View menu.
3387         *
3388         * Degrees are the angular measurement where there are 360 in a full
3389         * circle. */
[acdb8aa]3390        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
[736f7df]3391        /* TRANSLATORS: tickable menu item in View menu.
3392         *
3393         * Show the tilt of the survey as a percentage gradient (100% = 45
3394         * degrees = 50 grad). */
[d171c0c]3395        menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
[ee3e284]3396        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3397        PopupMenu(&menu);
[acdb8aa]3398        return true;
3399    }
3400
3401    if (PointWithinScaleBar(point)) {
3402        // Pop up menu.
3403        wxMenu menu;
[736f7df]3404        /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
[acdb8aa]3405        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
[0b8c321]3406        /* TRANSLATORS: tickable menu item in View menu.
3407         *
3408         * "Metric" here means metres, km, etc (rather than feet, miles, etc)
3409         */
[acdb8aa]3410        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
[ee3e284]3411        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]3412        PopupMenu(&menu);
3413        return true;
3414    }
3415
3416    if (PointWithinColourKey(point)) {
3417        // Pop up menu.
3418        wxMenu menu;
[d43fa84]3419        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
3420        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
3421        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_ERROR, wmsg(/*Colour by E&rror*/289));
[af50685]3422        menu.AppendCheckItem(menu_VIEW_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
[d43fa84]3423        menu.AppendSeparator();
[736f7df]3424        /* TRANSLATORS: Menu item which turns off the colour key.
3425         * The "Colour Key" is the thing in aven showing which colour
3426         * corresponds to which depth, date, survey closure error, etc. */
[97ea48d]3427        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
[d43fa84]3428        if (m_ColourBy == COLOUR_BY_DEPTH)
3429            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
[ee3e284]3430        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
[acdb8aa]3431        PopupMenu(&menu);
3432        return true;
3433    }
3434
3435    return false;
3436}
[dd6af8b]3437
3438void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
3439{
3440    if (centred) {
3441        p1.x = p2.x + (p1.x - p2.x) * 2;
3442        p1.y = p2.y + (p1.y - p2.y) * 2;
3443    }
3444    if (aspect) {
3445#if 0 // FIXME: This needs more work.
3446        int sx = GetXSize();
3447        int sy = GetYSize();
3448        int dx = p1.x - p2.x;
3449        int dy = p1.y - p2.y;
3450        int dy_new = dx * sy / sx;
3451        if (abs(dy_new) >= abs(dy)) {
3452            p1.y += (dy_new - dy) / 2;
3453            p2.y -= (dy_new - dy) / 2;
3454        } else {
3455            int dx_new = dy * sx / sy;
3456            p1.x += (dx_new - dx) / 2;
3457            p2.x -= (dx_new - dx) / 2;
3458        }
3459#endif
3460    }
3461    zoombox.set(p1, p2);
3462    ForceRefresh();
3463}
3464
3465void GfxCore::ZoomBoxGo()
3466{
3467    if (!zoombox.active()) return;
3468
3469    int width = GetXSize();
3470    int height = GetYSize();
3471
3472    TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
3473                  -0.5 * (zoombox.y1 + zoombox.y2 - height));
3474    int box_w = abs(zoombox.x1 - zoombox.x2);
3475    int box_h = abs(zoombox.y1 - zoombox.y2);
3476
3477    double factor = min(double(width) / box_w, double(height) / box_h);
3478
3479    zoombox.unset();
3480
3481    SetScale(GetScale() * factor);
3482}
Note: See TracBrowser for help on using the repository browser.