source: git/src/gfxcore.cc @ 415cbe4

stereo
Last change on this file since 415cbe4 was 415cbe4, checked in by Olly Betts <olly@…>, 6 years ago

Fix defaulting to perspective view

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