source: git/src/gfxcore.cc @ 4938bcd

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since 4938bcd was 4938bcd, checked in by Olly Betts <olly@…>, 10 years ago

lib/icons/Makefile.am,lib/icons/solid-surface.png,
lib/icons/solid_surface.xpm,lib/survex.pot,src/: Add UI for toggling
terrain on and off.

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