source: git/src/gfxcore.cc @ 5314a0e

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

src/gfxcore.cc,src/gfxcore.h: Factor out DEM loading into a separate
method.

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