source: git/src/gfxcore.cc @ 1ae34d6

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

src/gfxcore.cc: Fix reversed check for endian-ness of .bil files.

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