source: git/src/gfxcore.cc @ 91732f2

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

src/gfxcore.cc: Test with the void-filled 3-arc second SRTM data.

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