source: git/src/gfxcore.cc @ 194503c

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

src/gfxcore.cc: Fix DEM reading for big-endian platforms.

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