source: git/src/gfxcore.cc @ 4938bcd

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

lib/icons/Makefile.am,lib/icons/solid-surface.png,
lib/icons/solid_surface.xpm,lib/survex.pot,src/: Add UI for toggling
terrain on and off.

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