source: git/src/gfxcore.cc @ 74869a7

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

src/gfxcore.cc: Force a refresh after loading terrain data so
that it gets displayed right away.

  • Property mode set to 100644
File size: 106.7 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 "printing.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().Lower();
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')
2508                    o_y = -o_y;
2509                ++o_y;
2510                dirn = *p++;
2511                o_x = strtoul(p, &q, 10);
2512                if (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) {
2580        wxMessageBox(wxT("No DEM data found in .zip file"));
2581        return false;
2582    }
2583
2584    // No need for OpenEntry() if the current entry is the one we want.
2585    if (ze != ze_data && !zs.OpenEntry(*ze_data)) {
2586        wxMessageBox(wxT("Couldn't read DEM data from .zip file"));
2587        delete ze_data;
2588        return false;
2589    }
2590
2591    bool know_size = (size != 0);
2592    if (!size)
2593        size = DEFAULT_HGT_SIZE;
2594    dem = new unsigned short[size / 2];
2595    if (skipbytes) {
2596        if (zs.SeekI(skipbytes, wxFromStart) == ::wxInvalidOffset) {
2597            while (skipbytes) {
2598                unsigned long to_read = skipbytes;
2599                if (size < to_read) to_read = size;
2600                zs.Read(reinterpret_cast<char *>(dem), to_read);
2601                size_t c = zs.LastRead();
2602                if (c == 0) {
2603                    wxMessageBox(wxT("Failed to skip terrain data header"));
2604                    break;
2605                }
2606                skipbytes -= c;
2607            }
2608        }
2609    }
2610
2611#if wxCHECK_VERSION(2,9,5)
2612    if (!zs.ReadAll(dem, size)) {
2613        if (!know_size && size > 0) {
2614            size = zs.LastRead();
2615            dem_width = dem_height = sqrt(size / 2);
2616            if (dem_width * dem_height * 2 == size) {
2617                step_x = step_y = 1.0 / dem_width;
2618                goto size_ok;
2619            }
2620        }
2621        // FIXME: On __WXMSW__ currently we fail to
2622        // read any data from files in zips.
2623        wxMessageBox(wxT("Failed to read terrain data"));
2624        return false;
2625size_ok: ;
2626    }
2627#else
2628    char * p = reinterpret_cast<char *>(dem);
2629    while (size) {
2630        zs.Read(p, size);
2631        size_t c = zs.LastRead();
2632        if (c == 0) {
2633            if (!know_size && size != DEFAULT_HGT_SIZE) {
2634                size = DEFAULT_HGT_SIZE - size;
2635                dem_width = dem_height = sqrt(size / 2);
2636                if (dem_width * dem_height * 2 == size) {
2637                    step_x = step_y = 1.0 / dem_width;
2638                    break;
2639                }
2640            }
2641            wxMessageBox(wxT("Failed to read terrain data"));
2642            return false;
2643        }
2644        p += c;
2645        size -= c;
2646    }
2647#endif
2648    if (!know_size) {
2649        dem_width = dem_height = DEFAULT_HGT_DIM;
2650        step_x = step_y = 1.0 / DEFAULT_HGT_DIM;
2651    }
2652
2653    delete ze_data;
2654
2655    InvalidateList(LIST_TERRAIN);
2656    ForceRefresh();
2657    return true;
2658}
2659
2660void GfxCore::DrawTerrainTriangle(const Vector3 & a, const Vector3 & b, const Vector3 & c)
2661{
2662    Vector3 n = (b - a) * (c - a);
2663    n.normalise();
2664    Double factor = dot(n, light) * .95 + .05;
2665    SetColour(col_WHITE, factor);
2666    PlaceVertex(a);
2667    PlaceVertex(b);
2668    PlaceVertex(c);
2669    ++n_tris;
2670}
2671
2672void GfxCore::DrawTerrain()
2673{
2674    if (!dem) return;
2675
2676    wxBusyCursor hourglass;
2677
2678    // Draw terrain to twice the extent, or at least 1km.
2679    double r_sqrd = sqrd(max(m_Parent->GetExtent().magnitude(), 1000.0));
2680#define WGS84_DATUM_STRING "+proj=longlat +ellps=WGS84 +datum=WGS84"
2681    static projPJ pj_in = pj_init_plus(WGS84_DATUM_STRING);
2682    if (!pj_in) {
2683        ToggleTerrain();
2684        error(/*Failed to initialise input coordinate system “%s”*/287, WGS84_DATUM_STRING);
2685        return;
2686    }
2687    static projPJ pj_out = pj_init_plus(m_Parent->m_cs_proj.c_str());
2688    if (!pj_out) {
2689        ToggleTerrain();
2690        error(/*Failed to initialise output coordinate system “%s”*/288, (const char *)m_Parent->m_cs_proj.c_str());
2691        return;
2692    }
2693    n_tris = 0;
2694    SetAlpha(0.3);
2695    BeginTriangles();
2696    const Vector3 & off = m_Parent->GetOffset();
2697    vector<Vector3> prevcol(dem_height + 1);
2698    for (size_t x = 0; x < dem_width; ++x) {
2699        double X_ = (o_x + x * step_x) * DEG_TO_RAD;
2700        Vector3 prev;
2701        for (size_t y = 0; y < dem_height; ++y) {
2702            unsigned short elev = dem[x + y * dem_width];
2703#ifdef WORDS_BIGENDIAN
2704            const bool MACHINE_BIGENDIAN = true;
2705#else
2706            const bool MACHINE_BIGENDIAN = false;
2707#endif
2708            if (bigendian != MACHINE_BIGENDIAN) {
2709#if defined __GNUC__ && (__GNUC__ * 100 + __GNUC_MINOR__ >= 408)
2710                elev = __builtin_bswap16(elev);
2711#else
2712                elev = (elev >> 8) | (elev << 8);
2713#endif
2714            }
2715            double Z = (short)elev;
2716            Vector3 pt;
2717            if (Z == nodata_value) {
2718                pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2719            } else {
2720                double X = X_;
2721                double Y = (o_y - y * step_y) * DEG_TO_RAD;
2722                pj_transform(pj_in, pj_out, 1, 1, &X, &Y, &Z);
2723                pt = Vector3(X, Y, Z) - off;
2724                double dist_2 = sqrd(pt.GetX()) + sqrd(pt.GetY());
2725                if (dist_2 > r_sqrd) {
2726                    pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2727                }
2728            }
2729            if (x > 0 && y > 0) {
2730                const Vector3 & a = prevcol[y - 1];
2731                const Vector3 & b = prevcol[y];
2732                // If all points are valid, split the quadrilateral into
2733                // triangles along the shorter 3D diagonal, which typically
2734                // looks better:
2735                //
2736                //               ----->
2737                //     prev---a    x     prev---a
2738                //   |   |P  /|            |\  S|
2739                // y |   |  / |    or      | \  |
2740                //   V   | /  |            |  \ |
2741                //       |/  Q|            |R  \|
2742                //       b----pt           b----pt
2743                //
2744                //       FORWARD           BACKWARD
2745                enum { NONE = 0, P = 1, Q = 2, R = 4, S = 8, ALL = P|Q|R|S };
2746                int valid =
2747                    ((prev.GetZ() != DBL_MAX)) |
2748                    ((a.GetZ() != DBL_MAX) << 1) |
2749                    ((b.GetZ() != DBL_MAX) << 2) |
2750                    ((pt.GetZ() != DBL_MAX) << 3);
2751                static const int tris_map[16] = {
2752                    NONE, // nothing valid
2753                    NONE, // prev
2754                    NONE, // a
2755                    NONE, // a, prev
2756                    NONE, // b
2757                    NONE, // b, prev
2758                    NONE, // b, a
2759                    P, // b, a, prev
2760                    NONE, // pt
2761                    NONE, // pt, prev
2762                    NONE, // pt, a
2763                    S, // pt, a, prev
2764                    NONE, // pt, b
2765                    R, // pt, b, prev
2766                    Q, // pt, b, a
2767                    ALL, // pt, b, a, prev
2768                };
2769                int tris = tris_map[valid];
2770                if (tris == ALL) {
2771                    // All points valid.
2772                    if ((a - b).magnitude() < (prev - pt).magnitude()) {
2773                        tris = P | Q;
2774                    } else {
2775                        tris = R | S;
2776                    }
2777                }
2778                if (tris & P)
2779                    DrawTerrainTriangle(a, prev, b);
2780                if (tris & Q)
2781                    DrawTerrainTriangle(a, b, pt);
2782                if (tris & R)
2783                    DrawTerrainTriangle(pt, prev, b);
2784                if (tris & S)
2785                    DrawTerrainTriangle(a, prev, pt);
2786            }
2787            prev = prevcol[y];
2788            prevcol[y].assign(pt);
2789        }
2790    }
2791    EndTriangles();
2792    SetAlpha(1.0);
2793}
2794
2795// Plot blobs.
2796void GfxCore::GenerateBlobsDisplayList()
2797{
2798    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2799          m_Parent->GetNumHighlightedPts()))
2800        return;
2801
2802    // Plot blobs.
2803    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2804    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2805    BeginBlobs();
2806    while (pos != m_Parent->GetLabelsEnd()) {
2807        const LabelInfo* label = *pos++;
2808
2809        // When more than one flag is set on a point:
2810        // search results take priority over entrance highlighting
2811        // which takes priority over fixed point
2812        // highlighting, which in turn takes priority over exported
2813        // point highlighting.
2814
2815        if (!((m_Surface && label->IsSurface()) ||
2816              (m_Legs && label->IsUnderground()) ||
2817              (!label->IsSurface() && !label->IsUnderground()))) {
2818            // if this station isn't to be displayed, skip to the next
2819            // (last case is for stns with no legs attached)
2820            continue;
2821        }
2822
2823        gla_colour col;
2824
2825        if (label->IsHighLighted()) {
2826            col = col_YELLOW;
2827        } else if (m_Entrances && label->IsEntrance()) {
2828            col = col_GREEN;
2829        } else if (m_FixedPts && label->IsFixedPt()) {
2830            col = col_RED;
2831        } else if (m_ExportedPts && label->IsExportedPt()) {
2832            col = col_TURQUOISE;
2833        } else {
2834            continue;
2835        }
2836
2837        // Stations are sorted by blob type, so colour changes are infrequent.
2838        if (col != prev_col) {
2839            SetColour(col);
2840            prev_col = col;
2841        }
2842        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
2843    }
2844    EndBlobs();
2845}
2846
2847void GfxCore::DrawIndicators()
2848{
2849    // Draw colour key.
2850    if (m_ColourKey) {
2851        drawing_list key_list = LIST_LIMIT_;
2852        switch (m_ColourBy) {
2853            case COLOUR_BY_DEPTH:
2854                key_list = LIST_DEPTH_KEY; break;
2855            case COLOUR_BY_DATE:
2856                key_list = LIST_DATE_KEY; break;
2857            case COLOUR_BY_ERROR:
2858                key_list = LIST_ERROR_KEY; break;
2859            case COLOUR_BY_GRADIENT:
2860                key_list = LIST_GRADIENT_KEY; break;
2861            case COLOUR_BY_LENGTH:
2862                key_list = LIST_LENGTH_KEY; break;
2863        }
2864        if (key_list != LIST_LIMIT_) {
2865            DrawList2D(key_list, GetXSize() - KEY_OFFSET_X,
2866                       GetYSize() - KEY_OFFSET_Y, 0);
2867        }
2868    }
2869
2870    // Draw compass or elevation/heading indicators.
2871    if (m_Compass || m_Clino) {
2872        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
2873    }
2874
2875    // Draw scalebar.
2876    if (m_Scalebar) {
2877        DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
2878    }
2879}
2880
2881void GfxCore::PlaceVertexWithColour(const Vector3 & v,
2882                                    glaTexCoord tex_x, glaTexCoord tex_y,
2883                                    Double factor)
2884{
2885    SetColour(col_WHITE, factor);
2886    PlaceVertex(v, tex_x, tex_y);
2887}
2888
2889void GfxCore::SetDepthColour(Double z, Double factor) {
2890    // Set the drawing colour based on the altitude.
2891    Double z_ext = m_Parent->GetDepthExtent();
2892
2893    z -= m_Parent->GetDepthMin();
2894    // points arising from tubes may be slightly outside the limits...
2895    if (z < 0) z = 0;
2896    if (z > z_ext) z = z_ext;
2897
2898    if (z == 0) {
2899        SetColour(GetPen(0), factor);
2900        return;
2901    }
2902
2903    assert(z_ext > 0.0);
2904    Double how_far = z / z_ext;
2905    assert(how_far >= 0.0);
2906    assert(how_far <= 1.0);
2907
2908    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2909    GLAPen pen1 = GetPen(band);
2910    if (band < GetNumColourBands() - 1) {
2911        const GLAPen& pen2 = GetPen(band + 1);
2912
2913        Double interval = z_ext / (GetNumColourBands() - 1);
2914        Double into_band = z / interval - band;
2915
2916//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2917//             z_offset, interval, band);
2918        // FIXME: why do we need to clamp here?  Is it because the walls can
2919        // extend further up/down than the centre-line?
2920        if (into_band < 0.0) into_band = 0.0;
2921        if (into_band > 1.0) into_band = 1.0;
2922        assert(into_band >= 0.0);
2923        assert(into_band <= 1.0);
2924
2925        pen1.Interpolate(pen2, into_band);
2926    }
2927    SetColour(pen1, factor);
2928}
2929
2930void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2931{
2932    SetDepthColour(v.GetZ(), factor);
2933    PlaceVertex(v);
2934}
2935
2936void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
2937                                         glaTexCoord tex_x, glaTexCoord tex_y,
2938                                         Double factor)
2939{
2940    SetDepthColour(v.GetZ(), factor);
2941    PlaceVertex(v, tex_x, tex_y);
2942}
2943
2944void GfxCore::SplitLineAcrossBands(int band, int band2,
2945                                   const Vector3 &p, const Vector3 &q,
2946                                   Double factor)
2947{
2948    const int step = (band < band2) ? 1 : -1;
2949    for (int i = band; i != band2; i += step) {
2950        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
2951
2952        // Find the intersection point of the line p -> q
2953        // with the plane parallel to the xy-plane with z-axis intersection z.
2954        assert(q.GetZ() - p.GetZ() != 0.0);
2955
2956        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
2957//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
2958
2959        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
2960        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
2961
2962        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
2963    }
2964}
2965
2966int GfxCore::GetDepthColour(Double z) const
2967{
2968    // Return the (0-based) depth colour band index for a z-coordinate.
2969    Double z_ext = m_Parent->GetDepthExtent();
2970    z -= m_Parent->GetDepthMin();
2971    // We seem to get rounding differences causing z to sometimes be slightly
2972    // less than GetDepthMin() here, and it can certainly be true for passage
2973    // tubes, so just clamp the value to 0.
2974    if (z <= 0) return 0;
2975    // We seem to get rounding differences causing z to sometimes exceed z_ext
2976    // by a small amount here (see: http://trac.survex.com/ticket/26) and it
2977    // can certainly be true for passage tubes, so just clamp the value.
2978    if (z >= z_ext) return GetNumColourBands() - 1;
2979    return int(z / z_ext * (GetNumColourBands() - 1));
2980}
2981
2982Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
2983{
2984    // Return the z-coordinate of the depth colour boundary between
2985    // two adjacent depth colour bands (specified by 0-based indices).
2986
2987    assert((a == b - 1) || (a == b + 1));
2988    if (GetNumColourBands() == 1) return 0;
2989
2990    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
2991    Double z_ext = m_Parent->GetDepthExtent();
2992    return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
2993}
2994
2995void GfxCore::AddPolyline(const traverse & centreline)
2996{
2997    BeginPolyline();
2998    SetColour(col_WHITE);
2999    vector<PointInfo>::const_iterator i = centreline.begin();
3000    PlaceVertex(*i);
3001    ++i;
3002    while (i != centreline.end()) {
3003        PlaceVertex(*i);
3004        ++i;
3005    }
3006    EndPolyline();
3007}
3008
3009void GfxCore::AddPolylineShadow(const traverse & centreline)
3010{
3011    BeginPolyline();
3012    const double z = -0.5 * m_Parent->GetZExtent();
3013    vector<PointInfo>::const_iterator i = centreline.begin();
3014    PlaceVertex(i->GetX(), i->GetY(), z);
3015    ++i;
3016    while (i != centreline.end()) {
3017        PlaceVertex(i->GetX(), i->GetY(), z);
3018        ++i;
3019    }
3020    EndPolyline();
3021}
3022
3023void GfxCore::AddPolylineDepth(const traverse & centreline)
3024{
3025    BeginPolyline();
3026    vector<PointInfo>::const_iterator i, prev_i;
3027    i = centreline.begin();
3028    int band0 = GetDepthColour(i->GetZ());
3029    PlaceVertexWithDepthColour(*i);
3030    prev_i = i;
3031    ++i;
3032    while (i != centreline.end()) {
3033        int band = GetDepthColour(i->GetZ());
3034        if (band != band0) {
3035            SplitLineAcrossBands(band0, band, *prev_i, *i);
3036            band0 = band;
3037        }
3038        PlaceVertexWithDepthColour(*i);
3039        prev_i = i;
3040        ++i;
3041    }
3042    EndPolyline();
3043}
3044
3045void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
3046                               const Vector3 &c, const Vector3 &d)
3047{
3048    Vector3 normal = (a - c) * (d - b);
3049    normal.normalise();
3050    Double factor = dot(normal, light) * .3 + .7;
3051    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
3052    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
3053    // FIXME: should plot triangles instead to avoid rendering glitches.
3054    BeginQuadrilaterals();
3055    PlaceVertexWithColour(a, 0, 0, factor);
3056    PlaceVertexWithColour(b, w, 0, factor);
3057    PlaceVertexWithColour(c, w, h, factor);
3058    PlaceVertexWithColour(d, 0, h, factor);
3059    EndQuadrilaterals();
3060}
3061
3062void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
3063                                    const Vector3 &c, const Vector3 &d)
3064{
3065    Vector3 normal = (a - c) * (d - b);
3066    normal.normalise();
3067    Double factor = dot(normal, light) * .3 + .7;
3068    int a_band, b_band, c_band, d_band;
3069    a_band = GetDepthColour(a.GetZ());
3070    a_band = min(max(a_band, 0), GetNumColourBands());
3071    b_band = GetDepthColour(b.GetZ());
3072    b_band = min(max(b_band, 0), GetNumColourBands());
3073    c_band = GetDepthColour(c.GetZ());
3074    c_band = min(max(c_band, 0), GetNumColourBands());
3075    d_band = GetDepthColour(d.GetZ());
3076    d_band = min(max(d_band, 0), GetNumColourBands());
3077    // All this splitting is incorrect - we need to make a separate polygon
3078    // for each depth band...
3079    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
3080    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
3081    BeginPolygon();
3082////    PlaceNormal(normal);
3083    PlaceVertexWithDepthColour(a, 0, 0, factor);
3084    if (a_band != b_band) {
3085        SplitLineAcrossBands(a_band, b_band, a, b, factor);
3086    }
3087    PlaceVertexWithDepthColour(b, w, 0, factor);
3088    if (b_band != c_band) {
3089        SplitLineAcrossBands(b_band, c_band, b, c, factor);
3090    }
3091    PlaceVertexWithDepthColour(c, w, h, factor);
3092    if (c_band != d_band) {
3093        SplitLineAcrossBands(c_band, d_band, c, d, factor);
3094    }
3095    PlaceVertexWithDepthColour(d, 0, h, factor);
3096    if (d_band != a_band) {
3097        SplitLineAcrossBands(d_band, a_band, d, a, factor);
3098    }
3099    EndPolygon();
3100}
3101
3102void GfxCore::SetColourFromDate(int date, Double factor)
3103{
3104    // Set the drawing colour based on a date.
3105
3106    if (date == -1) {
3107        // Undated.
3108        SetColour(col_WHITE, factor);
3109        return;
3110    }
3111
3112    int date_offset = date - m_Parent->GetDateMin();
3113    if (date_offset == 0) {
3114        // Earliest date - handle as a special case for the single date case.
3115        SetColour(GetPen(0), factor);
3116        return;
3117    }
3118
3119    int date_ext = m_Parent->GetDateExtent();
3120    Double how_far = (Double)date_offset / date_ext;
3121    assert(how_far >= 0.0);
3122    assert(how_far <= 1.0);
3123    SetColourFrom01(how_far, factor);
3124}
3125
3126void GfxCore::AddPolylineDate(const traverse & centreline)
3127{
3128    BeginPolyline();
3129    vector<PointInfo>::const_iterator i, prev_i;
3130    i = centreline.begin();
3131    int date = i->GetDate();
3132    SetColourFromDate(date, 1.0);
3133    PlaceVertex(*i);
3134    prev_i = i;
3135    while (++i != centreline.end()) {
3136        int newdate = i->GetDate();
3137        if (newdate != date) {
3138            EndPolyline();
3139            BeginPolyline();
3140            date = newdate;
3141            SetColourFromDate(date, 1.0);
3142            PlaceVertex(*prev_i);
3143        }
3144        PlaceVertex(*i);
3145        prev_i = i;
3146    }
3147    EndPolyline();
3148}
3149
3150static int static_date_hack; // FIXME
3151
3152void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
3153                                   const Vector3 &c, const Vector3 &d)
3154{
3155    Vector3 normal = (a - c) * (d - b);
3156    normal.normalise();
3157    Double factor = dot(normal, light) * .3 + .7;
3158    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3159    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3160    // FIXME: should plot triangles instead to avoid rendering glitches.
3161    BeginQuadrilaterals();
3162////    PlaceNormal(normal);
3163    SetColourFromDate(static_date_hack, factor);
3164    PlaceVertex(a, 0, 0);
3165    PlaceVertex(b, w, 0);
3166    PlaceVertex(c, w, h);
3167    PlaceVertex(d, 0, h);
3168    EndQuadrilaterals();
3169}
3170
3171static double static_E_hack; // FIXME
3172
3173void GfxCore::SetColourFromError(double E, Double factor)
3174{
3175    // Set the drawing colour based on an error value.
3176
3177    if (E < 0) {
3178        SetColour(col_WHITE, factor);
3179        return;
3180    }
3181
3182    Double how_far = E / MAX_ERROR;
3183    assert(how_far >= 0.0);
3184    if (how_far > 1.0) how_far = 1.0;
3185    SetColourFrom01(how_far, factor);
3186}
3187
3188void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
3189                                    const Vector3 &c, const Vector3 &d)
3190{
3191    Vector3 normal = (a - c) * (d - b);
3192    normal.normalise();
3193    Double factor = dot(normal, light) * .3 + .7;
3194    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3195    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3196    // FIXME: should plot triangles instead to avoid rendering glitches.
3197    BeginQuadrilaterals();
3198////    PlaceNormal(normal);
3199    SetColourFromError(static_E_hack, factor);
3200    PlaceVertex(a, 0, 0);
3201    PlaceVertex(b, w, 0);
3202    PlaceVertex(c, w, h);
3203    PlaceVertex(d, 0, h);
3204    EndQuadrilaterals();
3205}
3206
3207void GfxCore::AddPolylineError(const traverse & centreline)
3208{
3209    BeginPolyline();
3210    SetColourFromError(centreline.E, 1.0);
3211    vector<PointInfo>::const_iterator i;
3212    for(i = centreline.begin(); i != centreline.end(); ++i) {
3213        PlaceVertex(*i);
3214    }
3215    EndPolyline();
3216}
3217
3218// gradient is in *radians*.
3219void GfxCore::SetColourFromGradient(double gradient, Double factor)
3220{
3221    // Set the drawing colour based on the gradient of the leg.
3222
3223    const Double GRADIENT_MAX = M_PI_2;
3224    gradient = fabs(gradient);
3225    Double how_far = gradient / GRADIENT_MAX;
3226    SetColourFrom01(how_far, factor);
3227}
3228
3229void GfxCore::AddPolylineGradient(const traverse & centreline)
3230{
3231    vector<PointInfo>::const_iterator i, prev_i;
3232    i = centreline.begin();
3233    prev_i = i;
3234    while (++i != centreline.end()) {
3235        BeginPolyline();
3236        SetColourFromGradient((*i - *prev_i).gradient(), 1.0);
3237        PlaceVertex(*prev_i);
3238        PlaceVertex(*i);
3239        prev_i = i;
3240        EndPolyline();
3241    }
3242}
3243
3244static double static_gradient_hack; // FIXME
3245
3246void GfxCore::AddQuadrilateralGradient(const Vector3 &a, const Vector3 &b,
3247                                       const Vector3 &c, const Vector3 &d)
3248{
3249    Vector3 normal = (a - c) * (d - b);
3250    normal.normalise();
3251    Double factor = dot(normal, light) * .3 + .7;
3252    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3253    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3254    // FIXME: should plot triangles instead to avoid rendering glitches.
3255    BeginQuadrilaterals();
3256////    PlaceNormal(normal);
3257    SetColourFromGradient(static_gradient_hack, factor);
3258    PlaceVertex(a, 0, 0);
3259    PlaceVertex(b, w, 0);
3260    PlaceVertex(c, w, h);
3261    PlaceVertex(d, 0, h);
3262    EndQuadrilaterals();
3263}
3264
3265void GfxCore::SetColourFromLength(double length, Double factor)
3266{
3267    // Set the drawing colour based on log(length_of_leg).
3268
3269    Double log_len = log10(length);
3270    Double how_far = log_len / LOG_LEN_MAX;
3271    how_far = max(how_far, 0.0);
3272    how_far = min(how_far, 1.0);
3273    SetColourFrom01(how_far, factor);
3274}
3275
3276void GfxCore::SetColourFrom01(double how_far, Double factor)
3277{
3278    double b;
3279    double into_band = modf(how_far * (GetNumColourBands() - 1), &b);
3280    int band(b);
3281    GLAPen pen1 = GetPen(band);
3282    // With 24bit colour, interpolating by less than this can have no effect.
3283    if (into_band >= 1.0 / 512.0) {
3284        const GLAPen& pen2 = GetPen(band + 1);
3285        pen1.Interpolate(pen2, into_band);
3286    }
3287    SetColour(pen1, factor);
3288}
3289
3290void GfxCore::AddPolylineLength(const traverse & centreline)
3291{
3292    vector<PointInfo>::const_iterator i, prev_i;
3293    i = centreline.begin();
3294    prev_i = i;
3295    while (++i != centreline.end()) {
3296        BeginPolyline();
3297        SetColourFromLength((*i - *prev_i).magnitude(), 1.0);
3298        PlaceVertex(*prev_i);
3299        PlaceVertex(*i);
3300        prev_i = i;
3301        EndPolyline();
3302    }
3303}
3304
3305static double static_length_hack; // FIXME
3306
3307void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
3308                                     const Vector3 &c, const Vector3 &d)
3309{
3310    Vector3 normal = (a - c) * (d - b);
3311    normal.normalise();
3312    Double factor = dot(normal, light) * .3 + .7;
3313    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3314    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3315    // FIXME: should plot triangles instead to avoid rendering glitches.
3316    BeginQuadrilaterals();
3317////    PlaceNormal(normal);
3318    SetColourFromLength(static_length_hack, factor);
3319    PlaceVertex(a, 0, 0);
3320    PlaceVertex(b, w, 0);
3321    PlaceVertex(c, w, h);
3322    PlaceVertex(d, 0, h);
3323    EndQuadrilaterals();
3324}
3325
3326void
3327GfxCore::SkinPassage(vector<XSect> & centreline, bool draw)
3328{
3329    assert(centreline.size() > 1);
3330    Vector3 U[4];
3331    XSect prev_pt_v;
3332    Vector3 last_right(1.0, 0.0, 0.0);
3333
3334//  FIXME: it's not simple to set the colour of a tube based on error...
3335//    static_E_hack = something...
3336    vector<XSect>::iterator i = centreline.begin();
3337    vector<XSect>::size_type segment = 0;
3338    while (i != centreline.end()) {
3339        // get the coordinates of this vertex
3340        XSect & pt_v = *i++;
3341
3342        double z_pitch_adjust = 0.0;
3343        bool cover_end = false;
3344
3345        Vector3 right, up;
3346
3347        const Vector3 up_v(0.0, 0.0, 1.0);
3348
3349        if (segment == 0) {
3350            assert(i != centreline.end());
3351            // first segment
3352
3353            // get the coordinates of the next vertex
3354            const XSect & next_pt_v = *i;
3355
3356            // calculate vector from this pt to the next one
3357            Vector3 leg_v = next_pt_v - pt_v;
3358
3359            // obtain a vector in the LRUD plane
3360            right = leg_v * up_v;
3361            if (right.magnitude() == 0) {
3362                right = last_right;
3363                // Obtain a second vector in the LRUD plane,
3364                // perpendicular to the first.
3365                //up = right * leg_v;
3366                up = up_v;
3367            } else {
3368                last_right = right;
3369                up = up_v;
3370            }
3371
3372            cover_end = true;
3373            static_date_hack = next_pt_v.GetDate();
3374        } else if (segment + 1 == centreline.size()) {
3375            // last segment
3376
3377            // Calculate vector from the previous pt to this one.
3378            Vector3 leg_v = pt_v - prev_pt_v;
3379
3380            // Obtain a horizontal vector in the LRUD plane.
3381            right = leg_v * up_v;
3382            if (right.magnitude() == 0) {
3383                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
3384                // Obtain a second vector in the LRUD plane,
3385                // perpendicular to the first.
3386                //up = right * leg_v;
3387                up = up_v;
3388            } else {
3389                last_right = right;
3390                up = up_v;
3391            }
3392
3393            cover_end = true;
3394            static_date_hack = pt_v.GetDate();
3395        } else {
3396            assert(i != centreline.end());
3397            // Intermediate segment.
3398
3399            // Get the coordinates of the next vertex.
3400            const XSect & next_pt_v = *i;
3401
3402            // Calculate vectors from this vertex to the
3403            // next vertex, and from the previous vertex to
3404            // this one.
3405            Vector3 leg1_v = pt_v - prev_pt_v;
3406            Vector3 leg2_v = next_pt_v - pt_v;
3407
3408            // Obtain horizontal vectors perpendicular to
3409            // both legs, then normalise and average to get
3410            // a horizontal bisector.
3411            Vector3 r1 = leg1_v * up_v;
3412            Vector3 r2 = leg2_v * up_v;
3413            r1.normalise();
3414            r2.normalise();
3415            right = r1 + r2;
3416            if (right.magnitude() == 0) {
3417                // This is the "mid-pitch" case...
3418                right = last_right;
3419            }
3420            if (r1.magnitude() == 0) {
3421                Vector3 n = leg1_v;
3422                n.normalise();
3423                z_pitch_adjust = n.GetZ();
3424                //up = Vector3(0, 0, leg1_v.GetZ());
3425                //up = right * up;
3426                up = up_v;
3427
3428                // Rotate pitch section to minimise the
3429                // "tortional stress" - FIXME: use
3430                // triangles instead of rectangles?
3431                int shift = 0;
3432                Double maxdotp = 0;
3433
3434                // Scale to unit vectors in the LRUD plane.
3435                right.normalise();
3436                up.normalise();
3437                Vector3 vec = up - right;
3438                for (int orient = 0; orient <= 3; ++orient) {
3439                    Vector3 tmp = U[orient] - prev_pt_v;
3440                    tmp.normalise();
3441                    Double dotp = dot(vec, tmp);
3442                    if (dotp > maxdotp) {
3443                        maxdotp = dotp;
3444                        shift = orient;
3445                    }
3446                }
3447                if (shift) {
3448                    if (shift != 2) {
3449                        Vector3 temp(U[0]);
3450                        U[0] = U[shift];
3451                        U[shift] = U[2];
3452                        U[2] = U[shift ^ 2];
3453                        U[shift ^ 2] = temp;
3454                    } else {
3455                        swap(U[0], U[2]);
3456                        swap(U[1], U[3]);
3457                    }
3458                }
3459#if 0
3460                // Check that the above code actually permuted
3461                // the vertices correctly.
3462                shift = 0;
3463                maxdotp = 0;
3464                for (int j = 0; j <= 3; ++j) {
3465                    Vector3 tmp = U[j] - prev_pt_v;
3466                    tmp.normalise();
3467                    Double dotp = dot(vec, tmp);
3468                    if (dotp > maxdotp) {
3469                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
3470                        shift = j;
3471                    }
3472                }
3473                if (shift) {
3474                    printf("New shift = %d!\n", shift);
3475                    shift = 0;
3476                    maxdotp = 0;
3477                    for (int j = 0; j <= 3; ++j) {
3478                        Vector3 tmp = U[j] - prev_pt_v;
3479                        tmp.normalise();
3480                        Double dotp = dot(vec, tmp);
3481                        printf("    %d : %.8f\n", j, dotp);
3482                    }
3483                }
3484#endif
3485            } else if (r2.magnitude() == 0) {
3486                Vector3 n = leg2_v;
3487                n.normalise();
3488                z_pitch_adjust = n.GetZ();
3489                //up = Vector3(0, 0, leg2_v.GetZ());
3490                //up = right * up;
3491                up = up_v;
3492            } else {
3493                up = up_v;
3494            }
3495            last_right = right;
3496            static_date_hack = pt_v.GetDate();
3497        }
3498
3499        // Scale to unit vectors in the LRUD plane.
3500        right.normalise();
3501        up.normalise();
3502
3503        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
3504
3505        Double l = fabs(pt_v.GetL());
3506        Double r = fabs(pt_v.GetR());
3507        Double u = fabs(pt_v.GetU());
3508        Double d = fabs(pt_v.GetD());
3509
3510        // Produce coordinates of the corners of the LRUD "plane".
3511        Vector3 v[4];
3512        v[0] = pt_v - right * l + up * u;
3513        v[1] = pt_v + right * r + up * u;
3514        v[2] = pt_v + right * r - up * d;
3515        v[3] = pt_v - right * l - up * d;
3516
3517        if (draw) {
3518            const Vector3 & delta = pt_v - prev_pt_v;
3519            static_length_hack = delta.magnitude();
3520            static_gradient_hack = delta.gradient();
3521            if (segment > 0) {
3522                (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3523                (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3524                (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3525                (this->*AddQuad)(v[3], v[0], U[0], U[3]);
3526            }
3527
3528            if (cover_end) {
3529                (this->*AddQuad)(v[3], v[2], v[1], v[0]);
3530            }
3531        }
3532
3533        prev_pt_v = pt_v;
3534        U[0] = v[0];
3535        U[1] = v[1];
3536        U[2] = v[2];
3537        U[3] = v[3];
3538
3539        pt_v.set_right_bearing(deg(atan2(right.GetY(), right.GetX())));
3540
3541        ++segment;
3542    }
3543}
3544
3545void GfxCore::FullScreenMode()
3546{
3547    m_Parent->ViewFullScreen();
3548}
3549
3550bool GfxCore::IsFullScreen() const
3551{
3552    return m_Parent->IsFullScreen();
3553}
3554
3555bool GfxCore::FullScreenModeShowingMenus() const
3556{
3557    return m_Parent->FullScreenModeShowingMenus();
3558}
3559
3560void GfxCore::FullScreenModeShowMenus(bool show)
3561{
3562    m_Parent->FullScreenModeShowMenus(show);
3563}
3564
3565void
3566GfxCore::MoveViewer(double forward, double up, double right)
3567{
3568    double cT = cos(rad(m_TiltAngle));
3569    double sT = sin(rad(m_TiltAngle));
3570    double cP = cos(rad(m_PanAngle));
3571    double sP = sin(rad(m_PanAngle));
3572    Vector3 v_forward(cT * sP, cT * cP, sT);
3573    Vector3 v_up(sT * sP, sT * cP, -cT);
3574    Vector3 v_right(-cP, sP, 0);
3575    assert(fabs(dot(v_forward, v_up)) < 1e-6);
3576    assert(fabs(dot(v_forward, v_right)) < 1e-6);
3577    assert(fabs(dot(v_right, v_up)) < 1e-6);
3578    Vector3 move = v_forward * forward + v_up * up + v_right * right;
3579    AddTranslation(-move);
3580    // Show current position.
3581    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
3582    ForceRefresh();
3583}
3584
3585PresentationMark GfxCore::GetView() const
3586{
3587    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
3588                            m_PanAngle, -m_TiltAngle, m_Scale);
3589}
3590
3591void GfxCore::SetView(const PresentationMark & p)
3592{
3593    m_SwitchingTo = 0;
3594    SetTranslation(p - m_Parent->GetOffset());
3595    m_PanAngle = p.angle;
3596    m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
3597    SetRotation(m_PanAngle, m_TiltAngle);
3598    SetScale(p.scale);
3599    ForceRefresh();
3600}
3601
3602void GfxCore::PlayPres(double speed, bool change_speed) {
3603    if (!change_speed || presentation_mode == 0) {
3604        if (speed == 0.0) {
3605            presentation_mode = 0;
3606            return;
3607        }
3608        presentation_mode = PLAYING;
3609        next_mark = m_Parent->GetPresMark(MARK_FIRST);
3610        SetView(next_mark);
3611        next_mark_time = 0; // There already!
3612        this_mark_total = 0;
3613        pres_reverse = (speed < 0);
3614    }
3615
3616    if (change_speed) pres_speed = speed;
3617
3618    if (speed != 0.0) {
3619        bool new_pres_reverse = (speed < 0);
3620        if (new_pres_reverse != pres_reverse) {
3621            pres_reverse = new_pres_reverse;
3622            if (pres_reverse) {
3623                next_mark = m_Parent->GetPresMark(MARK_PREV);
3624            } else {
3625                next_mark = m_Parent->GetPresMark(MARK_NEXT);
3626            }
3627            swap(this_mark_total, next_mark_time);
3628        }
3629    }
3630}
3631
3632void GfxCore::SetColourBy(int colour_by) {
3633    m_ColourBy = colour_by;
3634    switch (colour_by) {
3635        case COLOUR_BY_DEPTH:
3636            AddQuad = &GfxCore::AddQuadrilateralDepth;
3637            AddPoly = &GfxCore::AddPolylineDepth;
3638            break;
3639        case COLOUR_BY_DATE:
3640            AddQuad = &GfxCore::AddQuadrilateralDate;
3641            AddPoly = &GfxCore::AddPolylineDate;
3642            break;
3643        case COLOUR_BY_ERROR:
3644            AddQuad = &GfxCore::AddQuadrilateralError;
3645            AddPoly = &GfxCore::AddPolylineError;
3646            break;
3647        case COLOUR_BY_GRADIENT:
3648            AddQuad = &GfxCore::AddQuadrilateralGradient;
3649            AddPoly = &GfxCore::AddPolylineGradient;
3650            break;
3651        case COLOUR_BY_LENGTH:
3652            AddQuad = &GfxCore::AddQuadrilateralLength;
3653            AddPoly = &GfxCore::AddPolylineLength;
3654            break;
3655        default: // case COLOUR_BY_NONE:
3656            AddQuad = &GfxCore::AddQuadrilateral;
3657            AddPoly = &GfxCore::AddPolyline;
3658            break;
3659    }
3660
3661    InvalidateList(LIST_UNDERGROUND_LEGS);
3662    InvalidateList(LIST_SURFACE_LEGS);
3663    InvalidateList(LIST_TUBES);
3664
3665    ForceRefresh();
3666}
3667
3668bool GfxCore::ExportMovie(const wxString & fnm)
3669{
3670    int width;
3671    int height;
3672    GetSize(&width, &height);
3673    // Round up to next multiple of 2 (required by ffmpeg).
3674    width += (width & 1);
3675    height += (height & 1);
3676
3677    movie = new MovieMaker();
3678
3679    // FIXME: This should really use fn_str() - currently we probably can't
3680    // save to a Unicode path on wxmsw.
3681    if (!movie->Open(fnm.mb_str(), width, height)) {
3682        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
3683        delete movie;
3684        movie = NULL;
3685        return false;
3686    }
3687
3688    PlayPres(1);
3689    return true;
3690}
3691
3692void
3693GfxCore::OnPrint(const wxString &filename, const wxString &title,
3694                 const wxString &datestamp, time_t datestamp_numeric,
3695                 const wxString &cs_proj,
3696                 bool close_after_print)
3697{
3698    svxPrintDlg * p;
3699    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3700                        datestamp, datestamp_numeric,
3701                        m_PanAngle, m_TiltAngle,
3702                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3703                        m_Entrances, m_FixedPts, m_ExportedPts,
3704                        true, close_after_print);
3705    p->Show(true);
3706}
3707
3708void
3709GfxCore::OnExport(const wxString &filename, const wxString &title,
3710                  const wxString &datestamp, time_t datestamp_numeric,
3711                  const wxString &cs_proj)
3712{
3713    // Fill in "right_bearing" for each cross-section.
3714    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
3715    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
3716    while (trav != tend) {
3717        SkinPassage(*trav, false);
3718        ++trav;
3719    }
3720
3721    svxPrintDlg * p;
3722    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3723                        datestamp, datestamp_numeric,
3724                        m_PanAngle, m_TiltAngle,
3725                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3726                        m_Entrances, m_FixedPts, m_ExportedPts,
3727                        false);
3728    p->Show(true);
3729}
3730
3731static wxCursor
3732make_cursor(const unsigned char * bits, const unsigned char * mask,
3733            int hotx, int hoty)
3734{
3735#if defined __WXMSW__ || defined __WXMAC__
3736# ifdef __WXMAC__
3737    // The default Mac cursor is black with a white edge, so
3738    // invert our custom cursors to match.
3739    char b[128];
3740    for (int i = 0; i < 128; ++i)
3741        b[i] = bits[i] ^ 0xff;
3742# else
3743    const char * b = reinterpret_cast<const char *>(bits);
3744# endif
3745    wxBitmap cursor_bitmap(b, 32, 32);
3746    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
3747    cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
3748    wxImage cursor_image = cursor_bitmap.ConvertToImage();
3749    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
3750    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
3751    return wxCursor(cursor_image);
3752#else
3753    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
3754                    (const char *)mask, wxBLACK, wxWHITE);
3755#endif
3756}
3757
3758const
3759#include "hand.xbm"
3760const
3761#include "handmask.xbm"
3762
3763const
3764#include "brotate.xbm"
3765const
3766#include "brotatemask.xbm"
3767
3768const
3769#include "vrotate.xbm"
3770const
3771#include "vrotatemask.xbm"
3772
3773const
3774#include "rotate.xbm"
3775const
3776#include "rotatemask.xbm"
3777
3778const
3779#include "rotatezoom.xbm"
3780const
3781#include "rotatezoommask.xbm"
3782
3783void
3784GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
3785{
3786    // Check if we're already showing that cursor.
3787    if (current_cursor == new_cursor) return;
3788
3789    current_cursor = new_cursor;
3790    switch (current_cursor) {
3791        case GfxCore::CURSOR_DEFAULT:
3792            GLACanvas::SetCursor(wxNullCursor);
3793            break;
3794        case GfxCore::CURSOR_POINTING_HAND:
3795            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
3796            break;
3797        case GfxCore::CURSOR_DRAGGING_HAND:
3798            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
3799            break;
3800        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
3801            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
3802            break;
3803        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
3804            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
3805            break;
3806        case GfxCore::CURSOR_ROTATE_VERTICALLY:
3807            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
3808            break;
3809        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
3810            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
3811            break;
3812        case GfxCore::CURSOR_ZOOM:
3813            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
3814            break;
3815        case GfxCore::CURSOR_ZOOM_ROTATE:
3816            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
3817            break;
3818    }
3819}
3820
3821bool GfxCore::MeasuringLineActive() const
3822{
3823    if (Animating()) return false;
3824    return HereIsReal() || m_there;
3825}
3826
3827bool GfxCore::HandleRClick(wxPoint point)
3828{
3829    if (PointWithinCompass(point)) {
3830        // Pop up menu.
3831        wxMenu menu;
3832        /* TRANSLATORS: View *looking* North */
3833        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
3834        /* TRANSLATORS: View *looking* East */
3835        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
3836        /* TRANSLATORS: View *looking* South */
3837        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
3838        /* TRANSLATORS: View *looking* West */
3839        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
3840        menu.AppendSeparator();
3841        /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
3842        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
3843        /* TRANSLATORS: tickable menu item in View menu.
3844         *
3845         * Degrees are the angular measurement where there are 360 in a full
3846         * circle. */
3847        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3848        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3849        PopupMenu(&menu);
3850        return true;
3851    }
3852
3853    if (PointWithinClino(point)) {
3854        // Pop up menu.
3855        wxMenu menu;
3856        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
3857        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
3858        menu.AppendSeparator();
3859        /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
3860        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
3861        /* TRANSLATORS: tickable menu item in View menu.
3862         *
3863         * Degrees are the angular measurement where there are 360 in a full
3864         * circle. */
3865        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3866        /* TRANSLATORS: tickable menu item in View menu.
3867         *
3868         * Show the tilt of the survey as a percentage gradient (100% = 45
3869         * degrees = 50 grad). */
3870        menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
3871        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3872        PopupMenu(&menu);
3873        return true;
3874    }
3875
3876    if (PointWithinScaleBar(point)) {
3877        // Pop up menu.
3878        wxMenu menu;
3879        /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
3880        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
3881        /* TRANSLATORS: tickable menu item in View menu.
3882         *
3883         * "Metric" here means metres, km, etc (rather than feet, miles, etc)
3884         */
3885        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3886        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3887        PopupMenu(&menu);
3888        return true;
3889    }
3890
3891    if (PointWithinColourKey(point)) {
3892        // Pop up menu.
3893        wxMenu menu;
3894        menu.AppendCheckItem(menu_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
3895        menu.AppendCheckItem(menu_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
3896        menu.AppendCheckItem(menu_COLOUR_BY_ERROR, wmsg(/*Colour by &Error*/289));
3897        menu.AppendCheckItem(menu_COLOUR_BY_GRADIENT, wmsg(/*Colour by &Gradient*/85));
3898        menu.AppendCheckItem(menu_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
3899        menu.AppendSeparator();
3900        /* TRANSLATORS: Menu item which turns off the colour key.
3901         * The "Colour Key" is the thing in aven showing which colour
3902         * corresponds to which depth, date, survey closure error, etc. */
3903        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
3904        if (m_ColourBy == COLOUR_BY_DEPTH || m_ColourBy == COLOUR_BY_LENGTH)
3905            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3906        else if (m_ColourBy == COLOUR_BY_GRADIENT)
3907            menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3908        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3909        PopupMenu(&menu);
3910        return true;
3911    }
3912
3913    return false;
3914}
3915
3916void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
3917{
3918    if (centred) {
3919        p1.x = p2.x + (p1.x - p2.x) * 2;
3920        p1.y = p2.y + (p1.y - p2.y) * 2;
3921    }
3922    if (aspect) {
3923#if 0 // FIXME: This needs more work.
3924        int sx = GetXSize();
3925        int sy = GetYSize();
3926        int dx = p1.x - p2.x;
3927        int dy = p1.y - p2.y;
3928        int dy_new = dx * sy / sx;
3929        if (abs(dy_new) >= abs(dy)) {
3930            p1.y += (dy_new - dy) / 2;
3931            p2.y -= (dy_new - dy) / 2;
3932        } else {
3933            int dx_new = dy * sx / sy;
3934            p1.x += (dx_new - dx) / 2;
3935            p2.x -= (dx_new - dx) / 2;
3936        }
3937#endif
3938    }
3939    zoombox.set(p1, p2);
3940    ForceRefresh();
3941}
3942
3943void GfxCore::ZoomBoxGo()
3944{
3945    if (!zoombox.active()) return;
3946
3947    int width = GetXSize();
3948    int height = GetYSize();
3949
3950    TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
3951                  -0.5 * (zoombox.y1 + zoombox.y2 - height));
3952    int box_w = abs(zoombox.x1 - zoombox.x2);
3953    int box_h = abs(zoombox.y1 - zoombox.y2);
3954
3955    double factor = min(double(width) / box_w, double(height) / box_h);
3956
3957    zoombox.unset();
3958
3959    SetScale(GetScale() * factor);
3960}
Note: See TracBrowser for help on using the repository browser.