source: git/src/gfxcore.cc @ c2fa50c

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

src/gfxcore.cc: When reading terrain data from a .zip file, report an
error if the .zip file is bad, or if it doesn't contain any terrain
data we recognise.

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