source: git/src/gfxcore.cc @ db71ab5

line_contentsstereotravis-osx
Last change on this file since db71ab5 was db71ab5, checked in by Olly Betts <olly@…>, 5 years ago

src/gfxcore.cc: Remove unnecessary clamping when colouring by date or
error, due to cut-and-pasting code from the colour by depth case.

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