source: git/src/gfxcore.cc @ c26455e

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

src/gfxcore.cc: Show busy cursor while building the terrain model.

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