source: git/src/gfxcore.cc @ 18124e4

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

src/gfxcore.cc: Tweak error message in terrain reading code to
distinguish two failure cases.

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