source: git/src/gfxcore.cc @ 54fbad8

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

src/gfxcore.cc: Fix printf format/type mismatch.

  • Property mode set to 100644
File size: 105.8 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::ToggleTerrain()
2262{
2263    ToggleFlag(&m_Terrain);
2264    if (m_Terrain && !dem) {
2265        wxCommandEvent dummy;
2266        m_Parent->OnOpenTerrain(dummy);
2267    }
2268}
2269
2270void GfxCore::ToggleFatFinger()
2271{
2272    if (sqrd_measure_threshold == sqrd(MEASURE_THRESHOLD)) {
2273        sqrd_measure_threshold = sqrd(5 * MEASURE_THRESHOLD);
2274        wxMessageBox(wxT("Fat finger enabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2275    } else {
2276        sqrd_measure_threshold = sqrd(MEASURE_THRESHOLD);
2277        wxMessageBox(wxT("Fat finger disabled"), wxT("Aven Debug"), wxOK | wxICON_INFORMATION);
2278    }
2279}
2280
2281void GfxCore::ClearTreeSelection()
2282{
2283    m_Parent->ClearTreeSelection();
2284}
2285
2286void GfxCore::CentreOn(const Point &p)
2287{
2288    SetTranslation(-p);
2289    m_HitTestGridValid = false;
2290
2291    ForceRefresh();
2292}
2293
2294void GfxCore::ForceRefresh()
2295{
2296    Refresh(false);
2297}
2298
2299void GfxCore::GenerateList(unsigned int l)
2300{
2301    assert(m_HaveData);
2302
2303    switch (l) {
2304        case LIST_COMPASS:
2305            DrawCompass();
2306            break;
2307        case LIST_CLINO:
2308            DrawClino();
2309            break;
2310        case LIST_CLINO_BACK:
2311            DrawClinoBack();
2312            break;
2313        case LIST_SCALE_BAR:
2314            DrawScaleBar();
2315            break;
2316        case LIST_DEPTH_KEY:
2317            DrawDepthKey();
2318            break;
2319        case LIST_DATE_KEY:
2320            DrawDateKey();
2321            break;
2322        case LIST_ERROR_KEY:
2323            DrawErrorKey();
2324            break;
2325        case LIST_GRADIENT_KEY:
2326            DrawGradientKey();
2327            break;
2328        case LIST_LENGTH_KEY:
2329            DrawLengthKey();
2330            break;
2331        case LIST_UNDERGROUND_LEGS:
2332            GenerateDisplayList();
2333            break;
2334        case LIST_TUBES:
2335            GenerateDisplayListTubes();
2336            break;
2337        case LIST_SURFACE_LEGS:
2338            GenerateDisplayListSurface();
2339            break;
2340        case LIST_BLOBS:
2341            GenerateBlobsDisplayList();
2342            break;
2343        case LIST_CROSSES: {
2344            BeginCrosses();
2345            SetColour(col_LIGHT_GREY);
2346            list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2347            while (pos != m_Parent->GetLabelsEnd()) {
2348                const LabelInfo* label = *pos++;
2349
2350                if ((m_Surface && label->IsSurface()) ||
2351                    (m_Legs && label->IsUnderground()) ||
2352                    (!label->IsSurface() && !label->IsUnderground())) {
2353                    // Check if this station should be displayed
2354                    // (last case is for stns with no legs attached)
2355                    DrawCross(label->GetX(), label->GetY(), label->GetZ());
2356                }
2357            }
2358            EndCrosses();
2359            break;
2360        }
2361        case LIST_GRID:
2362            DrawGrid();
2363            break;
2364        case LIST_SHADOW:
2365            GenerateDisplayListShadow();
2366            break;
2367        case LIST_TERRAIN:
2368            DrawTerrain();
2369            break;
2370        default:
2371            assert(false);
2372            break;
2373    }
2374}
2375
2376void GfxCore::ToggleSmoothShading()
2377{
2378    GLACanvas::ToggleSmoothShading();
2379    InvalidateList(LIST_TUBES);
2380    ForceRefresh();
2381}
2382
2383void GfxCore::GenerateDisplayList()
2384{
2385    // Generate the display list for the underground legs.
2386    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2387    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2388
2389    if (m_Splays == SPLAYS_SHOW_FADED) {
2390        SetAlpha(0.4);
2391        while (trav != tend) {
2392            if ((*trav).isSplay)
2393                (this->*AddPoly)(*trav);
2394            ++trav;
2395        }
2396        SetAlpha(1.0);
2397        trav = m_Parent->traverses_begin();
2398    }
2399
2400    while (trav != tend) {
2401        if (m_Splays == SPLAYS_SHOW_NORMAL || !(*trav).isSplay)
2402            (this->*AddPoly)(*trav);
2403        ++trav;
2404    }
2405}
2406
2407void GfxCore::GenerateDisplayListTubes()
2408{
2409    // Generate the display list for the tubes.
2410    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
2411    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
2412    while (trav != tend) {
2413        SkinPassage(*trav);
2414        ++trav;
2415    }
2416}
2417
2418void GfxCore::GenerateDisplayListSurface()
2419{
2420    // Generate the display list for the surface legs.
2421    EnableDashedLines();
2422    list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2423    list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
2424    while (trav != tend) {
2425        if (m_ColourBy == COLOUR_BY_ERROR) {
2426            AddPolylineError(*trav);
2427        } else {
2428            AddPolyline(*trav);
2429        }
2430        ++trav;
2431    }
2432    DisableDashedLines();
2433}
2434
2435void GfxCore::GenerateDisplayListShadow()
2436{
2437    SetColour(col_BLACK);
2438    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2439    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2440    while (trav != tend) {
2441        AddPolylineShadow(*trav);
2442        ++trav;
2443    }
2444}
2445
2446bool GfxCore::LoadDEM(const wxString & file)
2447{
2448    if (m_Parent->m_cs_proj.empty()) {
2449        wxMessageBox(wxT("No coordinate system specified in survey data"));
2450        return false;
2451    }
2452
2453    delete [] dem;
2454    dem = NULL;
2455
2456    size_t size = 0;
2457    // Default is to not skip any bytes.
2458    unsigned long skipbytes = 0;
2459    // For .hgt files, default to using filesize to determine.
2460    dem_width = dem_height = 0;
2461    // ESRI say "The default byte order is the same as that of the host machine
2462    // executing the software", but that's stupid so we default to
2463    // little-endian.
2464    bigendian = false;
2465
2466    int fd = open(file.mb_str(), O_RDONLY);
2467    if (fd < 0) {
2468        wxMessageBox(wxT("Failed to open DEM zip"));
2469        return false;
2470    }
2471    wxZipEntry * ze_data = NULL;
2472    wxFileInputStream fs(fd);
2473    wxZipInputStream zs(fs);
2474    wxZipEntry * ze;
2475    while ((ze = zs.GetNextEntry()) != NULL) {
2476        if (!ze->IsDir()) {
2477            const wxString & name = ze->GetName();
2478            if (!ze_data && name.EndsWith(wxT(".hgt"))) {
2479                // SRTM .hgt files are raw binary data, with the filename
2480                // encoding the coordinates.
2481                ze_data = ze;
2482                const char * p = name.mb_str();
2483                char * q;
2484                char dirn = *p++;
2485                o_y = strtoul(p, &q, 10);
2486                p = q;
2487                if (dirn == 'S' || dirn == 's')
2488                    o_y = -o_y;
2489                ++o_y;
2490                dirn = *p++;
2491                o_x = strtoul(p, &q, 10);
2492                if (dirn == 'W' || dirn == 'w')
2493                    o_x = -o_x;
2494                bigendian = true;
2495                nodata_value = -32768;
2496                break;
2497            }
2498
2499            if (!ze_data && name.EndsWith(wxT(".bil"))) {
2500                ze_data = ze;
2501                continue;
2502            }
2503
2504            if (name.EndsWith(wxT(".hdr"))) {
2505                unsigned long nbits;
2506                while (!zs.Eof()) {
2507                    wxString line;
2508                    int ch;
2509                    while ((ch = zs.GetC()) != wxEOF) {
2510                        if (ch == '\n' || ch == '\r') break;
2511                        line += wxChar(ch);
2512                    }
2513#define CHECK(X, COND) \
2514} else if (line.StartsWith(wxT(X" "))) { \
2515size_t v = line.find_first_not_of(wxT(' '), sizeof(X)); \
2516if (v == line.npos || !(COND)) { \
2517err += wxT("Unexpected value for "X); \
2518}
2519                    wxString err;
2520                    unsigned long dummy;
2521                    if (false) {
2522                    // I = little-endian; M = big-endian
2523                    CHECK("BYTEORDER", (bigendian = (line[v] == 'M')) || line[v] == 'I')
2524                    CHECK("LAYOUT", line.substr(v) == wxT("BIL"))
2525                    CHECK("NROWS", line.substr(v).ToCULong(&dem_width))
2526                    CHECK("NCOLS", line.substr(v).ToCULong(&dem_height))
2527                    CHECK("NBANDS", line.substr(v).ToCULong(&dummy) && dummy == 1)
2528                    CHECK("NBITS", line.substr(v).ToCULong(&nbits) && nbits == 16)
2529                    //: BANDROWBYTES   7202
2530                    //: TOTALROWBYTES  7202
2531                    // PIXELTYPE is a GDAL extension, so may not be present.
2532                    CHECK("PIXELTYPE", line.substr(v) == wxT("SIGNEDINT"))
2533                    CHECK("ULXMAP", line.substr(v).ToCDouble(&o_x))
2534                    CHECK("ULYMAP", line.substr(v).ToCDouble(&o_y))
2535                    CHECK("XDIM", line.substr(v).ToCDouble(&step_x))
2536                    CHECK("YDIM", line.substr(v).ToCDouble(&step_y))
2537                    CHECK("NODATA", line.substr(v).ToCLong(&nodata_value))
2538                    CHECK("SKIPBYTES", line.substr(v).ToCULong(&skipbytes))
2539                    }
2540                    if (!err.empty()) {
2541                        wxMessageBox(err);
2542                    }
2543                }
2544                size = ((nbits + 7) / 8) * dem_width * dem_height;
2545            } else if (name.EndsWith(wxT(".prj"))) {
2546                //FIXME: check this matches the datum string we use
2547                //Projection    GEOGRAPHIC
2548                //Datum         WGS84
2549                //Zunits        METERS
2550                //Units         DD
2551                //Spheroid      WGS84
2552                //Xshift        0.0000000000
2553                //Yshift        0.0000000000
2554                //Parameters
2555            }
2556        }
2557        delete ze;
2558    }
2559    if (ze_data && zs.OpenEntry(*ze_data)) {
2560        bool know_size = (size != 0);
2561        if (!size)
2562            size = DEFAULT_HGT_SIZE;
2563        dem = new unsigned short[size / 2];
2564        if (skipbytes) {
2565            if (zs.SeekI(skipbytes, wxFromStart) == ::wxInvalidOffset) {
2566                while (skipbytes) {
2567                    unsigned long to_read = skipbytes;
2568                    if (size < to_read) to_read = size;
2569                    zs.Read(reinterpret_cast<char *>(dem), to_read);
2570                    size_t c = zs.LastRead();
2571                    if (c == 0) {
2572                        wxMessageBox(wxT("Failed to read terrain data"));
2573                        break;
2574                    }
2575                    skipbytes -= c;
2576                }
2577            }
2578        }
2579
2580#if wxCHECK_VERSION(2,9,5)
2581        if (!zs.ReadAll(dem, size)) {
2582            if (!know_size) {
2583                size = zs.LastRead();
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                    goto size_ok;
2588                }
2589            }
2590            wxMessageBox(wxT("Failed to read terrain data"));
2591size_ok: ;
2592        }
2593#else
2594        char * p = reinterpret_cast<char *>(dem);
2595        while (size) {
2596            zs.Read(p, size);
2597            size_t c = zs.LastRead();
2598            if (c == 0) {
2599                if (!know_size) {
2600                    size = DEFAULT_HGT_SIZE - size;
2601                    dem_width = dem_height = sqrt(size / 2);
2602                    if (dem_width * dem_height * 2 == size) {
2603                        step_x = step_y = 1.0 / dem_width;
2604                        break;
2605                    }
2606                }
2607                wxMessageBox(wxT("Failed to read terrain data"));
2608                break;
2609            }
2610            p += c;
2611            size -= c;
2612        }
2613#endif
2614        if (!know_size) {
2615            dem_width = dem_height = DEFAULT_HGT_DIM;
2616            step_x = step_y = 1.0 / DEFAULT_HGT_DIM;
2617        }
2618    }
2619    delete ze_data;
2620
2621    InvalidateList(LIST_TERRAIN);
2622    return true;
2623}
2624
2625void GfxCore::DrawTerrainTriangle(const Vector3 & a, const Vector3 & b, const Vector3 & c)
2626{
2627    Vector3 n = (b - a) * (c - a);
2628    n.normalise();
2629    Double factor = dot(n, light) * .95 + .05;
2630    SetColour(col_WHITE, factor);
2631    PlaceVertex(a);
2632    PlaceVertex(b);
2633    PlaceVertex(c);
2634    ++n_tris;
2635}
2636
2637void GfxCore::DrawTerrain()
2638{
2639    if (!dem) return;
2640
2641    wxBusyCursor hourglass;
2642
2643    // Draw terrain to twice the extent, or at least 1km.
2644    double r_sqrd = sqrd(max(m_Parent->GetExtent().magnitude(), 1000.0));
2645#define WGS84_DATUM_STRING "+proj=longlat +ellps=WGS84 +datum=WGS84"
2646    static projPJ pj_in = pj_init_plus(WGS84_DATUM_STRING);
2647    if (!pj_in) {
2648        ToggleTerrain();
2649        error(/*Failed to initialise input coordinate system “%s”*/287, WGS84_DATUM_STRING);
2650        return;
2651    }
2652    static projPJ pj_out = pj_init_plus(m_Parent->m_cs_proj.c_str());
2653    if (!pj_out) {
2654        ToggleTerrain();
2655        error(/*Failed to initialise output coordinate system “%s”*/288, (const char *)m_Parent->m_cs_proj.c_str());
2656        return;
2657    }
2658    n_tris = 0;
2659    SetAlpha(0.3);
2660    BeginTriangles();
2661    const Vector3 & off = m_Parent->GetOffset();
2662    vector<Vector3> prevcol(dem_height + 1);
2663    for (size_t x = 0; x < dem_width; ++x) {
2664        double X_ = (o_x + x * step_x) * DEG_TO_RAD;
2665        Vector3 prev;
2666        for (size_t y = 0; y < dem_height; ++y) {
2667            unsigned short elev = dem[x + y * dem_width];
2668#ifdef WORDS_BIGENDIAN
2669            const bool MACHINE_BIGENDIAN = true;
2670#else
2671            const bool MACHINE_BIGENDIAN = false;
2672#endif
2673            if (bigendian != MACHINE_BIGENDIAN) {
2674#if defined __GNUC__ && (__GNUC__ * 100 + __GNUC_MINOR__ >= 408)
2675                elev = __builtin_bswap16(elev);
2676#else
2677                elev = (elev >> 8) | (elev << 8);
2678#endif
2679            }
2680            double Z = (short)elev;
2681            Vector3 pt;
2682            if (Z == nodata_value) {
2683                pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2684            } else {
2685                double X = X_;
2686                double Y = (o_y - y * step_y) * DEG_TO_RAD;
2687                pj_transform(pj_in, pj_out, 1, 1, &X, &Y, &Z);
2688                pt = Vector3(X, Y, Z) - off;
2689                double dist_2 = sqrd(pt.GetX()) + sqrd(pt.GetY());
2690                if (dist_2 > r_sqrd) {
2691                    pt = Vector3(DBL_MAX, DBL_MAX, DBL_MAX);
2692                }
2693            }
2694            if (x > 0 && y > 0) {
2695                const Vector3 & a = prevcol[y - 1];
2696                const Vector3 & b = prevcol[y];
2697                // If all points are valid, split the quadrilateral into
2698                // triangles along the shorter 3D diagonal, which typically
2699                // looks better:
2700                //
2701                //               ----->
2702                //     prev---a    x     prev---a
2703                //   |   |P  /|            |\  S|
2704                // y |   |  / |    or      | \  |
2705                //   V   | /  |            |  \ |
2706                //       |/  Q|            |R  \|
2707                //       b----pt           b----pt
2708                //
2709                //       FORWARD           BACKWARD
2710                enum { NONE = 0, P = 1, Q = 2, R = 4, S = 8, ALL = P|Q|R|S };
2711                int valid =
2712                    ((prev.GetZ() != DBL_MAX)) |
2713                    ((a.GetZ() != DBL_MAX) << 1) |
2714                    ((b.GetZ() != DBL_MAX) << 2) |
2715                    ((pt.GetZ() != DBL_MAX) << 3);
2716                static const int tris_map[16] = {
2717                    NONE, // nothing valid
2718                    NONE, // prev
2719                    NONE, // a
2720                    NONE, // a, prev
2721                    NONE, // b
2722                    NONE, // b, prev
2723                    NONE, // b, a
2724                    P, // b, a, prev
2725                    NONE, // pt
2726                    NONE, // pt, prev
2727                    NONE, // pt, a
2728                    S, // pt, a, prev
2729                    NONE, // pt, b
2730                    R, // pt, b, prev
2731                    Q, // pt, b, a
2732                    ALL, // pt, b, a, prev
2733                };
2734                int tris = tris_map[valid];
2735                if (tris == ALL) {
2736                    // All points valid.
2737                    if ((a - b).magnitude() < (prev - pt).magnitude()) {
2738                        tris = P | Q;
2739                    } else {
2740                        tris = R | S;
2741                    }
2742                }
2743                if (tris & P)
2744                    DrawTerrainTriangle(a, prev, b);
2745                if (tris & Q)
2746                    DrawTerrainTriangle(a, b, pt);
2747                if (tris & R)
2748                    DrawTerrainTriangle(pt, prev, b);
2749                if (tris & S)
2750                    DrawTerrainTriangle(a, prev, pt);
2751            }
2752            prev = prevcol[y];
2753            prevcol[y].assign(pt);
2754        }
2755    }
2756    EndTriangles();
2757    SetAlpha(1.0);
2758    printf("%lu DEM triangles drawn\n", (unsigned long)n_tris);
2759}
2760
2761// Plot blobs.
2762void GfxCore::GenerateBlobsDisplayList()
2763{
2764    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2765          m_Parent->GetNumHighlightedPts()))
2766        return;
2767
2768    // Plot blobs.
2769    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2770    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2771    BeginBlobs();
2772    while (pos != m_Parent->GetLabelsEnd()) {
2773        const LabelInfo* label = *pos++;
2774
2775        // When more than one flag is set on a point:
2776        // search results take priority over entrance highlighting
2777        // which takes priority over fixed point
2778        // highlighting, which in turn takes priority over exported
2779        // point highlighting.
2780
2781        if (!((m_Surface && label->IsSurface()) ||
2782              (m_Legs && label->IsUnderground()) ||
2783              (!label->IsSurface() && !label->IsUnderground()))) {
2784            // if this station isn't to be displayed, skip to the next
2785            // (last case is for stns with no legs attached)
2786            continue;
2787        }
2788
2789        gla_colour col;
2790
2791        if (label->IsHighLighted()) {
2792            col = col_YELLOW;
2793        } else if (m_Entrances && label->IsEntrance()) {
2794            col = col_GREEN;
2795        } else if (m_FixedPts && label->IsFixedPt()) {
2796            col = col_RED;
2797        } else if (m_ExportedPts && label->IsExportedPt()) {
2798            col = col_TURQUOISE;
2799        } else {
2800            continue;
2801        }
2802
2803        // Stations are sorted by blob type, so colour changes are infrequent.
2804        if (col != prev_col) {
2805            SetColour(col);
2806            prev_col = col;
2807        }
2808        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
2809    }
2810    EndBlobs();
2811}
2812
2813void GfxCore::DrawIndicators()
2814{
2815    // Draw colour key.
2816    if (m_ColourKey) {
2817        drawing_list key_list = LIST_LIMIT_;
2818        switch (m_ColourBy) {
2819            case COLOUR_BY_DEPTH:
2820                key_list = LIST_DEPTH_KEY; break;
2821            case COLOUR_BY_DATE:
2822                key_list = LIST_DATE_KEY; break;
2823            case COLOUR_BY_ERROR:
2824                key_list = LIST_ERROR_KEY; break;
2825            case COLOUR_BY_GRADIENT:
2826                key_list = LIST_GRADIENT_KEY; break;
2827            case COLOUR_BY_LENGTH:
2828                key_list = LIST_LENGTH_KEY; break;
2829        }
2830        if (key_list != LIST_LIMIT_) {
2831            DrawList2D(key_list, GetXSize() - KEY_OFFSET_X,
2832                       GetYSize() - KEY_OFFSET_Y, 0);
2833        }
2834    }
2835
2836    // Draw compass or elevation/heading indicators.
2837    if (m_Compass || m_Clino) {
2838        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
2839    }
2840
2841    // Draw scalebar.
2842    if (m_Scalebar) {
2843        DrawList2D(LIST_SCALE_BAR, 0, 0, 0);
2844    }
2845}
2846
2847void GfxCore::PlaceVertexWithColour(const Vector3 & v,
2848                                    glaTexCoord tex_x, glaTexCoord tex_y,
2849                                    Double factor)
2850{
2851    SetColour(col_WHITE, factor);
2852    PlaceVertex(v, tex_x, tex_y);
2853}
2854
2855void GfxCore::SetDepthColour(Double z, Double factor) {
2856    // Set the drawing colour based on the altitude.
2857    Double z_ext = m_Parent->GetDepthExtent();
2858
2859    z -= m_Parent->GetDepthMin();
2860    // points arising from tubes may be slightly outside the limits...
2861    if (z < 0) z = 0;
2862    if (z > z_ext) z = z_ext;
2863
2864    if (z == 0) {
2865        SetColour(GetPen(0), factor);
2866        return;
2867    }
2868
2869    assert(z_ext > 0.0);
2870    Double how_far = z / z_ext;
2871    assert(how_far >= 0.0);
2872    assert(how_far <= 1.0);
2873
2874    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2875    GLAPen pen1 = GetPen(band);
2876    if (band < GetNumColourBands() - 1) {
2877        const GLAPen& pen2 = GetPen(band + 1);
2878
2879        Double interval = z_ext / (GetNumColourBands() - 1);
2880        Double into_band = z / interval - band;
2881
2882//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2883//             z_offset, interval, band);
2884        // FIXME: why do we need to clamp here?  Is it because the walls can
2885        // extend further up/down than the centre-line?
2886        if (into_band < 0.0) into_band = 0.0;
2887        if (into_band > 1.0) into_band = 1.0;
2888        assert(into_band >= 0.0);
2889        assert(into_band <= 1.0);
2890
2891        pen1.Interpolate(pen2, into_band);
2892    }
2893    SetColour(pen1, factor);
2894}
2895
2896void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2897{
2898    SetDepthColour(v.GetZ(), factor);
2899    PlaceVertex(v);
2900}
2901
2902void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
2903                                         glaTexCoord tex_x, glaTexCoord tex_y,
2904                                         Double factor)
2905{
2906    SetDepthColour(v.GetZ(), factor);
2907    PlaceVertex(v, tex_x, tex_y);
2908}
2909
2910void GfxCore::SplitLineAcrossBands(int band, int band2,
2911                                   const Vector3 &p, const Vector3 &q,
2912                                   Double factor)
2913{
2914    const int step = (band < band2) ? 1 : -1;
2915    for (int i = band; i != band2; i += step) {
2916        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
2917
2918        // Find the intersection point of the line p -> q
2919        // with the plane parallel to the xy-plane with z-axis intersection z.
2920        assert(q.GetZ() - p.GetZ() != 0.0);
2921
2922        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
2923//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
2924
2925        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
2926        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
2927
2928        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
2929    }
2930}
2931
2932int GfxCore::GetDepthColour(Double z) const
2933{
2934    // Return the (0-based) depth colour band index for a z-coordinate.
2935    Double z_ext = m_Parent->GetDepthExtent();
2936    z -= m_Parent->GetDepthMin();
2937    // We seem to get rounding differences causing z to sometimes be slightly
2938    // less than GetDepthMin() here, and it can certainly be true for passage
2939    // tubes, so just clamp the value to 0.
2940    if (z <= 0) return 0;
2941    // We seem to get rounding differences causing z to sometimes exceed z_ext
2942    // by a small amount here (see: http://trac.survex.com/ticket/26) and it
2943    // can certainly be true for passage tubes, so just clamp the value.
2944    if (z >= z_ext) return GetNumColourBands() - 1;
2945    return int(z / z_ext * (GetNumColourBands() - 1));
2946}
2947
2948Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
2949{
2950    // Return the z-coordinate of the depth colour boundary between
2951    // two adjacent depth colour bands (specified by 0-based indices).
2952
2953    assert((a == b - 1) || (a == b + 1));
2954    if (GetNumColourBands() == 1) return 0;
2955
2956    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
2957    Double z_ext = m_Parent->GetDepthExtent();
2958    return (z_ext * band / (GetNumColourBands() - 1)) + m_Parent->GetDepthMin();
2959}
2960
2961void GfxCore::AddPolyline(const traverse & centreline)
2962{
2963    BeginPolyline();
2964    SetColour(col_WHITE);
2965    vector<PointInfo>::const_iterator i = centreline.begin();
2966    PlaceVertex(*i);
2967    ++i;
2968    while (i != centreline.end()) {
2969        PlaceVertex(*i);
2970        ++i;
2971    }
2972    EndPolyline();
2973}
2974
2975void GfxCore::AddPolylineShadow(const traverse & centreline)
2976{
2977    BeginPolyline();
2978    const double z = -0.5 * m_Parent->GetZExtent();
2979    vector<PointInfo>::const_iterator i = centreline.begin();
2980    PlaceVertex(i->GetX(), i->GetY(), z);
2981    ++i;
2982    while (i != centreline.end()) {
2983        PlaceVertex(i->GetX(), i->GetY(), z);
2984        ++i;
2985    }
2986    EndPolyline();
2987}
2988
2989void GfxCore::AddPolylineDepth(const traverse & centreline)
2990{
2991    BeginPolyline();
2992    vector<PointInfo>::const_iterator i, prev_i;
2993    i = centreline.begin();
2994    int band0 = GetDepthColour(i->GetZ());
2995    PlaceVertexWithDepthColour(*i);
2996    prev_i = i;
2997    ++i;
2998    while (i != centreline.end()) {
2999        int band = GetDepthColour(i->GetZ());
3000        if (band != band0) {
3001            SplitLineAcrossBands(band0, band, *prev_i, *i);
3002            band0 = band;
3003        }
3004        PlaceVertexWithDepthColour(*i);
3005        prev_i = i;
3006        ++i;
3007    }
3008    EndPolyline();
3009}
3010
3011void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
3012                               const Vector3 &c, const Vector3 &d)
3013{
3014    Vector3 normal = (a - c) * (d - b);
3015    normal.normalise();
3016    Double factor = dot(normal, light) * .3 + .7;
3017    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
3018    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
3019    // FIXME: should plot triangles instead to avoid rendering glitches.
3020    BeginQuadrilaterals();
3021    PlaceVertexWithColour(a, 0, 0, factor);
3022    PlaceVertexWithColour(b, w, 0, factor);
3023    PlaceVertexWithColour(c, w, h, factor);
3024    PlaceVertexWithColour(d, 0, h, factor);
3025    EndQuadrilaterals();
3026}
3027
3028void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
3029                                    const Vector3 &c, const Vector3 &d)
3030{
3031    Vector3 normal = (a - c) * (d - b);
3032    normal.normalise();
3033    Double factor = dot(normal, light) * .3 + .7;
3034    int a_band, b_band, c_band, d_band;
3035    a_band = GetDepthColour(a.GetZ());
3036    a_band = min(max(a_band, 0), GetNumColourBands());
3037    b_band = GetDepthColour(b.GetZ());
3038    b_band = min(max(b_band, 0), GetNumColourBands());
3039    c_band = GetDepthColour(c.GetZ());
3040    c_band = min(max(c_band, 0), GetNumColourBands());
3041    d_band = GetDepthColour(d.GetZ());
3042    d_band = min(max(d_band, 0), GetNumColourBands());
3043    // All this splitting is incorrect - we need to make a separate polygon
3044    // for each depth band...
3045    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
3046    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
3047    BeginPolygon();
3048////    PlaceNormal(normal);
3049    PlaceVertexWithDepthColour(a, 0, 0, factor);
3050    if (a_band != b_band) {
3051        SplitLineAcrossBands(a_band, b_band, a, b, factor);
3052    }
3053    PlaceVertexWithDepthColour(b, w, 0, factor);
3054    if (b_band != c_band) {
3055        SplitLineAcrossBands(b_band, c_band, b, c, factor);
3056    }
3057    PlaceVertexWithDepthColour(c, w, h, factor);
3058    if (c_band != d_band) {
3059        SplitLineAcrossBands(c_band, d_band, c, d, factor);
3060    }
3061    PlaceVertexWithDepthColour(d, 0, h, factor);
3062    if (d_band != a_band) {
3063        SplitLineAcrossBands(d_band, a_band, d, a, factor);
3064    }
3065    EndPolygon();
3066}
3067
3068void GfxCore::SetColourFromDate(int date, Double factor)
3069{
3070    // Set the drawing colour based on a date.
3071
3072    if (date == -1) {
3073        // Undated.
3074        SetColour(col_WHITE, factor);
3075        return;
3076    }
3077
3078    int date_offset = date - m_Parent->GetDateMin();
3079    if (date_offset == 0) {
3080        // Earliest date - handle as a special case for the single date case.
3081        SetColour(GetPen(0), factor);
3082        return;
3083    }
3084
3085    int date_ext = m_Parent->GetDateExtent();
3086    Double how_far = (Double)date_offset / date_ext;
3087    assert(how_far >= 0.0);
3088    assert(how_far <= 1.0);
3089    SetColourFrom01(how_far, factor);
3090}
3091
3092void GfxCore::AddPolylineDate(const traverse & centreline)
3093{
3094    BeginPolyline();
3095    vector<PointInfo>::const_iterator i, prev_i;
3096    i = centreline.begin();
3097    int date = i->GetDate();
3098    SetColourFromDate(date, 1.0);
3099    PlaceVertex(*i);
3100    prev_i = i;
3101    while (++i != centreline.end()) {
3102        int newdate = i->GetDate();
3103        if (newdate != date) {
3104            EndPolyline();
3105            BeginPolyline();
3106            date = newdate;
3107            SetColourFromDate(date, 1.0);
3108            PlaceVertex(*prev_i);
3109        }
3110        PlaceVertex(*i);
3111        prev_i = i;
3112    }
3113    EndPolyline();
3114}
3115
3116static int static_date_hack; // FIXME
3117
3118void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
3119                                   const Vector3 &c, const Vector3 &d)
3120{
3121    Vector3 normal = (a - c) * (d - b);
3122    normal.normalise();
3123    Double factor = dot(normal, light) * .3 + .7;
3124    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3125    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3126    // FIXME: should plot triangles instead to avoid rendering glitches.
3127    BeginQuadrilaterals();
3128////    PlaceNormal(normal);
3129    SetColourFromDate(static_date_hack, factor);
3130    PlaceVertex(a, 0, 0);
3131    PlaceVertex(b, w, 0);
3132    PlaceVertex(c, w, h);
3133    PlaceVertex(d, 0, h);
3134    EndQuadrilaterals();
3135}
3136
3137static double static_E_hack; // FIXME
3138
3139void GfxCore::SetColourFromError(double E, Double factor)
3140{
3141    // Set the drawing colour based on an error value.
3142
3143    if (E < 0) {
3144        SetColour(col_WHITE, factor);
3145        return;
3146    }
3147
3148    Double how_far = E / MAX_ERROR;
3149    assert(how_far >= 0.0);
3150    if (how_far > 1.0) how_far = 1.0;
3151    SetColourFrom01(how_far, factor);
3152}
3153
3154void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
3155                                    const Vector3 &c, const Vector3 &d)
3156{
3157    Vector3 normal = (a - c) * (d - b);
3158    normal.normalise();
3159    Double factor = dot(normal, light) * .3 + .7;
3160    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3161    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3162    // FIXME: should plot triangles instead to avoid rendering glitches.
3163    BeginQuadrilaterals();
3164////    PlaceNormal(normal);
3165    SetColourFromError(static_E_hack, factor);
3166    PlaceVertex(a, 0, 0);
3167    PlaceVertex(b, w, 0);
3168    PlaceVertex(c, w, h);
3169    PlaceVertex(d, 0, h);
3170    EndQuadrilaterals();
3171}
3172
3173void GfxCore::AddPolylineError(const traverse & centreline)
3174{
3175    BeginPolyline();
3176    SetColourFromError(centreline.E, 1.0);
3177    vector<PointInfo>::const_iterator i;
3178    for(i = centreline.begin(); i != centreline.end(); ++i) {
3179        PlaceVertex(*i);
3180    }
3181    EndPolyline();
3182}
3183
3184// gradient is in *radians*.
3185void GfxCore::SetColourFromGradient(double gradient, Double factor)
3186{
3187    // Set the drawing colour based on the gradient of the leg.
3188
3189    const Double GRADIENT_MAX = M_PI_2;
3190    gradient = fabs(gradient);
3191    Double how_far = gradient / GRADIENT_MAX;
3192    SetColourFrom01(how_far, factor);
3193}
3194
3195void GfxCore::AddPolylineGradient(const traverse & centreline)
3196{
3197    vector<PointInfo>::const_iterator i, prev_i;
3198    i = centreline.begin();
3199    prev_i = i;
3200    while (++i != centreline.end()) {
3201        BeginPolyline();
3202        SetColourFromGradient((*i - *prev_i).gradient(), 1.0);
3203        PlaceVertex(*prev_i);
3204        PlaceVertex(*i);
3205        prev_i = i;
3206        EndPolyline();
3207    }
3208}
3209
3210static double static_gradient_hack; // FIXME
3211
3212void GfxCore::AddQuadrilateralGradient(const Vector3 &a, const Vector3 &b,
3213                                       const Vector3 &c, const Vector3 &d)
3214{
3215    Vector3 normal = (a - c) * (d - b);
3216    normal.normalise();
3217    Double factor = dot(normal, light) * .3 + .7;
3218    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3219    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3220    // FIXME: should plot triangles instead to avoid rendering glitches.
3221    BeginQuadrilaterals();
3222////    PlaceNormal(normal);
3223    SetColourFromGradient(static_gradient_hack, factor);
3224    PlaceVertex(a, 0, 0);
3225    PlaceVertex(b, w, 0);
3226    PlaceVertex(c, w, h);
3227    PlaceVertex(d, 0, h);
3228    EndQuadrilaterals();
3229}
3230
3231void GfxCore::SetColourFromLength(double length, Double factor)
3232{
3233    // Set the drawing colour based on log(length_of_leg).
3234
3235    Double log_len = log10(length);
3236    Double how_far = log_len / LOG_LEN_MAX;
3237    how_far = max(how_far, 0.0);
3238    how_far = min(how_far, 1.0);
3239    SetColourFrom01(how_far, factor);
3240}
3241
3242void GfxCore::SetColourFrom01(double how_far, Double factor)
3243{
3244    double b;
3245    double into_band = modf(how_far * (GetNumColourBands() - 1), &b);
3246    int band(b);
3247    GLAPen pen1 = GetPen(band);
3248    // With 24bit colour, interpolating by less than this can have no effect.
3249    if (into_band >= 1.0 / 512.0) {
3250        const GLAPen& pen2 = GetPen(band + 1);
3251        pen1.Interpolate(pen2, into_band);
3252    }
3253    SetColour(pen1, factor);
3254}
3255
3256void GfxCore::AddPolylineLength(const traverse & centreline)
3257{
3258    vector<PointInfo>::const_iterator i, prev_i;
3259    i = centreline.begin();
3260    prev_i = i;
3261    while (++i != centreline.end()) {
3262        BeginPolyline();
3263        SetColourFromLength((*i - *prev_i).magnitude(), 1.0);
3264        PlaceVertex(*prev_i);
3265        PlaceVertex(*i);
3266        prev_i = i;
3267        EndPolyline();
3268    }
3269}
3270
3271static double static_length_hack; // FIXME
3272
3273void GfxCore::AddQuadrilateralLength(const Vector3 &a, const Vector3 &b,
3274                                     const Vector3 &c, const Vector3 &d)
3275{
3276    Vector3 normal = (a - c) * (d - b);
3277    normal.normalise();
3278    Double factor = dot(normal, light) * .3 + .7;
3279    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
3280    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
3281    // FIXME: should plot triangles instead to avoid rendering glitches.
3282    BeginQuadrilaterals();
3283////    PlaceNormal(normal);
3284    SetColourFromLength(static_length_hack, factor);
3285    PlaceVertex(a, 0, 0);
3286    PlaceVertex(b, w, 0);
3287    PlaceVertex(c, w, h);
3288    PlaceVertex(d, 0, h);
3289    EndQuadrilaterals();
3290}
3291
3292void
3293GfxCore::SkinPassage(vector<XSect> & centreline, bool draw)
3294{
3295    assert(centreline.size() > 1);
3296    Vector3 U[4];
3297    XSect prev_pt_v;
3298    Vector3 last_right(1.0, 0.0, 0.0);
3299
3300//  FIXME: it's not simple to set the colour of a tube based on error...
3301//    static_E_hack = something...
3302    vector<XSect>::iterator i = centreline.begin();
3303    vector<XSect>::size_type segment = 0;
3304    while (i != centreline.end()) {
3305        // get the coordinates of this vertex
3306        XSect & pt_v = *i++;
3307
3308        double z_pitch_adjust = 0.0;
3309        bool cover_end = false;
3310
3311        Vector3 right, up;
3312
3313        const Vector3 up_v(0.0, 0.0, 1.0);
3314
3315        if (segment == 0) {
3316            assert(i != centreline.end());
3317            // first segment
3318
3319            // get the coordinates of the next vertex
3320            const XSect & next_pt_v = *i;
3321
3322            // calculate vector from this pt to the next one
3323            Vector3 leg_v = next_pt_v - pt_v;
3324
3325            // obtain a vector in the LRUD plane
3326            right = leg_v * up_v;
3327            if (right.magnitude() == 0) {
3328                right = last_right;
3329                // Obtain a second vector in the LRUD plane,
3330                // perpendicular to the first.
3331                //up = right * leg_v;
3332                up = up_v;
3333            } else {
3334                last_right = right;
3335                up = up_v;
3336            }
3337
3338            cover_end = true;
3339            static_date_hack = next_pt_v.GetDate();
3340        } else if (segment + 1 == centreline.size()) {
3341            // last segment
3342
3343            // Calculate vector from the previous pt to this one.
3344            Vector3 leg_v = pt_v - prev_pt_v;
3345
3346            // Obtain a horizontal vector in the LRUD plane.
3347            right = leg_v * up_v;
3348            if (right.magnitude() == 0) {
3349                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
3350                // Obtain a second vector in the LRUD plane,
3351                // perpendicular to the first.
3352                //up = right * leg_v;
3353                up = up_v;
3354            } else {
3355                last_right = right;
3356                up = up_v;
3357            }
3358
3359            cover_end = true;
3360            static_date_hack = pt_v.GetDate();
3361        } else {
3362            assert(i != centreline.end());
3363            // Intermediate segment.
3364
3365            // Get the coordinates of the next vertex.
3366            const XSect & next_pt_v = *i;
3367
3368            // Calculate vectors from this vertex to the
3369            // next vertex, and from the previous vertex to
3370            // this one.
3371            Vector3 leg1_v = pt_v - prev_pt_v;
3372            Vector3 leg2_v = next_pt_v - pt_v;
3373
3374            // Obtain horizontal vectors perpendicular to
3375            // both legs, then normalise and average to get
3376            // a horizontal bisector.
3377            Vector3 r1 = leg1_v * up_v;
3378            Vector3 r2 = leg2_v * up_v;
3379            r1.normalise();
3380            r2.normalise();
3381            right = r1 + r2;
3382            if (right.magnitude() == 0) {
3383                // This is the "mid-pitch" case...
3384                right = last_right;
3385            }
3386            if (r1.magnitude() == 0) {
3387                Vector3 n = leg1_v;
3388                n.normalise();
3389                z_pitch_adjust = n.GetZ();
3390                //up = Vector3(0, 0, leg1_v.GetZ());
3391                //up = right * up;
3392                up = up_v;
3393
3394                // Rotate pitch section to minimise the
3395                // "tortional stress" - FIXME: use
3396                // triangles instead of rectangles?
3397                int shift = 0;
3398                Double maxdotp = 0;
3399
3400                // Scale to unit vectors in the LRUD plane.
3401                right.normalise();
3402                up.normalise();
3403                Vector3 vec = up - right;
3404                for (int orient = 0; orient <= 3; ++orient) {
3405                    Vector3 tmp = U[orient] - prev_pt_v;
3406                    tmp.normalise();
3407                    Double dotp = dot(vec, tmp);
3408                    if (dotp > maxdotp) {
3409                        maxdotp = dotp;
3410                        shift = orient;
3411                    }
3412                }
3413                if (shift) {
3414                    if (shift != 2) {
3415                        Vector3 temp(U[0]);
3416                        U[0] = U[shift];
3417                        U[shift] = U[2];
3418                        U[2] = U[shift ^ 2];
3419                        U[shift ^ 2] = temp;
3420                    } else {
3421                        swap(U[0], U[2]);
3422                        swap(U[1], U[3]);
3423                    }
3424                }
3425#if 0
3426                // Check that the above code actually permuted
3427                // the vertices correctly.
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                    if (dotp > maxdotp) {
3435                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
3436                        shift = j;
3437                    }
3438                }
3439                if (shift) {
3440                    printf("New shift = %d!\n", shift);
3441                    shift = 0;
3442                    maxdotp = 0;
3443                    for (int j = 0; j <= 3; ++j) {
3444                        Vector3 tmp = U[j] - prev_pt_v;
3445                        tmp.normalise();
3446                        Double dotp = dot(vec, tmp);
3447                        printf("    %d : %.8f\n", j, dotp);
3448                    }
3449                }
3450#endif
3451            } else if (r2.magnitude() == 0) {
3452                Vector3 n = leg2_v;
3453                n.normalise();
3454                z_pitch_adjust = n.GetZ();
3455                //up = Vector3(0, 0, leg2_v.GetZ());
3456                //up = right * up;
3457                up = up_v;
3458            } else {
3459                up = up_v;
3460            }
3461            last_right = right;
3462            static_date_hack = pt_v.GetDate();
3463        }
3464
3465        // Scale to unit vectors in the LRUD plane.
3466        right.normalise();
3467        up.normalise();
3468
3469        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
3470
3471        Double l = fabs(pt_v.GetL());
3472        Double r = fabs(pt_v.GetR());
3473        Double u = fabs(pt_v.GetU());
3474        Double d = fabs(pt_v.GetD());
3475
3476        // Produce coordinates of the corners of the LRUD "plane".
3477        Vector3 v[4];
3478        v[0] = pt_v - right * l + up * u;
3479        v[1] = pt_v + right * r + up * u;
3480        v[2] = pt_v + right * r - up * d;
3481        v[3] = pt_v - right * l - up * d;
3482
3483        if (draw) {
3484            const Vector3 & delta = pt_v - prev_pt_v;
3485            static_length_hack = delta.magnitude();
3486            static_gradient_hack = delta.gradient();
3487            if (segment > 0) {
3488                (this->*AddQuad)(v[0], v[1], U[1], U[0]);
3489                (this->*AddQuad)(v[2], v[3], U[3], U[2]);
3490                (this->*AddQuad)(v[1], v[2], U[2], U[1]);
3491                (this->*AddQuad)(v[3], v[0], U[0], U[3]);
3492            }
3493
3494            if (cover_end) {
3495                (this->*AddQuad)(v[3], v[2], v[1], v[0]);
3496            }
3497        }
3498
3499        prev_pt_v = pt_v;
3500        U[0] = v[0];
3501        U[1] = v[1];
3502        U[2] = v[2];
3503        U[3] = v[3];
3504
3505        pt_v.set_right_bearing(deg(atan2(right.GetY(), right.GetX())));
3506
3507        ++segment;
3508    }
3509}
3510
3511void GfxCore::FullScreenMode()
3512{
3513    m_Parent->ViewFullScreen();
3514}
3515
3516bool GfxCore::IsFullScreen() const
3517{
3518    return m_Parent->IsFullScreen();
3519}
3520
3521bool GfxCore::FullScreenModeShowingMenus() const
3522{
3523    return m_Parent->FullScreenModeShowingMenus();
3524}
3525
3526void GfxCore::FullScreenModeShowMenus(bool show)
3527{
3528    m_Parent->FullScreenModeShowMenus(show);
3529}
3530
3531void
3532GfxCore::MoveViewer(double forward, double up, double right)
3533{
3534    double cT = cos(rad(m_TiltAngle));
3535    double sT = sin(rad(m_TiltAngle));
3536    double cP = cos(rad(m_PanAngle));
3537    double sP = sin(rad(m_PanAngle));
3538    Vector3 v_forward(cT * sP, cT * cP, sT);
3539    Vector3 v_up(sT * sP, sT * cP, -cT);
3540    Vector3 v_right(-cP, sP, 0);
3541    assert(fabs(dot(v_forward, v_up)) < 1e-6);
3542    assert(fabs(dot(v_forward, v_right)) < 1e-6);
3543    assert(fabs(dot(v_right, v_up)) < 1e-6);
3544    Vector3 move = v_forward * forward + v_up * up + v_right * right;
3545    AddTranslation(-move);
3546    // Show current position.
3547    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
3548    ForceRefresh();
3549}
3550
3551PresentationMark GfxCore::GetView() const
3552{
3553    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
3554                            m_PanAngle, -m_TiltAngle, m_Scale);
3555}
3556
3557void GfxCore::SetView(const PresentationMark & p)
3558{
3559    m_SwitchingTo = 0;
3560    SetTranslation(p - m_Parent->GetOffset());
3561    m_PanAngle = p.angle;
3562    m_TiltAngle = -p.tilt_angle; // FIXME: nasty reversed sense (and above)
3563    SetRotation(m_PanAngle, m_TiltAngle);
3564    SetScale(p.scale);
3565    ForceRefresh();
3566}
3567
3568void GfxCore::PlayPres(double speed, bool change_speed) {
3569    if (!change_speed || presentation_mode == 0) {
3570        if (speed == 0.0) {
3571            presentation_mode = 0;
3572            return;
3573        }
3574        presentation_mode = PLAYING;
3575        next_mark = m_Parent->GetPresMark(MARK_FIRST);
3576        SetView(next_mark);
3577        next_mark_time = 0; // There already!
3578        this_mark_total = 0;
3579        pres_reverse = (speed < 0);
3580    }
3581
3582    if (change_speed) pres_speed = speed;
3583
3584    if (speed != 0.0) {
3585        bool new_pres_reverse = (speed < 0);
3586        if (new_pres_reverse != pres_reverse) {
3587            pres_reverse = new_pres_reverse;
3588            if (pres_reverse) {
3589                next_mark = m_Parent->GetPresMark(MARK_PREV);
3590            } else {
3591                next_mark = m_Parent->GetPresMark(MARK_NEXT);
3592            }
3593            swap(this_mark_total, next_mark_time);
3594        }
3595    }
3596}
3597
3598void GfxCore::SetColourBy(int colour_by) {
3599    m_ColourBy = colour_by;
3600    switch (colour_by) {
3601        case COLOUR_BY_DEPTH:
3602            AddQuad = &GfxCore::AddQuadrilateralDepth;
3603            AddPoly = &GfxCore::AddPolylineDepth;
3604            break;
3605        case COLOUR_BY_DATE:
3606            AddQuad = &GfxCore::AddQuadrilateralDate;
3607            AddPoly = &GfxCore::AddPolylineDate;
3608            break;
3609        case COLOUR_BY_ERROR:
3610            AddQuad = &GfxCore::AddQuadrilateralError;
3611            AddPoly = &GfxCore::AddPolylineError;
3612            break;
3613        case COLOUR_BY_GRADIENT:
3614            AddQuad = &GfxCore::AddQuadrilateralGradient;
3615            AddPoly = &GfxCore::AddPolylineGradient;
3616            break;
3617        case COLOUR_BY_LENGTH:
3618            AddQuad = &GfxCore::AddQuadrilateralLength;
3619            AddPoly = &GfxCore::AddPolylineLength;
3620            break;
3621        default: // case COLOUR_BY_NONE:
3622            AddQuad = &GfxCore::AddQuadrilateral;
3623            AddPoly = &GfxCore::AddPolyline;
3624            break;
3625    }
3626
3627    InvalidateList(LIST_UNDERGROUND_LEGS);
3628    InvalidateList(LIST_SURFACE_LEGS);
3629    InvalidateList(LIST_TUBES);
3630
3631    ForceRefresh();
3632}
3633
3634bool GfxCore::ExportMovie(const wxString & fnm)
3635{
3636    int width;
3637    int height;
3638    GetSize(&width, &height);
3639    // Round up to next multiple of 2 (required by ffmpeg).
3640    width += (width & 1);
3641    height += (height & 1);
3642
3643    movie = new MovieMaker();
3644
3645    // FIXME: This should really use fn_str() - currently we probably can't
3646    // save to a Unicode path on wxmsw.
3647    if (!movie->Open(fnm.mb_str(), width, height)) {
3648        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
3649        delete movie;
3650        movie = NULL;
3651        return false;
3652    }
3653
3654    PlayPres(1);
3655    return true;
3656}
3657
3658void
3659GfxCore::OnPrint(const wxString &filename, const wxString &title,
3660                 const wxString &datestamp, time_t datestamp_numeric,
3661                 const wxString &cs_proj,
3662                 bool close_after_print)
3663{
3664    svxPrintDlg * p;
3665    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3666                        datestamp, datestamp_numeric,
3667                        m_PanAngle, m_TiltAngle,
3668                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3669                        m_Entrances, m_FixedPts, m_ExportedPts,
3670                        true, close_after_print);
3671    p->Show(true);
3672}
3673
3674void
3675GfxCore::OnExport(const wxString &filename, const wxString &title,
3676                  const wxString &datestamp, time_t datestamp_numeric,
3677                  const wxString &cs_proj)
3678{
3679    // Fill in "right_bearing" for each cross-section.
3680    list<vector<XSect> >::iterator trav = m_Parent->tubes_begin();
3681    list<vector<XSect> >::iterator tend = m_Parent->tubes_end();
3682    while (trav != tend) {
3683        SkinPassage(*trav, false);
3684        ++trav;
3685    }
3686
3687    svxPrintDlg * p;
3688    p = new svxPrintDlg(m_Parent, filename, title, cs_proj,
3689                        datestamp, datestamp_numeric,
3690                        m_PanAngle, m_TiltAngle,
3691                        m_Names, m_Crosses, m_Legs, m_Surface, m_Tubes,
3692                        m_Entrances, m_FixedPts, m_ExportedPts,
3693                        false);
3694    p->Show(true);
3695}
3696
3697static wxCursor
3698make_cursor(const unsigned char * bits, const unsigned char * mask,
3699            int hotx, int hoty)
3700{
3701#if defined __WXMSW__ || defined __WXMAC__
3702# ifdef __WXMAC__
3703    // The default Mac cursor is black with a white edge, so
3704    // invert our custom cursors to match.
3705    char b[128];
3706    for (int i = 0; i < 128; ++i)
3707        b[i] = bits[i] ^ 0xff;
3708# else
3709    const char * b = reinterpret_cast<const char *>(bits);
3710# endif
3711    wxBitmap cursor_bitmap(b, 32, 32);
3712    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
3713    cursor_bitmap.SetMask(new wxMask(mask_bitmap, *wxWHITE));
3714    wxImage cursor_image = cursor_bitmap.ConvertToImage();
3715    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
3716    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
3717    return wxCursor(cursor_image);
3718#else
3719    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
3720                    (const char *)mask, wxBLACK, wxWHITE);
3721#endif
3722}
3723
3724const
3725#include "hand.xbm"
3726const
3727#include "handmask.xbm"
3728
3729const
3730#include "brotate.xbm"
3731const
3732#include "brotatemask.xbm"
3733
3734const
3735#include "vrotate.xbm"
3736const
3737#include "vrotatemask.xbm"
3738
3739const
3740#include "rotate.xbm"
3741const
3742#include "rotatemask.xbm"
3743
3744const
3745#include "rotatezoom.xbm"
3746const
3747#include "rotatezoommask.xbm"
3748
3749void
3750GfxCore::UpdateCursor(GfxCore::cursor new_cursor)
3751{
3752    // Check if we're already showing that cursor.
3753    if (current_cursor == new_cursor) return;
3754
3755    current_cursor = new_cursor;
3756    switch (current_cursor) {
3757        case GfxCore::CURSOR_DEFAULT:
3758            GLACanvas::SetCursor(wxNullCursor);
3759            break;
3760        case GfxCore::CURSOR_POINTING_HAND:
3761            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
3762            break;
3763        case GfxCore::CURSOR_DRAGGING_HAND:
3764            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
3765            break;
3766        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
3767            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
3768            break;
3769        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
3770            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
3771            break;
3772        case GfxCore::CURSOR_ROTATE_VERTICALLY:
3773            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
3774            break;
3775        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
3776            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
3777            break;
3778        case GfxCore::CURSOR_ZOOM:
3779            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
3780            break;
3781        case GfxCore::CURSOR_ZOOM_ROTATE:
3782            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
3783            break;
3784    }
3785}
3786
3787bool GfxCore::MeasuringLineActive() const
3788{
3789    if (Animating()) return false;
3790    return HereIsReal() || m_there;
3791}
3792
3793bool GfxCore::HandleRClick(wxPoint point)
3794{
3795    if (PointWithinCompass(point)) {
3796        // Pop up menu.
3797        wxMenu menu;
3798        /* TRANSLATORS: View *looking* North */
3799        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
3800        /* TRANSLATORS: View *looking* East */
3801        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
3802        /* TRANSLATORS: View *looking* South */
3803        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
3804        /* TRANSLATORS: View *looking* West */
3805        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
3806        menu.AppendSeparator();
3807        /* TRANSLATORS: Menu item which turns off the "north arrow" in aven. */
3808        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/387));
3809        /* TRANSLATORS: tickable menu item in View menu.
3810         *
3811         * Degrees are the angular measurement where there are 360 in a full
3812         * circle. */
3813        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3814        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3815        PopupMenu(&menu);
3816        return true;
3817    }
3818
3819    if (PointWithinClino(point)) {
3820        // Pop up menu.
3821        wxMenu menu;
3822        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
3823        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
3824        menu.AppendSeparator();
3825        /* TRANSLATORS: Menu item which turns off the tilt indicator in aven. */
3826        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
3827        /* TRANSLATORS: tickable menu item in View menu.
3828         *
3829         * Degrees are the angular measurement where there are 360 in a full
3830         * circle. */
3831        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3832        /* TRANSLATORS: tickable menu item in View menu.
3833         *
3834         * Show the tilt of the survey as a percentage gradient (100% = 45
3835         * degrees = 50 grad). */
3836        menu.AppendCheckItem(menu_CTL_PERCENT, wmsg(/*&Percent*/430));
3837        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3838        PopupMenu(&menu);
3839        return true;
3840    }
3841
3842    if (PointWithinScaleBar(point)) {
3843        // Pop up menu.
3844        wxMenu menu;
3845        /* TRANSLATORS: Menu item which turns off the scale bar in aven. */
3846        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
3847        /* TRANSLATORS: tickable menu item in View menu.
3848         *
3849         * "Metric" here means metres, km, etc (rather than feet, miles, etc)
3850         */
3851        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3852        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3853        PopupMenu(&menu);
3854        return true;
3855    }
3856
3857    if (PointWithinColourKey(point)) {
3858        // Pop up menu.
3859        wxMenu menu;
3860        menu.AppendCheckItem(menu_COLOUR_BY_DEPTH, wmsg(/*Colour by &Depth*/292));
3861        menu.AppendCheckItem(menu_COLOUR_BY_DATE, wmsg(/*Colour by D&ate*/293));
3862        menu.AppendCheckItem(menu_COLOUR_BY_ERROR, wmsg(/*Colour by &Error*/289));
3863        menu.AppendCheckItem(menu_COLOUR_BY_GRADIENT, wmsg(/*Colour by &Gradient*/85));
3864        menu.AppendCheckItem(menu_COLOUR_BY_LENGTH, wmsg(/*Colour by &Length*/82));
3865        menu.AppendSeparator();
3866        /* TRANSLATORS: Menu item which turns off the colour key.
3867         * The "Colour Key" is the thing in aven showing which colour
3868         * corresponds to which depth, date, survey closure error, etc. */
3869        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
3870        if (m_ColourBy == COLOUR_BY_DEPTH || m_ColourBy == COLOUR_BY_LENGTH)
3871            menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3872        else if (m_ColourBy == COLOUR_BY_GRADIENT)
3873            menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3874        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&wxEvtHandler::ProcessEvent, NULL, m_Parent->GetEventHandler());
3875        PopupMenu(&menu);
3876        return true;
3877    }
3878
3879    return false;
3880}
3881
3882void GfxCore::SetZoomBox(wxPoint p1, wxPoint p2, bool centred, bool aspect)
3883{
3884    if (centred) {
3885        p1.x = p2.x + (p1.x - p2.x) * 2;
3886        p1.y = p2.y + (p1.y - p2.y) * 2;
3887    }
3888    if (aspect) {
3889#if 0 // FIXME: This needs more work.
3890        int sx = GetXSize();
3891        int sy = GetYSize();
3892        int dx = p1.x - p2.x;
3893        int dy = p1.y - p2.y;
3894        int dy_new = dx * sy / sx;
3895        if (abs(dy_new) >= abs(dy)) {
3896            p1.y += (dy_new - dy) / 2;
3897            p2.y -= (dy_new - dy) / 2;
3898        } else {
3899            int dx_new = dy * sx / sy;
3900            p1.x += (dx_new - dx) / 2;
3901            p2.x -= (dx_new - dx) / 2;
3902        }
3903#endif
3904    }
3905    zoombox.set(p1, p2);
3906    ForceRefresh();
3907}
3908
3909void GfxCore::ZoomBoxGo()
3910{
3911    if (!zoombox.active()) return;
3912
3913    int width = GetXSize();
3914    int height = GetYSize();
3915
3916    TranslateCave(-0.5 * (zoombox.x1 + zoombox.x2 - width),
3917                  -0.5 * (zoombox.y1 + zoombox.y2 - height));
3918    int box_w = abs(zoombox.x1 - zoombox.x2);
3919    int box_h = abs(zoombox.y1 - zoombox.y2);
3920
3921    double factor = min(double(width) / box_w, double(height) / box_h);
3922
3923    zoombox.unset();
3924
3925    SetScale(GetScale() * factor);
3926}
Note: See TracBrowser for help on using the repository browser.