source: git/src/gfxcore.cc @ 46beda0

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

lib/survex.pot,src/: Create a "Colour by" submenu of the "View" menu.

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