source: git/src/gfxcore.cc @ 5a7597a

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernlogstereowalls-datawalls-data-hanging-as-warning
Last change on this file since 5a7597a was 5a7597a, checked in by Olly Betts <olly@…>, 9 years ago

src/gfxcore.cc: Wrap the rotation angle to the range [0,360)
properly, rather than only if it's off by at most 360 either way.

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