source: git/src/gfxcore.cc @ 5293c84

RELEASE/1.1RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-datawalls-data-hanging-as-warning
Last change on this file since 5293c84 was d35144d, checked in by Olly Betts <olly@…>, 14 years ago

Initialise 3 flags when we load a survey to avoid using them potentially
uninitialised.

git-svn-id: file:///home/survex-svn/survex/branches/survex-1_1@3359 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

  • Property mode set to 100644
File size: 77.5 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 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 "gfxcore.h"
34#include "mainfrm.h"
35#include "message.h"
36#include "useful.h"
37#include "printwx.h"
38#include "guicontrol.h"
39#include "moviemaker.h"
40
41#include <wx/confbase.h>
42#include <wx/image.h>
43
44#define MAX(a, b) ((a) > (b) ? (a) : (b))
45#define MAX3(a, b, c) ((a) > (b) ? MAX(a, c) : MAX(b, c))
46
47// Values for m_SwitchingTo
48#define PLAN 1
49#define ELEVATION 2
50#define NORTH 3
51#define EAST 4
52#define SOUTH 5
53#define WEST 6
54
55// Any error value higher than this is clamped to this.
56#define MAX_ERROR 12.0
57
58// How many bins per letter height to use when working out non-overlapping
59// labels.
60const unsigned int QUANTISE_FACTOR = 2;
61
62const int NUM_DEPTH_COLOURS = 13;
63
64#include "avenpal.h"
65
66static const int COMPASS_OFFSET_X = 60;
67static const int COMPASS_OFFSET_Y = 80;
68static const int INDICATOR_BOX_SIZE = 60;
69static const int INDICATOR_GAP = 2;
70static const int INDICATOR_MARGIN = 5;
71static const int INDICATOR_OFFSET_X = 15;
72static const int INDICATOR_OFFSET_Y = 15;
73static const int INDICATOR_RADIUS = INDICATOR_BOX_SIZE / 2 - INDICATOR_MARGIN;
74static const int CLINO_OFFSET_X = 6 + INDICATOR_OFFSET_X +
75                                  INDICATOR_BOX_SIZE + INDICATOR_GAP;
76static const int DEPTH_BAR_OFFSET_X = 16;
77static const int DEPTH_BAR_EXTRA_LEFT_MARGIN = 2;
78static const int DEPTH_BAR_BLOCK_WIDTH = 20;
79static const int DEPTH_BAR_BLOCK_HEIGHT = 15;
80static const int DEPTH_BAR_MARGIN = 6;
81static const int DEPTH_BAR_OFFSET_Y = 16 + DEPTH_BAR_MARGIN;
82static const int TICK_LENGTH = 4;
83static const int SCALE_BAR_OFFSET_X = 15;
84static const int SCALE_BAR_OFFSET_Y = 12;
85static const int SCALE_BAR_HEIGHT = 12;
86
87static const gla_colour TEXT_COLOUR = col_GREEN;
88static const gla_colour HERE_COLOUR = col_WHITE;
89static const gla_colour NAME_COLOUR = col_GREEN;
90
91#define HITTEST_SIZE 20
92
93// vector for lighting angle
94static const Vector3 light(.577, .577, .577);
95
96BEGIN_EVENT_TABLE(GfxCore, wxGLCanvas)
97    EVT_PAINT(GfxCore::OnPaint)
98    EVT_LEFT_DOWN(GfxCore::OnLButtonDown)
99    EVT_LEFT_UP(GfxCore::OnLButtonUp)
100    EVT_MIDDLE_DOWN(GfxCore::OnMButtonDown)
101    EVT_MIDDLE_UP(GfxCore::OnMButtonUp)
102    EVT_RIGHT_DOWN(GfxCore::OnRButtonDown)
103    EVT_RIGHT_UP(GfxCore::OnRButtonUp)
104    EVT_MOUSEWHEEL(GfxCore::OnMouseWheel)
105    EVT_MOTION(GfxCore::OnMouseMove)
106    EVT_LEAVE_WINDOW(GfxCore::OnLeaveWindow)
107    EVT_SIZE(GfxCore::OnSize)
108    EVT_IDLE(GfxCore::OnIdle)
109    EVT_CHAR(GfxCore::OnKeyPress)
110END_EVENT_TABLE()
111
112GfxCore::GfxCore(MainFrm* parent, wxWindow* parent_win, GUIControl* control) :
113    GLACanvas(parent_win, 100), m_HaveData(false)
114{
115    m_Control = control;
116    m_ScaleBarWidth = 0;
117    m_Parent = parent;
118    m_DoneFirstShow = false;
119    m_Crosses = false;
120    m_Legs = true;
121    m_Names = false;
122    m_OverlappingNames = false;
123    m_Compass = true;
124    m_Clino = true;
125    m_Depthbar = true;
126    m_Scalebar = true;
127    m_LabelGrid = NULL;
128    m_Rotating = false;
129    m_SwitchingTo = 0;
130    m_Entrances = false;
131    m_FixedPts = false;
132    m_ExportedPts = false;
133    m_Tubes = false;
134    m_Grid = false;
135    m_BoundingBox = false;
136    m_ColourBy = COLOUR_BY_DEPTH;
137    AddQuad = &GfxCore::AddQuadrilateralDepth;
138    AddPoly = &GfxCore::AddPolylineDepth;
139    wxConfigBase::Get()->Read(wxT("metric"), &m_Metric, true);
140    wxConfigBase::Get()->Read(wxT("degrees"), &m_Degrees, true);
141    m_here.Invalidate();
142    m_there.Invalidate();
143    presentation_mode = 0;
144    pres_speed = 0.0;
145    pres_reverse = false;
146    mpeg = NULL;
147    current_cursor = GfxCore::CURSOR_DEFAULT;
148
149    // Initialise grid for hit testing.
150    m_PointGrid = new list<LabelInfo*>[HITTEST_SIZE * HITTEST_SIZE];
151
152    m_Pens = new GLAPen[NUM_DEPTH_COLOURS + 1];
153    for (int pen = 0; pen < NUM_DEPTH_COLOURS + 1; ++pen) {
154        m_Pens[pen].SetColour(REDS[pen] / 255.0,
155                              GREENS[pen] / 255.0,
156                              BLUES[pen] / 255.0);
157    }
158}
159
160GfxCore::~GfxCore()
161{
162    TryToFreeArrays();
163
164    delete[] m_Pens;
165    delete[] m_PointGrid;
166}
167
168void GfxCore::TryToFreeArrays()
169{
170    // Free up any memory allocated for arrays.
171
172    if (m_LabelGrid) {
173        delete[] m_LabelGrid;
174        m_LabelGrid = NULL;
175    }
176}
177
178//
179//  Initialisation methods
180//
181
182void GfxCore::Initialise(bool same_file)
183{
184    // Initialise the view from the parent holding the survey data.
185
186    TryToFreeArrays();
187
188    m_DoneFirstShow = false;
189
190    m_HitTestGridValid = false;
191    m_here_is_temporary = true;
192    m_here.Invalidate();
193    m_there.Invalidate();
194
195    m_MouseOutsideCompass = m_MouseOutsideElev = false;
196
197    if (!same_file) {
198        // Apply default parameters unless reloading the same file.
199        DefaultParameters();
200
201        // Set the initial scale.
202        SetScale(1.0);
203    }
204
205    switch (m_ColourBy) {
206        case COLOUR_BY_DEPTH:
207            if (m_Parent->GetDepthExtent() == 0.0) {
208                SetColourBy(COLOUR_BY_NONE);
209            }
210            break;
211        case COLOUR_BY_DATE:
212            if (m_Parent->GetDateExtent() == 0) {
213                SetColourBy(COLOUR_BY_NONE);
214            }
215            break;
216        case COLOUR_BY_ERROR:
217            if (!m_Parent->HasErrorInformation()) {
218                SetColourBy(COLOUR_BY_NONE);
219            }
220            break;
221    }
222
223    m_HaveData = true;
224
225    ForceRefresh();
226}
227
228void GfxCore::FirstShow()
229{
230    GLACanvas::FirstShow();
231
232    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
233    list<LabelInfo*>::iterator pos = m_Parent->GetLabelsNC();
234    while (pos != m_Parent->GetLabelsNCEnd()) {
235        LabelInfo* label = *pos++;
236        // Calculate and set the label width for use when plotting
237        // none-overlapping labels.
238        int ext_x;
239        GLACanvas::GetTextExtent(label->GetText(), &ext_x, NULL);
240        label->set_width(unsigned(ext_x) / quantise + 1);
241    }
242
243    SetBackgroundColour(0.0, 0.0, 0.0);
244
245    // Set diameter of the viewing volume.
246    SetVolumeDiameter(sqrt(sqrd(m_Parent->GetXExtent()) +
247                           sqrd(m_Parent->GetYExtent()) +
248                           sqrd(m_Parent->GetZExtent())));
249
250    // Update our record of the client area size and centre.
251    GetClientSize(&m_XSize, &m_YSize);
252
253    m_DoneFirstShow = true;
254}
255
256//
257//  Recalculating methods
258//
259
260void GfxCore::SetScale(Double scale)
261{
262    // Fill the plot data arrays with screen coordinates, scaling the survey
263    // to a particular absolute scale.
264
265    if (scale < 0.05) {
266        scale = 0.05;
267    } else {
268        if (scale > 1000.0) scale = 1000.0;
269    }
270
271    m_Scale = scale;
272    m_HitTestGridValid = false;
273    if (m_here_is_temporary) SetHere();
274
275    GLACanvas::SetScale(scale);
276}
277
278bool GfxCore::HasUndergroundLegs() const
279{
280    return m_Parent->HasUndergroundLegs();
281}
282
283bool GfxCore::HasSurfaceLegs() const
284{
285    return m_Parent->HasSurfaceLegs();
286}
287
288bool GfxCore::HasTubes() const
289{
290    return m_Parent->HasTubes();
291}
292
293void GfxCore::UpdateBlobs()
294{
295    InvalidateList(LIST_BLOBS);
296}
297
298//
299//  Event handlers
300//
301
302void GfxCore::OnLeaveWindow(wxMouseEvent& event) {
303    SetHere();
304    ClearCoords();
305}
306
307void GfxCore::OnIdle(wxIdleEvent& event)
308{
309    // Handle an idle event.
310    if (Animate()) {
311        ForceRefresh();
312        event.RequestMore();
313    }
314}
315
316void GfxCore::OnPaint(wxPaintEvent&)
317{
318    // Redraw the window.
319
320    // Get a graphics context.
321    wxPaintDC dc(this);
322
323    assert(GetContext());
324
325    if (m_HaveData) {
326        // Make sure we're initialised.
327        bool first_time = !m_DoneFirstShow;
328        if (first_time) {
329            FirstShow();
330        }
331
332        StartDrawing();
333
334        // Clear the background.
335        Clear();
336
337        // Set up model transformation matrix.
338        SetDataTransform();
339
340        timer.Start(); // reset timer
341
342        if (m_Legs || m_Tubes) {
343            if (m_Tubes) {
344                EnableSmoothPolygons(true); // FIXME: allow false for wireframe view
345                DrawList(LIST_TUBES);
346                DisableSmoothPolygons();
347            }
348
349            // Draw the underground legs.  Do this last so that anti-aliasing
350            // works over polygons.
351            SetColour(col_GREEN);
352            DrawList(LIST_UNDERGROUND_LEGS);
353        }
354
355        if (m_Surface) {
356            // Draw the surface legs.
357            DrawList(LIST_SURFACE_LEGS);
358        }
359
360        DrawList(LIST_BLOBS);
361
362        if (m_BoundingBox) {
363            DrawShadowedBoundingBox();
364        }
365        if (m_Grid) {
366            // Draw the grid.
367            DrawList(LIST_GRID);
368        }
369
370        if (m_Crosses) {
371            DrawList(LIST_CROSSES);
372        }
373
374        SetIndicatorTransform();
375
376        // Draw station names.
377        if (m_Names /*&& !m_Control->MouseDown() && !Animating()*/) {
378            SetColour(NAME_COLOUR);
379
380            if (m_OverlappingNames) {
381                SimpleDrawNames();
382            } else {
383                NattyDrawNames();
384            }
385        }
386
387        if (!Animating() && (m_here.IsValid() || m_there.IsValid())) {
388            // Draw "here" and "there".
389            Double hx, hy;
390            SetColour(HERE_COLOUR);
391            if (m_here.IsValid()) {
392                Double dummy;
393                Transform(m_here, &hx, &hy, &dummy);
394                if (!m_here_is_temporary) DrawRing(hx, hy);
395            }
396            if (m_there.IsValid()) {
397                Double tx, ty;
398                Double dummy;
399                Transform(m_there, &tx, &ty, &dummy);
400                if (m_here.IsValid()) {
401                    BeginLines();
402                    PlaceIndicatorVertex(hx, hy);
403                    PlaceIndicatorVertex(tx, ty);
404                    EndLines();
405                }
406                BeginBlobs();
407                DrawBlob(tx, ty);
408                EndBlobs();
409            }
410        }
411
412        // Draw indicators.
413        //
414        // There's no advantage in generating an OpenGL list for the
415        // indicators since they change with almost every redraw (and
416        // sometimes several times between redraws).  This way we avoid
417        // the need to track when to update the indicator OpenGL list,
418        // and also avoid indicator update bugs when we don't quite get this
419        // right...
420        DrawIndicators();
421
422        FinishDrawing();
423
424        drawtime = timer.Time();
425    } else {
426        dc.SetBackground(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWFRAME));
427        dc.Clear();
428    }
429}
430
431void GfxCore::DrawBoundingBox()
432{
433    const Vector3 v = 0.5 * m_Parent->GetExtent();
434
435    SetColour(col_BLUE);
436    EnableDashedLines();
437    BeginPolyline();
438    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
439    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
440    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
441    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
442    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
443    EndPolyline();
444    BeginPolyline();
445    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
446    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
447    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
448    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
449    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
450    EndPolyline();
451    BeginLines();
452    PlaceVertex(-v.GetX(), -v.GetY(), v.GetZ());
453    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
454    PlaceVertex(-v.GetX(), v.GetY(), v.GetZ());
455    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
456    PlaceVertex(v.GetX(), v.GetY(), v.GetZ());
457    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
458    PlaceVertex(v.GetX(), -v.GetY(), v.GetZ());
459    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
460    EndLines();
461    DisableDashedLines();
462}
463
464void GfxCore::DrawShadowedBoundingBox()
465{
466    const Vector3 v = 0.5 * m_Parent->GetExtent();
467
468    DrawBoundingBox();
469
470    // FIXME: these gl* calls should be in gla-gl.cc
471    glPolygonOffset(1.0, 1.0);
472    glEnable(GL_POLYGON_OFFSET_FILL);
473
474    SetColour(col_DARK_GREY);
475    BeginQuadrilaterals();
476    PlaceVertex(-v.GetX(), -v.GetY(), -v.GetZ());
477    PlaceVertex(-v.GetX(), v.GetY(), -v.GetZ());
478    PlaceVertex(v.GetX(), v.GetY(), -v.GetZ());
479    PlaceVertex(v.GetX(), -v.GetY(), -v.GetZ());
480    EndQuadrilaterals();
481
482    glDisable(GL_POLYGON_OFFSET_FILL);
483
484    DrawList(LIST_SHADOW);
485}
486
487void GfxCore::DrawGrid()
488{
489    // Draw the grid.
490    SetColour(col_RED);
491
492    // Calculate the extent of the survey, in metres across the screen plane.
493    Double m_across_screen = SurveyUnitsAcrossViewport();
494    // Calculate the length of the scale bar in metres.
495    //--move this elsewhere
496    Double size_snap = pow(10.0, floor(log10(0.75 * m_across_screen)));
497    Double t = m_across_screen * 0.75 / size_snap;
498    if (t >= 5.0) {
499        size_snap *= 5.0;
500    }
501    else if (t >= 2.0) {
502        size_snap *= 2.0;
503    }
504
505    Double grid_size = size_snap * 0.1;
506    Double edge = grid_size * 2.0;
507    Double grid_z = -m_Parent->GetZExtent() * 0.5 - grid_size;
508    Double left = -m_Parent->GetXExtent() * 0.5 - edge;
509    Double right = m_Parent->GetXExtent() * 0.5 + edge;
510    Double bottom = -m_Parent->GetYExtent() * 0.5 - edge;
511    Double top = m_Parent->GetYExtent() * 0.5 + edge;
512    int count_x = (int) ceil((right - left) / grid_size);
513    int count_y = (int) ceil((top - bottom) / grid_size);
514    Double actual_right = left + count_x*grid_size;
515    Double actual_top = bottom + count_y*grid_size;
516
517    BeginLines();
518
519    for (int xc = 0; xc <= count_x; xc++) {
520        Double x = left + xc*grid_size;
521
522        PlaceVertex(x, bottom, grid_z);
523        PlaceVertex(x, actual_top, grid_z);
524    }
525
526    for (int yc = 0; yc <= count_y; yc++) {
527        Double y = bottom + yc*grid_size;
528        PlaceVertex(left, y, grid_z);
529        PlaceVertex(actual_right, y, grid_z);
530    }
531
532    EndLines();
533}
534
535int GfxCore::GetClinoOffset() const
536{
537    return m_Compass ? CLINO_OFFSET_X : INDICATOR_OFFSET_X;
538}
539
540void GfxCore::DrawTick(int angle_cw)
541{
542    const Double theta = rad(angle_cw);
543    const wxCoord length1 = INDICATOR_RADIUS;
544    const wxCoord length0 = length1 + TICK_LENGTH;
545    wxCoord x0 = wxCoord(length0 * sin(theta));
546    wxCoord y0 = wxCoord(length0 * cos(theta));
547    wxCoord x1 = wxCoord(length1 * sin(theta));
548    wxCoord y1 = wxCoord(length1 * cos(theta));
549
550    PlaceIndicatorVertex(x0, y0);
551    PlaceIndicatorVertex(x1, y1);
552}
553
554void GfxCore::DrawArrow(gla_colour col1, gla_colour col2) {
555    Vector3 p1(0, INDICATOR_RADIUS, 0);
556    Vector3 p2(INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 150deg
557    Vector3 p3(-INDICATOR_RADIUS/2, INDICATOR_RADIUS*-.866025404, 0); // 210deg
558    Vector3 pc(0, 0, 0);
559
560    DrawTriangle(col_LIGHT_GREY, col1, p2, p1, pc);
561    DrawTriangle(col_LIGHT_GREY, col2, p3, p1, pc);
562}
563
564void GfxCore::DrawCompass() {
565    // Ticks.
566    BeginLines();
567    for (int angle = 315; angle > 0; angle -= 45) {
568        DrawTick(angle);
569    }
570    SetColour(col_GREEN);
571    DrawTick(0);
572    EndLines();
573
574    // Compass background.
575    DrawCircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS);
576
577    // Compass arrow.
578    DrawArrow(col_INDICATOR_1, col_INDICATOR_2);
579}
580
581// Draw the non-rotating background to the clino.
582void GfxCore::DrawClinoBack() {
583    BeginLines();
584    for (int angle = 0; angle <= 180; angle += 90) {
585        DrawTick(angle);
586    }
587
588    SetColour(col_GREY);
589    PlaceIndicatorVertex(0, INDICATOR_RADIUS);
590    PlaceIndicatorVertex(0, -INDICATOR_RADIUS);
591    PlaceIndicatorVertex(0, 0);
592    PlaceIndicatorVertex(INDICATOR_RADIUS, 0);
593
594    EndLines();
595}
596
597void GfxCore::DrawClino() {
598    // Ticks.
599    SetColour(col_GREEN);
600    BeginLines();
601    DrawTick(0);
602    EndLines();
603
604    // Clino background.
605    DrawSemicircle(col_LIGHT_GREY_2, col_GREY, 0, 0, INDICATOR_RADIUS, 0);
606
607    // Elevation arrow.
608    DrawArrow(col_INDICATOR_2, col_INDICATOR_1);
609}
610
611void GfxCore::Draw2dIndicators()
612{
613    // Draw the compass and elevation indicators.
614
615    const int centre_y = INDICATOR_BOX_SIZE / 2 + INDICATOR_OFFSET_Y;
616
617    const int comp_centre_x = GetCompassXPosition();
618
619    if (m_Compass && !m_Parent->IsExtendedElevation()) {
620        // If the user is dragging the compass with the pointer outside the
621        // compass, we snap to 45 degree multiples, and the ticks go white.
622        SetColour(m_MouseOutsideCompass ? col_WHITE : col_LIGHT_GREY_2);
623        DrawList2D(LIST_COMPASS, comp_centre_x, centre_y, -m_PanAngle);
624    }
625
626    const int elev_centre_x = GetClinoXPosition();
627
628    if (m_Clino) {
629        // If the user is dragging the clino with the pointer outside the
630        // clino, we snap to 90 degree multiples, and the ticks go white.
631        SetColour(m_MouseOutsideElev ? col_WHITE : col_LIGHT_GREY_2);
632        DrawList2D(LIST_CLINO_BACK, elev_centre_x, centre_y, 0);
633        DrawList2D(LIST_CLINO, elev_centre_x, centre_y, 90 + m_TiltAngle);
634    }
635
636    SetColour(TEXT_COLOUR);
637
638    static int triple_zero_width = 0;
639    static int height = 0;
640    if (!triple_zero_width) {
641        GetTextExtent(wxT("000"), &triple_zero_width, &height);
642    }
643    const int y_off = INDICATOR_OFFSET_Y + INDICATOR_BOX_SIZE + height / 2;
644
645    if (m_Compass && !m_Parent->IsExtendedElevation()) {
646        wxString str;
647        int value;
648        if (m_Degrees) {
649            value = int(m_PanAngle);
650        } else {
651            value = int(m_PanAngle * 200.0 / 180.0);
652        }
653        str.Printf(wxT("%03d"), value);
654        DrawIndicatorText(comp_centre_x - triple_zero_width / 2, y_off, str);
655
656        str = wmsg(/*Facing*/203);
657        int w;
658        GetTextExtent(str, &w, NULL);
659        DrawIndicatorText(comp_centre_x - w / 2, y_off + height, str);
660    }
661
662    if (m_Clino) {
663        int angle;
664        wxString str;
665        int width;
666        if (m_Degrees) {
667            static int zero_zero_width = 0;
668            if (!zero_zero_width) {
669                GetTextExtent(wxT("00"), &zero_zero_width, NULL);
670            }
671            width = zero_zero_width;
672            angle = int(-m_TiltAngle);
673            str = angle ? wxString::Format(wxT("%+03d"), angle) : wxT("00");
674        } else {
675            width = triple_zero_width;
676            angle = int(-m_TiltAngle * 200.0 / 180.0);
677            str = angle ? wxString::Format(wxT("%+04d"), angle) : wxT("000");
678        }
679
680        // Adjust horizontal position so the left of the first digit is
681        // always in the same place.
682        int sign_offset = 0;
683        if (angle < 0) {
684            static int minus_width = 0;
685            if (!minus_width) {
686                GetTextExtent(wxT("-"), &minus_width, NULL);
687            }
688            sign_offset = minus_width + 1;
689        } else if (angle > 0) {
690            static int plus_width = 0;
691            if (!plus_width) {
692                GetTextExtent(wxT("+"), &plus_width, NULL);
693            }
694            sign_offset = plus_width + 1;
695        }
696        DrawIndicatorText(elev_centre_x - sign_offset - width / 2, y_off, str);
697
698        str = wmsg(/*Elevation*/118);
699        int w;
700        GetTextExtent(str, &w, NULL);
701        DrawIndicatorText(elev_centre_x - w / 2, y_off + height, str);
702    }
703}
704
705void GfxCore::NattyDrawNames()
706{
707    // Draw station names, without overlapping.
708
709    const unsigned int quantise(GetFontSize() / QUANTISE_FACTOR);
710    const unsigned int quantised_x = m_XSize / quantise;
711    const unsigned int quantised_y = m_YSize / quantise;
712    const size_t buffer_size = quantised_x * quantised_y;
713
714    if (!m_LabelGrid) m_LabelGrid = new char[buffer_size];
715
716    memset((void*) m_LabelGrid, 0, buffer_size);
717
718    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
719    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
720        if (!((m_Surface && (*label)->IsSurface()) ||
721              (m_Legs && (*label)->IsUnderground()) ||
722              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
723            // if this station isn't to be displayed, skip to the next
724            // (last case is for stns with no legs attached)
725            continue;
726        }
727
728        Double x, y, z;
729
730        Transform(**label, &x, &y, &z);
731        // Check if the label is behind us (in perspective view).
732        if (z <= 0.0 || z >= 1.0) continue;
733
734        // Apply a small shift so that translating the view doesn't make which
735        // labels are displayed change as the resulting twinkling effect is
736        // distracting.
737        Double tx, ty, tz;
738        Transform(Vector3(), &tx, &ty, &tz);
739        tx -= floor(tx / quantise) * quantise;
740        ty -= floor(ty / quantise) * quantise;
741
742        tx = x - tx;
743        if (tx < 0) continue;
744
745        ty = y - ty;
746        if (ty < 0) continue;
747
748        unsigned int iy = unsigned(ty) / quantise;
749        if (iy >= quantised_y) continue;
750        unsigned int width = (*label)->get_width();
751        unsigned int ix = unsigned(tx) / quantise;
752        if (ix + width >= quantised_x) continue;
753
754        char * test = m_LabelGrid + ix + iy * quantised_x;
755        if (memchr(test, 1, width)) continue;
756
757        x += 3;
758        y -= GetFontSize() / 2;
759        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
760
761        if (iy > QUANTISE_FACTOR) iy = QUANTISE_FACTOR;
762        test -= quantised_x * iy;
763        iy += 4;
764        while (--iy && test < m_LabelGrid + buffer_size) {
765            memset(test, 1, width);
766            test += quantised_x;
767        }
768    }
769}
770
771void GfxCore::SimpleDrawNames()
772{
773    // Draw all station names, without worrying about overlaps
774    list<LabelInfo*>::const_iterator label = m_Parent->GetLabels();
775    for ( ; label != m_Parent->GetLabelsEnd(); ++label) {
776        if (!((m_Surface && (*label)->IsSurface()) ||
777              (m_Legs && (*label)->IsUnderground()) ||
778              (!(*label)->IsSurface() && !(*label)->IsUnderground()))) {
779            // if this station isn't to be displayed, skip to the next
780            // (last case is for stns with no legs attached)
781            continue;
782        }
783
784        Double x, y, z;
785        Transform(**label, &x, &y, &z);
786
787        // Check if the label is behind us (in perspective view).
788        if (z <= 0) continue;
789
790        x += 3;
791        y -= GetFontSize() / 2;
792        DrawIndicatorText((int)x, (int)y, (*label)->GetText());
793    }
794}
795
796void GfxCore::DrawDepthbar()
797{
798    const int total_block_height =
799        DEPTH_BAR_BLOCK_HEIGHT * (GetNumDepthBands() - 1);
800    const int top = -(total_block_height + DEPTH_BAR_OFFSET_Y);
801    int size = 0;
802
803    wxString* strs = new wxString[GetNumDepthBands()];
804    int band;
805    for (band = 0; band < GetNumDepthBands(); band++) {
806        Double z = m_Parent->GetDepthMin() + m_Parent->GetOffset().GetZ() +
807                   m_Parent->GetDepthExtent() * band / (GetNumDepthBands() - 1);
808        strs[band] = FormatLength(z, false);
809
810        int x;
811        GetTextExtent(strs[band], &x, NULL);
812        if (x > size) size = x;
813    }
814
815    int left = -DEPTH_BAR_OFFSET_X - DEPTH_BAR_BLOCK_WIDTH
816                - DEPTH_BAR_MARGIN - size;
817
818    DrawRectangle(col_BLACK, col_DARK_GREY,
819                  left - DEPTH_BAR_MARGIN - DEPTH_BAR_EXTRA_LEFT_MARGIN,
820                  top - DEPTH_BAR_MARGIN * 2,
821                  DEPTH_BAR_BLOCK_WIDTH + size + DEPTH_BAR_MARGIN * 3 +
822                      DEPTH_BAR_EXTRA_LEFT_MARGIN,
823                  total_block_height + DEPTH_BAR_MARGIN*4);
824
825    int y = top;
826    for (band = 0; band < GetNumDepthBands() - 1; band++) {
827        DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
828                            DEPTH_BAR_BLOCK_WIDTH, DEPTH_BAR_BLOCK_HEIGHT);
829        y += DEPTH_BAR_BLOCK_HEIGHT;
830    }
831
832    y = top - GetFontSize() / 2;
833    left += DEPTH_BAR_BLOCK_WIDTH + 5;
834
835    SetColour(TEXT_COLOUR);
836    for (band = 0; band < GetNumDepthBands(); band++) {
837        DrawIndicatorText(left, y, strs[band]);
838        y += DEPTH_BAR_BLOCK_HEIGHT;
839    }
840
841    delete[] strs;
842}
843
844void GfxCore::DrawDatebar()
845{
846    int total_block_height = DEPTH_BAR_BLOCK_HEIGHT * (GetNumDepthBands() - 1);
847    if (!m_Parent->HasCompleteDateInfo())
848        total_block_height += DEPTH_BAR_BLOCK_HEIGHT + DEPTH_BAR_MARGIN;
849    const int top = -(total_block_height + DEPTH_BAR_OFFSET_Y);
850
851    int size = 0;
852    if (!m_Parent->HasCompleteDateInfo()) {
853        GetTextExtent(wxT("No info"), &size, NULL);
854    }
855
856    wxString* strs = new wxString[GetNumDepthBands()];
857    char buf[128];
858    int band;
859    for (band = 0; band < GetNumDepthBands(); band++) {
860        time_t date = m_Parent->GetDateMin() +
861                   time_t((double)m_Parent->GetDateExtent() * band / (GetNumDepthBands() - 1));
862        size_t res = strftime(buf, sizeof(buf), "%Y-%m-%d", gmtime(&date));
863        // Insert extra "" to avoid trigraphs issues.
864        if (res == 0 || res == sizeof(buf)) strcpy(buf, "?""?""?""?-?""?-?""?");
865        strs[band] = wxString(buf, wxConvUTF8);
866
867        int x;
868        GetTextExtent(strs[band], &x, NULL);
869        if (x > size) size = x;
870    }
871
872    int left = -DEPTH_BAR_OFFSET_X - DEPTH_BAR_BLOCK_WIDTH
873                - DEPTH_BAR_MARGIN - size;
874
875    DrawRectangle(col_BLACK, col_DARK_GREY,
876                  left - DEPTH_BAR_MARGIN - DEPTH_BAR_EXTRA_LEFT_MARGIN,
877                  top - DEPTH_BAR_MARGIN * 2,
878                  DEPTH_BAR_BLOCK_WIDTH + size + DEPTH_BAR_MARGIN * 3 +
879                      DEPTH_BAR_EXTRA_LEFT_MARGIN,
880                  total_block_height + DEPTH_BAR_MARGIN*4);
881
882    int y = top;
883
884    if (!m_Parent->HasCompleteDateInfo()) {
885        DrawShadedRectangle(GetSurfacePen(), GetSurfacePen(), left, y,
886                DEPTH_BAR_BLOCK_WIDTH, DEPTH_BAR_BLOCK_HEIGHT);
887        y += DEPTH_BAR_BLOCK_HEIGHT + DEPTH_BAR_MARGIN;
888    }
889
890    for (band = 0; band < GetNumDepthBands() - 1; band++) {
891        DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
892                            DEPTH_BAR_BLOCK_WIDTH, DEPTH_BAR_BLOCK_HEIGHT);
893        y += DEPTH_BAR_BLOCK_HEIGHT;
894    }
895
896    y = top - GetFontSize() / 2;
897    left += DEPTH_BAR_BLOCK_WIDTH + 5;
898
899    SetColour(TEXT_COLOUR);
900
901    if (!m_Parent->HasCompleteDateInfo()) {
902        y += DEPTH_BAR_MARGIN;
903        DrawIndicatorText(left, y, wxT("No info"));
904        y += DEPTH_BAR_BLOCK_HEIGHT;
905    }
906
907    for (band = 0; band < GetNumDepthBands(); band++) {
908        DrawIndicatorText(left, y, strs[band]);
909        y += DEPTH_BAR_BLOCK_HEIGHT;
910    }
911
912    delete[] strs;
913}
914
915void GfxCore::DrawErrorbar()
916{
917    int total_block_height = DEPTH_BAR_BLOCK_HEIGHT * (GetNumDepthBands() - 1);
918    // Always show the "Not a loop" legend for now (FIXME).
919    total_block_height += DEPTH_BAR_BLOCK_HEIGHT + DEPTH_BAR_MARGIN;
920    const int top = -(total_block_height + DEPTH_BAR_OFFSET_Y);
921
922    int size = 0;
923    GetTextExtent(wxT("Not a loop"), &size, NULL);
924
925    wxString* strs = new wxString[GetNumDepthBands()];
926    int band;
927    for (band = 0; band < GetNumDepthBands(); band++) {
928        double E = MAX_ERROR * band / (GetNumDepthBands() - 1);
929        strs[band].Printf(wxT("%.2f"), E);
930
931        int x;
932        GetTextExtent(strs[band], &x, NULL);
933        if (x > size) size = x;
934    }
935
936    int left = -DEPTH_BAR_OFFSET_X - DEPTH_BAR_BLOCK_WIDTH
937                - DEPTH_BAR_MARGIN - size;
938
939    DrawRectangle(col_BLACK, col_DARK_GREY,
940                  left - DEPTH_BAR_MARGIN - DEPTH_BAR_EXTRA_LEFT_MARGIN,
941                  top - DEPTH_BAR_MARGIN * 2,
942                  DEPTH_BAR_BLOCK_WIDTH + size + DEPTH_BAR_MARGIN * 3 +
943                      DEPTH_BAR_EXTRA_LEFT_MARGIN,
944                  total_block_height + DEPTH_BAR_MARGIN*4);
945
946    int y = top;
947
948    DrawShadedRectangle(GetSurfacePen(), GetSurfacePen(), left, y,
949            DEPTH_BAR_BLOCK_WIDTH, DEPTH_BAR_BLOCK_HEIGHT);
950    y += DEPTH_BAR_BLOCK_HEIGHT + DEPTH_BAR_MARGIN;
951
952    for (band = 0; band < GetNumDepthBands() - 1; band++) {
953        DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
954                            DEPTH_BAR_BLOCK_WIDTH, DEPTH_BAR_BLOCK_HEIGHT);
955        y += DEPTH_BAR_BLOCK_HEIGHT;
956    }
957
958    y = top - GetFontSize() / 2;
959    left += DEPTH_BAR_BLOCK_WIDTH + 5;
960
961    SetColour(TEXT_COLOUR);
962
963    y += DEPTH_BAR_MARGIN;
964    DrawIndicatorText(left, y, wxT("Not in loop"));
965    y += DEPTH_BAR_BLOCK_HEIGHT;
966
967    for (band = 0; band < GetNumDepthBands(); band++) {
968        DrawIndicatorText(left, y, strs[band]);
969        y += DEPTH_BAR_BLOCK_HEIGHT;
970    }
971
972    delete[] strs;
973}
974
975wxString GfxCore::FormatLength(Double size_snap, bool scalebar)
976{
977    wxString str;
978    bool negative = (size_snap < 0.0);
979
980    if (negative) {
981        size_snap = -size_snap;
982    }
983
984    if (size_snap == 0.0) {
985        str = wxT("0");
986    } else if (m_Metric) {
987#ifdef SILLY_UNITS
988        if (size_snap < 1e-12) {
989            str.Printf(wxT("%.3gpm"), size_snap * 1e12);
990        } else if (size_snap < 1e-9) {
991            str.Printf(wxT("%.fpm"), size_snap * 1e12);
992        } else if (size_snap < 1e-6) {
993            str.Printf(wxT("%.fnm"), size_snap * 1e9);
994        } else if (size_snap < 1e-3) {
995            str.Printf(wxT("%.fum"), size_snap * 1e6);
996#else
997        if (size_snap < 1e-3) {
998            str.Printf(wxT("%.3gmm"), size_snap * 1e3);
999#endif
1000        } else if (size_snap < 1e-2) {
1001            str.Printf(wxT("%.fmm"), size_snap * 1e3);
1002        } else if (size_snap < 1.0) {
1003            str.Printf(wxT("%.fcm"), size_snap * 100.0);
1004        } else if (size_snap < 1e3) {
1005            str.Printf(wxT("%.fm"), size_snap);
1006#ifdef SILLY_UNITS
1007        } else if (size_snap < 1e6) {
1008            str.Printf(wxT("%.fkm"), size_snap * 1e-3);
1009        } else if (size_snap < 1e9) {
1010            str.Printf(wxT("%.fMm"), size_snap * 1e-6);
1011        } else {
1012            str.Printf(wxT("%.fGm"), size_snap * 1e-9);
1013#else
1014        } else {
1015            str.Printf(scalebar ? wxT("%.fkm") : wxT("%.2fkm"), size_snap * 1e-3);
1016#endif
1017        }
1018    } else {
1019        size_snap /= METRES_PER_FOOT;
1020        if (scalebar) {
1021            Double inches = size_snap * 12;
1022            if (inches < 1.0) {
1023                str.Printf(wxT("%.3gin"), inches);
1024            } else if (size_snap < 1.0) {
1025                str.Printf(wxT("%.fin"), inches);
1026            } else if (size_snap < 5279.5) {
1027                str.Printf(wxT("%.fft"), size_snap);
1028            } else {
1029                str.Printf(wxT("%.f miles"), size_snap / 5280.0);
1030            }
1031        } else {
1032            str.Printf(wxT("%.fft"), size_snap);
1033        }
1034    }
1035
1036    return negative ? wxString(wxT("-")) + str : str;
1037}
1038
1039void GfxCore::DrawScalebar()
1040{
1041    // Draw the scalebar.
1042    if (GetPerspective()) return;
1043
1044    // Calculate how many metres of survey are currently displayed across the
1045    // screen.
1046    Double across_screen = SurveyUnitsAcrossViewport();
1047
1048    // Convert to imperial measurements if required.
1049    Double multiplier = 1.0;
1050    if (!m_Metric) {
1051        across_screen /= METRES_PER_FOOT;
1052        multiplier = METRES_PER_FOOT;
1053        if (across_screen >= 5280.0 / 0.75) {
1054            across_screen /= 5280.0;
1055            multiplier *= 5280.0;
1056        }
1057    }
1058
1059    // Calculate the length of the scale bar.
1060    Double size_snap = pow(10.0, floor(log10(0.65 * across_screen)));
1061    Double t = across_screen * 0.65 / size_snap;
1062    if (t >= 5.0) {
1063        size_snap *= 5.0;
1064    } else if (t >= 2.0) {
1065        size_snap *= 2.0;
1066    }
1067
1068    if (!m_Metric) size_snap *= multiplier;
1069
1070    // Actual size of the thing in pixels:
1071    int size = int((size_snap / SurveyUnitsAcrossViewport()) * m_XSize);
1072    m_ScaleBarWidth = size;
1073
1074    // Draw it...
1075    const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
1076    int interval = size / 10;
1077
1078    gla_colour col = col_WHITE;
1079    for (int ix = 0; ix < 10; ix++) {
1080        int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
1081
1082        DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
1083
1084        col = (col == col_WHITE) ? col_GREY : col_WHITE;
1085    }
1086
1087    // Add labels.
1088    wxString str = FormatLength(size_snap);
1089
1090    int text_width, text_height;
1091    GetTextExtent(str, &text_width, &text_height);
1092    const int text_y = end_y - text_height + 1;
1093    SetColour(TEXT_COLOUR);
1094    DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
1095    DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
1096}
1097
1098bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
1099{
1100    if (Animating()) return false;
1101
1102    if (point.x < 0 || point.x >= m_XSize ||
1103        point.y < 0 || point.y >= m_YSize) {
1104        return false;
1105    }
1106
1107    SetDataTransform();
1108
1109    if (!m_HitTestGridValid) CreateHitTestGrid();
1110
1111    int grid_x = (point.x * (HITTEST_SIZE - 1)) / m_XSize;
1112    int grid_y = (point.y * (HITTEST_SIZE - 1)) / m_YSize;
1113
1114    LabelInfo *best = NULL;
1115    int dist_sqrd = 25;
1116    int square = grid_x + grid_y * HITTEST_SIZE;
1117    list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
1118
1119    while (iter != m_PointGrid[square].end()) {
1120        LabelInfo *pt = *iter++;
1121
1122        Double cx, cy, cz;
1123
1124        Transform(*pt, &cx, &cy, &cz);
1125
1126        cy = m_YSize - cy;
1127
1128        int dx = point.x - int(cx);
1129        int ds = dx * dx;
1130        if (ds >= dist_sqrd) continue;
1131        int dy = point.y - int(cy);
1132
1133        ds += dy * dy;
1134        if (ds >= dist_sqrd) continue;
1135
1136        dist_sqrd = ds;
1137        best = pt;
1138
1139        if (ds == 0) break;
1140    }
1141
1142    m_Parent->ShowInfo(best);
1143    if (best) {
1144        if (centre) {
1145            // FIXME: allow Ctrl-Click to not set there or something?
1146            CentreOn(*best);
1147            WarpPointer(m_XSize / 2, m_YSize / 2);
1148            SetThere(*best);
1149            m_Parent->SelectTreeItem(best);
1150        }
1151    } else {
1152        // Left-clicking not on a survey cancels the measuring line.
1153        if (centre) {
1154            ClearTreeSelection();
1155        } else {
1156            Double x, y, z;
1157            ReverseTransform(point.x, m_YSize - point.y, &x, &y, &z);
1158            SetHere(Point(Vector3(x, y, z)));
1159            m_here_is_temporary = true;
1160        }
1161    }
1162
1163    return best;
1164}
1165
1166void GfxCore::OnSize(wxSizeEvent& event)
1167{
1168    // Handle a change in window size.
1169
1170    wxSize size = event.GetSize();
1171
1172    if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
1173        // Before things are fully initialised, we sometimes get a bogus
1174        // resize message...
1175        // FIXME have changes in MainFrm cured this?  It still happens with
1176        // 1.0.32 and wxGtk 2.5.2 (load a file from the command line).
1177        // With 1.1.6 and wxGtk 2.4.2 we only get negative sizes if MainFrm
1178        // is resized such that the GfxCore window isn't visible.
1179        //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
1180        return;
1181    }
1182
1183    wxGLCanvas::OnSize(event);
1184
1185    m_XSize = size.GetWidth();
1186    m_YSize = size.GetHeight();
1187
1188    if (m_DoneFirstShow) {
1189        if (m_LabelGrid) {
1190            delete[] m_LabelGrid;
1191            m_LabelGrid = NULL;
1192        }
1193
1194        m_HitTestGridValid = false;
1195
1196        ForceRefresh();
1197    }
1198}
1199
1200void GfxCore::DefaultParameters()
1201{
1202    // Set default viewing parameters.
1203
1204    m_Surface = false;
1205    if (!m_Parent->HasUndergroundLegs()) {
1206        if (m_Parent->HasSurfaceLegs()) {
1207            // If there are surface legs, but no underground legs, turn
1208            // surface surveys on.
1209            m_Surface = true;
1210        } else {
1211            // If there are no legs (e.g. after loading a .pos file), turn
1212            // crosses on.
1213            m_Crosses = true;
1214        }
1215    }
1216
1217    m_PanAngle = 0.0;
1218    if (m_Parent->IsExtendedElevation()) {
1219        m_TiltAngle = 0.0;
1220    } else {
1221        m_TiltAngle = 90.0;
1222    }
1223
1224    SetRotation(m_PanAngle, m_TiltAngle);
1225    SetTranslation(Vector3());
1226
1227    m_RotationStep = 30.0;
1228    m_Rotating = false;
1229    m_SwitchingTo = 0;
1230    m_Entrances = false;
1231    m_FixedPts = false;
1232    m_ExportedPts = false;
1233    m_Grid = false;
1234    m_BoundingBox = false;
1235    m_Tubes = false;
1236    if (GetPerspective()) TogglePerspective();
1237}
1238
1239void GfxCore::Defaults()
1240{
1241    // Restore default scale, rotation and translation parameters.
1242    DefaultParameters();
1243    SetScale(1.0);
1244
1245    // Invalidate all the cached lists.
1246    GLACanvas::FirstShow();
1247
1248    ForceRefresh();
1249}
1250
1251// return: true if animation occured (and ForceRefresh() needs to be called)
1252bool GfxCore::Animate()
1253{
1254    if (!Animating()) return false;
1255
1256    // Don't show pointer coordinates while animating.
1257    // FIXME : only do this when we *START* animating!  Use a static copy
1258    // of the value of "Animating()" last time we were here to track this?
1259    // MainFrm now checks if we're trying to clear already cleared labels
1260    // and just returns, but it might be simpler to check here!
1261    ClearCoords();
1262    m_Parent->ShowInfo(NULL);
1263
1264    static double last_t = 0;
1265    double t;
1266    if (mpeg) {
1267        // FIXME: this glReadPixels call should be in gla-gl.cc
1268        glReadPixels(0, 0, mpeg->GetWidth(), mpeg->GetHeight(), GL_RGB,
1269                     GL_UNSIGNED_BYTE, (GLvoid *)mpeg->GetBuffer());
1270        mpeg->AddFrame();
1271        t = 1.0 / 25.0; // 25 frames per second
1272    } else {
1273        t = timer.Time() * 1.0e-3;
1274        if (t == 0) t = 0.001;
1275        else if (t > 1.0) t = 1.0;
1276        if (last_t > 0) t = (t + last_t) / 2;
1277        last_t = t;
1278    }
1279
1280    if (presentation_mode == PLAYING && pres_speed != 0.0) {
1281        t *= fabs(pres_speed);
1282        while (t >= next_mark_time) {
1283            t -= next_mark_time;
1284            this_mark_total = 0;
1285            PresentationMark prev_mark = next_mark;
1286            if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1287            else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
1288            if (pres_reverse)
1289                next_mark = m_Parent->GetPresMark(MARK_PREV);
1290            else
1291                next_mark = m_Parent->GetPresMark(MARK_NEXT);
1292            if (!next_mark.is_valid()) {
1293                SetView(prev_mark);
1294                presentation_mode = 0;
1295                if (mpeg) {
1296                    delete mpeg;
1297                    mpeg = 0;
1298                }
1299                break;
1300            }
1301
1302            double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1303            if (tmp > 0) {
1304                next_mark_time = tmp;
1305            } else {
1306                double d = (next_mark - prev_mark).magnitude();
1307                // FIXME: should ignore component of d which is unseen in
1308                // non-perspective mode?
1309                next_mark_time = sqrd(d / 30.0);
1310                double a = next_mark.angle - prev_mark.angle;
1311                if (a > 180.0) {
1312                    next_mark.angle -= 360.0;
1313                    a = 360.0 - a;
1314                } else if (a < -180.0) {
1315                    next_mark.angle += 360.0;
1316                    a += 360.0;
1317                } else {
1318                    a = fabs(a);
1319                }
1320                next_mark_time += sqrd(a / 60.0);
1321                double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1322                next_mark_time += sqrd(ta / 60.0);
1323                double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
1324                next_mark_time += sqrd(s / 2.0);
1325                next_mark_time = sqrt(next_mark_time);
1326                // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
1327                //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
1328                //       next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1329                if (tmp < 0) next_mark_time /= -tmp;
1330            }
1331        }
1332
1333        if (presentation_mode) {
1334            // Advance position towards next_mark
1335            double p = t / next_mark_time;
1336            double q = 1 - p;
1337            PresentationMark here = GetView();
1338            if (next_mark.angle < 0) {
1339                if (here.angle >= next_mark.angle + 360.0)
1340                    here.angle -= 360.0;
1341            } else if (next_mark.angle >= 360.0) {
1342                if (here.angle <= next_mark.angle - 360.0)
1343                    here.angle += 360.0;
1344            }
1345            here.assign(q * here + p * next_mark);
1346            here.angle = q * here.angle + p * next_mark.angle;
1347            if (here.angle < 0) here.angle += 360.0;
1348            else if (here.angle >= 360.0) here.angle -= 360.0;
1349            here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
1350            here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
1351            SetView(here);
1352            this_mark_total += t;
1353            next_mark_time -= t;
1354        }
1355    }
1356
1357    // When rotating...
1358    if (m_Rotating) {
1359        TurnCave(m_RotationStep * t);
1360    }
1361
1362    if (m_SwitchingTo == PLAN) {
1363        // When switching to plan view...
1364        TiltCave(90.0 * t);
1365        if (m_TiltAngle == 90.0) {
1366            m_SwitchingTo = 0;
1367        }
1368    } else if (m_SwitchingTo == ELEVATION) {
1369        // When switching to elevation view...
1370        if (fabs(m_TiltAngle) < 90.0 * t) {
1371            m_SwitchingTo = 0;
1372            TiltCave(-m_TiltAngle);
1373        } else if (m_TiltAngle < 0.0) {
1374            TiltCave(90.0 * t);
1375        } else {
1376            TiltCave(-90.0 * t);
1377        }
1378    } else if (m_SwitchingTo) {
1379        int angle = (m_SwitchingTo - NORTH) * 90;
1380        double diff = angle - m_PanAngle;
1381        if (diff < -180) diff += 360;
1382        if (diff > 180) diff -= 360;
1383        double move = 90.0 * t;
1384        if (move >= fabs(diff)) {
1385            TurnCave(diff);
1386            m_SwitchingTo = 0;
1387        } else if (diff < 0) {
1388            TurnCave(-move);
1389        } else {
1390            TurnCave(move);
1391        }
1392    }
1393
1394    return true;
1395}
1396
1397// How much to allow around the box - this is because of the ring shape
1398// at one end of the line.
1399static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1400#define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1401void GfxCore::RefreshLine(const Point &a, const Point &b, const Point &c)
1402{
1403    // Best of all might be to copy the window contents before we draw the
1404    // line, then replace each time we redraw.
1405
1406    // Calculate the minimum rectangle which includes the old and new
1407    // measuring lines to minimise the redraw time
1408    int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
1409    Double X, Y, Z;
1410    if (a.IsValid()) {
1411        if (!Transform(a, &X, &Y, &Z)) {
1412            printf("oops\n");
1413        } else {
1414            int x = int(X);
1415            int y = m_YSize - 1 - int(Y);
1416            l = x - MARGIN;
1417            r = x + MARGIN;
1418            u = y + MARGIN;
1419            d = y - MARGIN;
1420        }
1421    }
1422    if (b.IsValid()) {
1423        if (!Transform(b, &X, &Y, &Z)) {
1424            printf("oops\n");
1425        } else {
1426            int x = int(X);
1427            int y = m_YSize - 1 - int(Y);
1428            l = min(l, x - MARGIN);
1429            r = max(r, x + MARGIN);
1430            u = max(u, y + MARGIN);
1431            d = min(d, y - MARGIN);
1432        }
1433    }
1434    if (c.IsValid()) {
1435        if (!Transform(c, &X, &Y, &Z)) {
1436            printf("oops\n");
1437        } else {
1438            int x = int(X);
1439            int y = m_YSize - 1 - int(Y);
1440            l = min(l, x - MARGIN);
1441            r = max(r, x + MARGIN);
1442            u = max(u, y + MARGIN);
1443            d = min(d, y - MARGIN);
1444        }
1445    }
1446    const wxRect R(l, d, r - l, u - d);
1447    Refresh(false, &R);
1448}
1449
1450void GfxCore::SetHere()
1451{
1452    if (!m_here.IsValid()) return;
1453    Point old = m_here;
1454    m_here.Invalidate();
1455    RefreshLine(old, m_there, m_here);
1456}
1457
1458void GfxCore::SetHere(const Point &p)
1459{
1460    Point old = m_here;
1461    m_here = p;
1462    RefreshLine(old, m_there, m_here);
1463    m_here_is_temporary = false;
1464}
1465
1466void GfxCore::SetThere()
1467{
1468    if (!m_there.IsValid()) return;
1469    Point old = m_there;
1470    m_there.Invalidate();
1471    RefreshLine(m_here, old, m_there);
1472}
1473
1474void GfxCore::SetThere(const Point &p)
1475{
1476    Point old = m_there;
1477    m_there = p;
1478    RefreshLine(m_here, old, m_there);
1479}
1480
1481void GfxCore::CreateHitTestGrid()
1482{
1483    // Clear hit-test grid.
1484    for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
1485        m_PointGrid[i].clear();
1486    }
1487
1488    // Fill the grid.
1489    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1490    list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1491    while (pos != end) {
1492        LabelInfo* label = *pos++;
1493
1494        if (!((m_Surface && label->IsSurface()) ||
1495              (m_Legs && label->IsUnderground()) ||
1496              (!label->IsSurface() && !label->IsUnderground()))) {
1497            // if this station isn't to be displayed, skip to the next
1498            // (last case is for stns with no legs attached)
1499            continue;
1500        }
1501
1502        // Calculate screen coordinates.
1503        Double cx, cy, cz;
1504        Transform(*label, &cx, &cy, &cz);
1505        if (cx < 0 || cx >= m_XSize) continue;
1506        if (cy < 0 || cy >= m_YSize) continue;
1507
1508        cy = m_YSize - cy;
1509
1510        // On-screen, so add to hit-test grid...
1511        int grid_x = int((cx * (HITTEST_SIZE - 1)) / m_XSize);
1512        int grid_y = int((cy * (HITTEST_SIZE - 1)) / m_YSize);
1513
1514        m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
1515    }
1516
1517    m_HitTestGridValid = true;
1518}
1519
1520//
1521//  Methods for controlling the orientation of the survey
1522//
1523
1524void GfxCore::TurnCave(Double angle)
1525{
1526    // Turn the cave around its z-axis by a given angle.
1527
1528    m_PanAngle += angle;
1529    if (m_PanAngle >= 360.0) {
1530        m_PanAngle -= 360.0;
1531    } else if (m_PanAngle < 0.0) {
1532        m_PanAngle += 360.0;
1533    }
1534
1535    m_HitTestGridValid = false;
1536    if (m_here_is_temporary) SetHere();
1537
1538    SetRotation(m_PanAngle, m_TiltAngle);
1539}
1540
1541void GfxCore::TurnCaveTo(Double angle)
1542{
1543    timer.Start(drawtime);
1544    int new_switching_to = ((int)angle) / 90 + NORTH;
1545    if (new_switching_to == m_SwitchingTo) {
1546        // A second order to switch takes us there right away
1547        TurnCave(angle - m_PanAngle);
1548        m_SwitchingTo = 0;
1549        ForceRefresh();
1550    } else {
1551        m_SwitchingTo = new_switching_to;
1552    }
1553}
1554
1555void GfxCore::TiltCave(Double tilt_angle)
1556{
1557    // Tilt the cave by a given angle.
1558    if (m_TiltAngle + tilt_angle > 90.0) {
1559        m_TiltAngle = 90.0;
1560    } else if (m_TiltAngle + tilt_angle < -90.0) {
1561        m_TiltAngle = -90.0;
1562    } else {
1563        m_TiltAngle += tilt_angle;
1564    }
1565
1566    m_HitTestGridValid = false;
1567    if (m_here_is_temporary) SetHere();
1568
1569    SetRotation(m_PanAngle, m_TiltAngle);
1570}
1571
1572void GfxCore::TranslateCave(int dx, int dy)
1573{
1574    AddTranslationScreenCoordinates(dx, dy);
1575    m_HitTestGridValid = false;
1576
1577    if (m_here_is_temporary) SetHere();
1578
1579    ForceRefresh();
1580}
1581
1582void GfxCore::DragFinished()
1583{
1584    m_MouseOutsideCompass = m_MouseOutsideElev = false;
1585    ForceRefresh();
1586}
1587
1588void GfxCore::ClearCoords()
1589{
1590    m_Parent->ClearCoords();
1591}
1592
1593void GfxCore::SetCoords(wxPoint point)
1594{
1595    // We can't work out 2D coordinates from a perspective view, and it
1596    // doesn't really make sense to show coordinates while we're animating.
1597    if (GetPerspective() || Animating()) return;
1598
1599    // Update the coordinate or altitude display, given the (x, y) position in
1600    // window coordinates.  The relevant display is updated depending on
1601    // whether we're in plan or elevation view.
1602
1603    Double cx, cy, cz;
1604
1605    SetDataTransform();
1606    ReverseTransform(point.x, m_YSize - 1 - point.y, &cx, &cy, &cz);
1607
1608    if (ShowingPlan()) {
1609        m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
1610                            cy + m_Parent->GetOffset().GetY());
1611    } else if (ShowingElevation()) {
1612        m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ());
1613    } else {
1614        m_Parent->ClearCoords();
1615    }
1616}
1617
1618int GfxCore::GetCompassXPosition() const
1619{
1620    // Return the x-coordinate of the centre of the compass in window
1621    // coordinates.
1622    return m_XSize - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE / 2;
1623}
1624
1625int GfxCore::GetClinoXPosition() const
1626{
1627    // Return the x-coordinate of the centre of the compass in window
1628    // coordinates.
1629    return m_XSize - GetClinoOffset() - INDICATOR_BOX_SIZE / 2;
1630}
1631
1632int GfxCore::GetIndicatorYPosition() const
1633{
1634    // Return the y-coordinate of the centre of the indicators in window
1635    // coordinates.
1636    return m_YSize - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
1637}
1638
1639int GfxCore::GetIndicatorRadius() const
1640{
1641    // Return the radius of each indicator.
1642    return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
1643}
1644
1645bool GfxCore::PointWithinCompass(wxPoint point) const
1646{
1647    // Determine whether a point (in window coordinates) lies within the
1648    // compass.
1649    if (!ShowingCompass()) return false;
1650
1651    glaCoord dx = point.x - GetCompassXPosition();
1652    glaCoord dy = point.y - GetIndicatorYPosition();
1653    glaCoord radius = GetIndicatorRadius();
1654
1655    return (dx * dx + dy * dy <= radius * radius);
1656}
1657
1658bool GfxCore::PointWithinClino(wxPoint point) const
1659{
1660    // Determine whether a point (in window coordinates) lies within the clino.
1661    if (!ShowingClino()) return false;
1662
1663    glaCoord dx = point.x - GetClinoXPosition();
1664    glaCoord dy = point.y - GetIndicatorYPosition();
1665    glaCoord radius = GetIndicatorRadius();
1666
1667    return (dx * dx + dy * dy <= radius * radius);
1668}
1669
1670bool GfxCore::PointWithinScaleBar(wxPoint point) const
1671{
1672    // Determine whether a point (in window coordinates) lies within the scale
1673    // bar.
1674    if (!ShowingScaleBar()) return false;
1675
1676    return (point.x >= SCALE_BAR_OFFSET_X &&
1677            point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
1678            point.y <= m_YSize - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
1679            point.y >= m_YSize - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
1680}
1681
1682void GfxCore::SetCompassFromPoint(wxPoint point)
1683{
1684    // Given a point in window coordinates, set the heading of the survey.  If
1685    // the point is outside the compass, it snaps to 45 degree intervals;
1686    // otherwise it operates as normal.
1687
1688    wxCoord dx = point.x - GetCompassXPosition();
1689    wxCoord dy = point.y - GetIndicatorYPosition();
1690    wxCoord radius = GetIndicatorRadius();
1691
1692    double angle = deg(atan2(double(dx), double(dy))) - 180.0;
1693    if (dx * dx + dy * dy <= radius * radius) {
1694        TurnCave(angle - m_PanAngle);
1695        m_MouseOutsideCompass = false;
1696    } else {
1697        TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
1698        m_MouseOutsideCompass = true;
1699    }
1700
1701    ForceRefresh();
1702}
1703
1704void GfxCore::SetClinoFromPoint(wxPoint point)
1705{
1706    // Given a point in window coordinates, set the elevation of the survey.
1707    // If the point is outside the clino, it snaps to 90 degree intervals;
1708    // otherwise it operates as normal.
1709
1710    glaCoord dx = point.x - GetClinoXPosition();
1711    glaCoord dy = point.y - GetIndicatorYPosition();
1712    glaCoord radius = GetIndicatorRadius();
1713
1714    if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
1715        TiltCave(deg(atan2(double(dy), double(dx))) - m_TiltAngle);
1716        m_MouseOutsideElev = false;
1717    } else if (dy >= INDICATOR_MARGIN) {
1718        TiltCave(90.0 - m_TiltAngle);
1719        m_MouseOutsideElev = true;
1720    } else if (dy <= -INDICATOR_MARGIN) {
1721        TiltCave(-90.0 - m_TiltAngle);
1722        m_MouseOutsideElev = true;
1723    } else {
1724        TiltCave(-m_TiltAngle);
1725        m_MouseOutsideElev = true;
1726    }
1727
1728    ForceRefresh();
1729}
1730
1731void GfxCore::SetScaleBarFromOffset(wxCoord dx)
1732{
1733    // Set the scale of the survey, given an offset as to how much the mouse has
1734    // been dragged over the scalebar since the last scale change.
1735
1736    SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
1737    ForceRefresh();
1738}
1739
1740void GfxCore::RedrawIndicators()
1741{
1742    // Redraw the compass and clino indicators.
1743
1744    const wxRect r(m_XSize - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE*2 -
1745                     INDICATOR_GAP,
1746                   m_YSize - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
1747                   INDICATOR_BOX_SIZE*2 + INDICATOR_GAP,
1748                   INDICATOR_BOX_SIZE);
1749
1750    Refresh(false, &r);
1751}
1752
1753void GfxCore::StartRotation()
1754{
1755    // Start the survey rotating.
1756
1757    m_Rotating = true;
1758    timer.Start(drawtime);
1759}
1760
1761void GfxCore::ToggleRotation()
1762{
1763    // Toggle the survey rotation on/off.
1764
1765    if (m_Rotating) {
1766        StopRotation();
1767    } else {
1768        StartRotation();
1769    }
1770}
1771
1772void GfxCore::StopRotation()
1773{
1774    // Stop the survey rotating.
1775
1776    m_Rotating = false;
1777    ForceRefresh();
1778}
1779
1780bool GfxCore::IsExtendedElevation() const
1781{
1782    return m_Parent->IsExtendedElevation();
1783}
1784
1785void GfxCore::ReverseRotation()
1786{
1787    // Reverse the direction of rotation.
1788
1789    m_RotationStep = -m_RotationStep;
1790}
1791
1792void GfxCore::RotateSlower(bool accel)
1793{
1794    // Decrease the speed of rotation, optionally by an increased amount.
1795
1796    m_RotationStep /= accel ? 1.44 : 1.2;
1797    if (m_RotationStep < 1.0) {
1798        m_RotationStep = 1.0;
1799    }
1800}
1801
1802void GfxCore::RotateFaster(bool accel)
1803{
1804    // Increase the speed of rotation, optionally by an increased amount.
1805
1806    m_RotationStep *= accel ? 1.44 : 1.2;
1807    if (m_RotationStep > 450.0) {
1808        m_RotationStep = 450.0;
1809    }
1810}
1811
1812void GfxCore::SwitchToElevation()
1813{
1814    // Perform an animated switch to elevation view.
1815
1816    switch (m_SwitchingTo) {
1817        case 0:
1818            timer.Start(drawtime);
1819            m_SwitchingTo = ELEVATION;
1820            break;
1821
1822        case PLAN:
1823            m_SwitchingTo = ELEVATION;
1824            break;
1825
1826        case ELEVATION:
1827            // a second order to switch takes us there right away
1828            TiltCave(-m_TiltAngle);
1829            m_SwitchingTo = 0;
1830            ForceRefresh();
1831    }
1832}
1833
1834void GfxCore::SwitchToPlan()
1835{
1836    // Perform an animated switch to plan view.
1837
1838    switch (m_SwitchingTo) {
1839        case 0:
1840            timer.Start(drawtime);
1841            m_SwitchingTo = PLAN;
1842            break;
1843
1844        case ELEVATION:
1845            m_SwitchingTo = PLAN;
1846            break;
1847
1848        case PLAN:
1849            // A second order to switch takes us there right away
1850            TiltCave(90.0 - m_TiltAngle);
1851            m_SwitchingTo = 0;
1852            ForceRefresh();
1853    }
1854}
1855
1856void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
1857{
1858
1859    SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
1860    Double scale = HUGE_VAL;
1861    const Vector3 ext = m_Parent->GetExtent();
1862    if (xmax > xmin) {
1863        Double s = ext.GetX() / (xmax - xmin);
1864        if (s < scale) scale = s;
1865    }
1866    if (ymax > ymin) {
1867        Double s = ext.GetY() / (ymax - ymin);
1868        if (s < scale) scale = s;
1869    }
1870    if (!ShowingPlan() && zmax > zmin) {
1871        Double s = ext.GetZ() / (zmax - zmin);
1872        if (s < scale) scale = s;
1873    }
1874    if (scale != HUGE_VAL) SetScale(scale);
1875    ForceRefresh();
1876}
1877
1878bool GfxCore::CanRaiseViewpoint() const
1879{
1880    // Determine if the survey can be viewed from a higher angle of elevation.
1881
1882    return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
1883}
1884
1885bool GfxCore::CanLowerViewpoint() const
1886{
1887    // Determine if the survey can be viewed from a lower angle of elevation.
1888
1889    return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
1890}
1891
1892bool GfxCore::HasDepth() const
1893{
1894    return m_Parent->GetDepthExtent() == 0.0;
1895}
1896
1897bool GfxCore::HasRangeOfDates() const
1898{
1899    return m_Parent->GetDateExtent() > 0;
1900}
1901
1902bool GfxCore::HasErrorInformation() const
1903{
1904    return m_Parent->HasErrorInformation();
1905}
1906
1907bool GfxCore::ShowingPlan() const
1908{
1909    // Determine if the survey is in plan view.
1910
1911    return (m_TiltAngle == 90.0);
1912}
1913
1914bool GfxCore::ShowingElevation() const
1915{
1916    // Determine if the survey is in elevation view.
1917
1918    return (m_TiltAngle == 0.0);
1919}
1920
1921bool GfxCore::ShowingMeasuringLine() const
1922{
1923    // Determine if the measuring line is being shown.
1924
1925    return (m_there.IsValid() && m_here.IsValid());
1926}
1927
1928void GfxCore::ToggleFlag(bool* flag, int update)
1929{
1930    *flag = !*flag;
1931    if (update == UPDATE_BLOBS) {
1932        UpdateBlobs();
1933    } else if (update == UPDATE_BLOBS_AND_CROSSES) {
1934        UpdateBlobs();
1935        InvalidateList(LIST_CROSSES);
1936    }
1937    ForceRefresh();
1938}
1939
1940int GfxCore::GetNumEntrances() const
1941{
1942    return m_Parent->GetNumEntrances();
1943}
1944
1945int GfxCore::GetNumFixedPts() const
1946{
1947    return m_Parent->GetNumFixedPts();
1948}
1949
1950int GfxCore::GetNumExportedPts() const
1951{
1952    return m_Parent->GetNumExportedPts();
1953}
1954
1955void GfxCore::ClearTreeSelection()
1956{
1957    m_Parent->ClearTreeSelection();
1958}
1959
1960void GfxCore::CentreOn(const Point &p)
1961{
1962    SetTranslation(-p);
1963    m_HitTestGridValid = false;
1964
1965    ForceRefresh();
1966}
1967
1968void GfxCore::ForceRefresh()
1969{
1970    Refresh(false);
1971}
1972
1973void GfxCore::GenerateList(unsigned int l)
1974{
1975    assert(m_HaveData);
1976
1977    switch (l) {
1978        case LIST_COMPASS:
1979            DrawCompass();
1980            break;
1981        case LIST_CLINO:
1982            DrawClino();
1983            break;
1984        case LIST_CLINO_BACK:
1985            DrawClinoBack();
1986            break;
1987        case LIST_DEPTHBAR:
1988            DrawDepthbar();
1989            break;
1990        case LIST_DATEBAR:
1991            DrawDatebar();
1992            break;
1993        case LIST_ERRORBAR:
1994            DrawErrorbar();
1995            break;
1996        case LIST_UNDERGROUND_LEGS:
1997            GenerateDisplayList();
1998            break;
1999        case LIST_TUBES:
2000            GenerateDisplayListTubes();
2001            break;
2002        case LIST_SURFACE_LEGS:
2003            GenerateDisplayListSurface();
2004            break;
2005        case LIST_BLOBS:
2006            GenerateBlobsDisplayList();
2007            break;
2008        case LIST_CROSSES: {
2009            BeginCrosses();
2010            SetColour(col_LIGHT_GREY);
2011            list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2012            while (pos != m_Parent->GetLabelsEnd()) {
2013                const LabelInfo* label = *pos++;
2014
2015                if ((m_Surface && label->IsSurface()) ||
2016                    (m_Legs && label->IsUnderground()) ||
2017                    (!label->IsSurface() && !label->IsUnderground())) {
2018                    // Check if this station should be displayed
2019                    // (last case is for stns with no legs attached)
2020                    DrawCross(label->GetX(), label->GetY(), label->GetZ());
2021                }
2022            }
2023            EndCrosses();
2024            break;
2025        }
2026        case LIST_GRID:
2027            DrawGrid();
2028            break;
2029        case LIST_SHADOW:
2030            GenerateDisplayListShadow();
2031            break;
2032        default:
2033            assert(false);
2034            break;
2035    }
2036}
2037
2038void GfxCore::ToggleSmoothShading()
2039{
2040    GLACanvas::ToggleSmoothShading();
2041    InvalidateList(LIST_TUBES);
2042    ForceRefresh();
2043}
2044
2045void GfxCore::GenerateDisplayList()
2046{
2047    // Generate the display list for the underground legs.
2048    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2049    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2050    while (trav != tend) {
2051        (this->*AddPoly)(*trav);
2052        ++trav;
2053    }
2054}
2055
2056void GfxCore::GenerateDisplayListTubes()
2057{
2058    // Generate the display list for the tubes.
2059    list<vector<XSect> >::const_iterator trav = m_Parent->tubes_begin();
2060    list<vector<XSect> >::const_iterator tend = m_Parent->tubes_end();
2061    while (trav != tend) {
2062        SkinPassage(*trav);
2063        ++trav;
2064    }
2065}
2066
2067void GfxCore::GenerateDisplayListSurface()
2068{
2069    // Generate the display list for the surface legs.
2070    EnableDashedLines();
2071    list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2072    list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
2073    while (trav != tend) {
2074        if (m_ColourBy == COLOUR_BY_ERROR) {
2075            AddPolylineError(*trav);
2076        } else {
2077            AddPolyline(*trav);
2078        }
2079        ++trav;
2080    }
2081    DisableDashedLines();
2082}
2083
2084void GfxCore::GenerateDisplayListShadow()
2085{
2086    SetColour(col_BLACK);
2087    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2088    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2089    while (trav != tend) {
2090        AddPolylineShadow(*trav);
2091        ++trav;
2092    }
2093}
2094
2095// Plot blobs.
2096void GfxCore::GenerateBlobsDisplayList()
2097{
2098    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2099          m_Parent->GetNumHighlightedPts()))
2100        return;
2101
2102    // Plot blobs.
2103    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2104    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2105    BeginBlobs();
2106    while (pos != m_Parent->GetLabelsEnd()) {
2107        const LabelInfo* label = *pos++;
2108
2109        // When more than one flag is set on a point:
2110        // search results take priority over entrance highlighting
2111        // which takes priority over fixed point
2112        // highlighting, which in turn takes priority over exported
2113        // point highlighting.
2114
2115        if (!((m_Surface && label->IsSurface()) ||
2116              (m_Legs && label->IsUnderground()) ||
2117              (!label->IsSurface() && !label->IsUnderground()))) {
2118            // if this station isn't to be displayed, skip to the next
2119            // (last case is for stns with no legs attached)
2120            continue;
2121        }
2122
2123        gla_colour col;
2124
2125        if (label->IsHighLighted()) {
2126            col = col_YELLOW;
2127        } else if (m_Entrances && label->IsEntrance()) {
2128            col = col_GREEN;
2129        } else if (m_FixedPts && label->IsFixedPt()) {
2130            col = col_RED;
2131        } else if (m_ExportedPts && label->IsExportedPt()) {
2132            col = col_TURQUOISE;
2133        } else {
2134            continue;
2135        }
2136
2137        // Stations are sorted by blob type, so colour changes are infrequent.
2138        if (col != prev_col) {
2139            SetColour(col);
2140            prev_col = col;
2141        }
2142        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
2143    }
2144    EndBlobs();
2145}
2146
2147void GfxCore::DrawIndicators()
2148{
2149    // Draw depthbar.
2150    if (m_Depthbar) {
2151       if (m_ColourBy == COLOUR_BY_DEPTH && m_Parent->GetDepthExtent() != 0.0) {
2152           DrawList2D(LIST_DEPTHBAR, m_XSize, m_YSize, 0);
2153       } else if (m_ColourBy == COLOUR_BY_DATE && m_Parent->GetDateExtent()) {
2154           DrawList2D(LIST_DATEBAR, m_XSize, m_YSize, 0);
2155       } else if (m_ColourBy == COLOUR_BY_ERROR && m_Parent->HasErrorInformation()) {
2156           DrawList2D(LIST_ERRORBAR, m_XSize, m_YSize, 0);
2157       }
2158    }
2159
2160    // Draw compass or elevation/heading indicators.
2161    if (m_Compass || m_Clino) {
2162        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
2163    }
2164
2165    // Draw scalebar.
2166    if (m_Scalebar) {
2167        DrawScalebar();
2168    }
2169}
2170
2171void GfxCore::PlaceVertexWithColour(const Vector3 & v, Double factor)
2172{
2173    SetColour(GetSurfacePen(), factor); // FIXME : assumes surface pen is white!
2174    PlaceVertex(v);
2175}
2176
2177void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2178{
2179    // Set the drawing colour based on the altitude.
2180    Double z_ext = m_Parent->GetDepthExtent();
2181    assert(z_ext > 0);
2182
2183    Double z = v.GetZ() - m_Parent->GetDepthMin();
2184    // points arising from tubes may be slightly outside the limits...
2185    if (z < 0) z = 0;
2186    if (z > z_ext) z = z_ext;
2187
2188    Double how_far = z / z_ext;
2189    assert(how_far >= 0.0);
2190    assert(how_far <= 1.0);
2191
2192    int band = int(floor(how_far * (GetNumDepthBands() - 1)));
2193    GLAPen pen1 = GetPen(band);
2194    if (band < GetNumDepthBands() - 1) {
2195        const GLAPen& pen2 = GetPen(band + 1);
2196
2197        Double interval = z_ext / (GetNumDepthBands() - 1);
2198        Double into_band = z / interval - band;
2199
2200//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2201//             z_offset, interval, band);
2202        // FIXME: why do we need to clamp here?  Is it because the walls can
2203        // extend further up/down than the centre-line?
2204        if (into_band < 0.0) into_band = 0.0;
2205        if (into_band > 1.0) into_band = 1.0;
2206        assert(into_band >= 0.0);
2207        assert(into_band <= 1.0);
2208
2209        pen1.Interpolate(pen2, into_band);
2210    }
2211    SetColour(pen1, factor);
2212
2213    PlaceVertex(v);
2214}
2215
2216void GfxCore::SplitLineAcrossBands(int band, int band2,
2217                                   const Vector3 &p, const Vector3 &q,
2218                                   Double factor)
2219{
2220    const int step = (band < band2) ? 1 : -1;
2221    for (int i = band; i != band2; i += step) {
2222        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
2223
2224        // Find the intersection point of the line p -> q
2225        // with the plane parallel to the xy-plane with z-axis intersection z.
2226        assert(q.GetZ() - p.GetZ() != 0.0);
2227
2228        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
2229//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
2230
2231        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
2232        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
2233
2234        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
2235    }
2236}
2237
2238int GfxCore::GetDepthColour(Double z) const
2239{
2240    // Return the (0-based) depth colour band index for a z-coordinate.
2241    Double z_ext = m_Parent->GetDepthExtent();
2242    assert(z_ext > 0);
2243    z -= m_Parent->GetDepthMin();
2244    z += z_ext / 2;
2245    return int(z / z_ext * (GetNumDepthBands() - 1));
2246}
2247
2248Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
2249{
2250    // Return the z-coordinate of the depth colour boundary between
2251    // two adjacent depth colour bands (specified by 0-based indices).
2252
2253    assert((a == b - 1) || (a == b + 1));
2254    if (GetNumDepthBands() == 1) return 0;
2255
2256    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
2257    Double z_ext = m_Parent->GetDepthExtent();
2258    return (z_ext * band / (GetNumDepthBands() - 1)) - z_ext / 2
2259        + m_Parent->GetDepthMin();
2260}
2261
2262void GfxCore::AddPolyline(const traverse & centreline)
2263{
2264    BeginPolyline();
2265    SetColour(GetSurfacePen());
2266    vector<PointInfo>::const_iterator i = centreline.begin();
2267    PlaceVertex(*i);
2268    ++i;
2269    while (i != centreline.end()) {
2270        PlaceVertex(*i);
2271        ++i;
2272    }
2273    EndPolyline();
2274}
2275
2276void GfxCore::AddPolylineShadow(const traverse & centreline)
2277{
2278    BeginPolyline();
2279    const double z = -0.5 * m_Parent->GetZExtent();
2280    vector<PointInfo>::const_iterator i = centreline.begin();
2281    PlaceVertex(i->GetX(), i->GetY(), z);
2282    ++i;
2283    while (i != centreline.end()) {
2284        PlaceVertex(i->GetX(), i->GetY(), z);
2285        ++i;
2286    }
2287    EndPolyline();
2288}
2289
2290void GfxCore::AddPolylineDepth(const traverse & centreline)
2291{
2292    BeginPolyline();
2293    vector<PointInfo>::const_iterator i, prev_i;
2294    i = centreline.begin();
2295    int band0 = GetDepthColour(i->GetZ());
2296    PlaceVertexWithDepthColour(*i);
2297    prev_i = i;
2298    ++i;
2299    while (i != centreline.end()) {
2300        int band = GetDepthColour(i->GetZ());
2301        if (band != band0) {
2302            SplitLineAcrossBands(band0, band, *prev_i, *i);
2303            band0 = band;
2304        }
2305        PlaceVertexWithDepthColour(*i);
2306        prev_i = i;
2307        ++i;
2308    }
2309    EndPolyline();
2310}
2311
2312void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
2313                               const Vector3 &c, const Vector3 &d)
2314{
2315    Vector3 normal = (a - c) * (d - b);
2316    normal.normalise();
2317    Double factor = dot(normal, light) * .3 + .7;
2318    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2319    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2320    // FIXME: should plot triangles instead to avoid rendering glitches.
2321    BeginQuadrilaterals();
2322    // FIXME: these glTexCoord2i calls should be in gla-gl.cc
2323    glTexCoord2i(0, 0);
2324    PlaceVertexWithColour(a, factor);
2325    glTexCoord2i(w, 0);
2326    PlaceVertexWithColour(b, factor);
2327    glTexCoord2i(w, h);
2328    PlaceVertexWithColour(c, factor);
2329    glTexCoord2i(0, h);
2330    PlaceVertexWithColour(d, factor);
2331    EndQuadrilaterals();
2332}
2333
2334void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
2335                                    const Vector3 &c, const Vector3 &d)
2336{
2337    Vector3 normal = (a - c) * (d - b);
2338    normal.normalise();
2339    Double factor = dot(normal, light) * .3 + .7;
2340    int a_band, b_band, c_band, d_band;
2341    a_band = GetDepthColour(a.GetZ());
2342    a_band = min(max(a_band, 0), GetNumDepthBands());
2343    b_band = GetDepthColour(b.GetZ());
2344    b_band = min(max(b_band, 0), GetNumDepthBands());
2345    c_band = GetDepthColour(c.GetZ());
2346    c_band = min(max(c_band, 0), GetNumDepthBands());
2347    d_band = GetDepthColour(d.GetZ());
2348    d_band = min(max(d_band, 0), GetNumDepthBands());
2349    // All this splitting is incorrect - we need to make a separate polygon
2350    // for each depth band...
2351    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2352    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2353    // FIXME: should plot triangles instead to avoid rendering glitches.
2354    BeginPolygon();
2355////    PlaceNormal(normal);
2356    // FIXME: these glTexCoord2i calls should be in gla-gl.cc
2357    glTexCoord2i(0, 0);
2358    PlaceVertexWithDepthColour(a, factor);
2359    if (a_band != b_band) {
2360        SplitLineAcrossBands(a_band, b_band, a, b, factor);
2361    }
2362    glTexCoord2i(w, 0);
2363    PlaceVertexWithDepthColour(b, factor);
2364    if (b_band != c_band) {
2365        SplitLineAcrossBands(b_band, c_band, b, c, factor);
2366    }
2367    glTexCoord2i(w, h);
2368    PlaceVertexWithDepthColour(c, factor);
2369    if (c_band != d_band) {
2370        SplitLineAcrossBands(c_band, d_band, c, d, factor);
2371    }
2372    glTexCoord2i(0, h);
2373    PlaceVertexWithDepthColour(d, factor);
2374    if (d_band != a_band) {
2375        SplitLineAcrossBands(d_band, a_band, d, a, factor);
2376    }
2377    EndPolygon();
2378}
2379
2380void GfxCore::SetColourFromDate(time_t date, Double factor)
2381{
2382    // Set the drawing colour based on a date.
2383
2384    if (date == 0) {
2385        SetColour(GetSurfacePen(), factor);
2386        return;
2387    }
2388
2389    time_t date_ext = m_Parent->GetDateExtent();
2390    assert(date_ext > 0);
2391    time_t date_offset = date - m_Parent->GetDateMin();
2392
2393    Double how_far = (Double)date_offset / date_ext;
2394    assert(how_far >= 0.0);
2395    assert(how_far <= 1.0);
2396
2397    int band = int(floor(how_far * (GetNumDepthBands() - 1)));
2398    GLAPen pen1 = GetPen(band);
2399    if (band < GetNumDepthBands() - 1) {
2400        const GLAPen& pen2 = GetPen(band + 1);
2401
2402        Double interval = date_ext / (GetNumDepthBands() - 1);
2403        Double into_band = date_offset / interval - band;
2404
2405//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2406//             z_offset, interval, band);
2407        // FIXME: why do we need to clamp here?  Is it because the walls can
2408        // extend further up/down than the centre-line?
2409        if (into_band < 0.0) into_band = 0.0;
2410        if (into_band > 1.0) into_band = 1.0;
2411        assert(into_band >= 0.0);
2412        assert(into_band <= 1.0);
2413
2414        pen1.Interpolate(pen2, into_band);
2415    }
2416    SetColour(pen1, factor);
2417}
2418
2419void GfxCore::AddPolylineDate(const traverse & centreline)
2420{
2421    BeginPolyline();
2422    vector<PointInfo>::const_iterator i, prev_i;
2423    i = centreline.begin();
2424    time_t date = i->GetDate();
2425    SetColourFromDate(date, 1.0);
2426    PlaceVertex(*i);
2427    prev_i = i;
2428    while (++i != centreline.end()) {
2429        time_t newdate = i->GetDate();
2430        if (newdate != date) {
2431            EndPolyline();
2432            BeginPolyline();
2433            date = newdate;
2434            SetColourFromDate(date, 1.0);
2435            PlaceVertex(*prev_i);
2436        }
2437        PlaceVertex(*i);
2438        prev_i = i;
2439    }
2440    EndPolyline();
2441}
2442
2443static time_t static_date_hack; // FIXME
2444
2445void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
2446                                   const Vector3 &c, const Vector3 &d)
2447{
2448    Vector3 normal = (a - c) * (d - b);
2449    normal.normalise();
2450    Double factor = dot(normal, light) * .3 + .7;
2451    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2452    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2453    // FIXME: should plot triangles instead to avoid rendering glitches.
2454    BeginPolygon();
2455////    PlaceNormal(normal);
2456    SetColourFromDate(static_date_hack, factor);
2457    // FIXME: these glTexCoord2i calls should be in gla-gl.cc
2458    glTexCoord2i(0, 0);
2459    PlaceVertex(a);
2460    glTexCoord2i(w, 0);
2461    PlaceVertex(b);
2462    glTexCoord2i(w, h);
2463    PlaceVertex(c);
2464    glTexCoord2i(0, h);
2465    PlaceVertex(d);
2466    EndPolygon();
2467}
2468
2469static double static_E_hack; // FIXME
2470
2471void GfxCore::SetColourFromError(double E, Double factor)
2472{
2473    // Set the drawing colour based on an error value.
2474
2475    if (E < 0) {
2476        SetColour(GetSurfacePen(), factor);
2477        return;
2478    }
2479
2480    Double how_far = E / MAX_ERROR;
2481    assert(how_far >= 0.0);
2482    if (how_far > 1.0) how_far = 1.0;
2483
2484    int band = int(floor(how_far * (GetNumDepthBands() - 1)));
2485    GLAPen pen1 = GetPen(band);
2486    if (band < GetNumDepthBands() - 1) {
2487        const GLAPen& pen2 = GetPen(band + 1);
2488
2489        Double interval = MAX_ERROR / (GetNumDepthBands() - 1);
2490        Double into_band = E / interval - band;
2491
2492//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2493//             z_offset, interval, band);
2494        // FIXME: why do we need to clamp here?  Is it because the walls can
2495        // extend further up/down than the centre-line?
2496        if (into_band < 0.0) into_band = 0.0;
2497        if (into_band > 1.0) into_band = 1.0;
2498        assert(into_band >= 0.0);
2499        assert(into_band <= 1.0);
2500
2501        pen1.Interpolate(pen2, into_band);
2502    }
2503    SetColour(pen1, factor);
2504}
2505
2506void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
2507                                    const Vector3 &c, const Vector3 &d)
2508{
2509    Vector3 normal = (a - c) * (d - b);
2510    normal.normalise();
2511    Double factor = dot(normal, light) * .3 + .7;
2512    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2513    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2514    // FIXME: should plot triangles instead to avoid rendering glitches.
2515    BeginPolygon();
2516////    PlaceNormal(normal);
2517    SetColourFromError(static_E_hack, factor);
2518    // FIXME: these glTexCoord2i calls should be in gla-gl.cc
2519    glTexCoord2i(0, 0);
2520    PlaceVertex(a);
2521    glTexCoord2i(w, 0);
2522    PlaceVertex(b);
2523    glTexCoord2i(w, h);
2524    PlaceVertex(c);
2525    glTexCoord2i(0, h);
2526    PlaceVertex(d);
2527    EndPolygon();
2528}
2529
2530void GfxCore::AddPolylineError(const traverse & centreline)
2531{
2532    BeginPolyline();
2533    SetColourFromError(centreline.E, 1.0);
2534    vector<PointInfo>::const_iterator i;
2535    for(i = centreline.begin(); i != centreline.end(); ++i) {
2536        PlaceVertex(*i);
2537    }
2538    EndPolyline();
2539}
2540
2541void
2542GfxCore::SkinPassage(const vector<XSect> & centreline)
2543{
2544    assert(centreline.size() > 1);
2545    Vector3 U[4];
2546    XSect prev_pt_v;
2547    Vector3 last_right(1.0, 0.0, 0.0);
2548
2549//  FIXME: it's not simple to set the colour of a tube based on error...
2550//    static_E_hack = something...
2551    vector<XSect>::const_iterator i = centreline.begin();
2552    vector<XSect>::size_type segment = 0;
2553    while (i != centreline.end()) {
2554        // get the coordinates of this vertex
2555        const XSect & pt_v = *i++;
2556
2557        double z_pitch_adjust = 0.0;
2558        bool cover_end = false;
2559
2560        Vector3 right, up;
2561
2562        const Vector3 up_v(0.0, 0.0, 1.0);
2563
2564        if (segment == 0) {
2565            assert(i != centreline.end());
2566            // first segment
2567
2568            // get the coordinates of the next vertex
2569            const XSect & next_pt_v = *i;
2570
2571            // calculate vector from this pt to the next one
2572            Vector3 leg_v = next_pt_v - pt_v;
2573
2574            // obtain a vector in the LRUD plane
2575            right = leg_v * up_v;
2576            if (right.magnitude() == 0) {
2577                right = last_right;
2578                // Obtain a second vector in the LRUD plane,
2579                // perpendicular to the first.
2580                //up = right * leg_v;
2581                up = up_v;
2582            } else {
2583                last_right = right;
2584                up = up_v;
2585            }
2586
2587            cover_end = true;
2588            static_date_hack = next_pt_v.GetDate();
2589        } else if (segment + 1 == centreline.size()) {
2590            // last segment
2591
2592            // Calculate vector from the previous pt to this one.
2593            Vector3 leg_v = pt_v - prev_pt_v;
2594
2595            // Obtain a horizontal vector in the LRUD plane.
2596            right = leg_v * up_v;
2597            if (right.magnitude() == 0) {
2598                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
2599                // Obtain a second vector in the LRUD plane,
2600                // perpendicular to the first.
2601                //up = right * leg_v;
2602                up = up_v;
2603            } else {
2604                last_right = right;
2605                up = up_v;
2606            }
2607
2608            cover_end = true;
2609            static_date_hack = pt_v.GetDate();
2610        } else {
2611            assert(i != centreline.end());
2612            // Intermediate segment.
2613
2614            // Get the coordinates of the next vertex.
2615            const XSect & next_pt_v = *i;
2616
2617            // Calculate vectors from this vertex to the
2618            // next vertex, and from the previous vertex to
2619            // this one.
2620            Vector3 leg1_v = pt_v - prev_pt_v;
2621            Vector3 leg2_v = next_pt_v - pt_v;
2622
2623            // Obtain horizontal vectors perpendicular to
2624            // both legs, then normalise and average to get
2625            // a horizontal bisector.
2626            Vector3 r1 = leg1_v * up_v;
2627            Vector3 r2 = leg2_v * up_v;
2628            r1.normalise();
2629            r2.normalise();
2630            right = r1 + r2;
2631            if (right.magnitude() == 0) {
2632                // This is the "mid-pitch" case...
2633                right = last_right;
2634            }
2635            if (r1.magnitude() == 0) {
2636                Vector3 n = leg1_v;
2637                n.normalise();
2638                z_pitch_adjust = n.GetZ();
2639                //up = Vector3(0, 0, leg1_v.GetZ());
2640                //up = right * up;
2641                up = up_v;
2642
2643                // Rotate pitch section to minimise the
2644                // "tortional stress" - FIXME: use
2645                // triangles instead of rectangles?
2646                int shift = 0;
2647                Double maxdotp = 0;
2648
2649                // Scale to unit vectors in the LRUD plane.
2650                right.normalise();
2651                up.normalise();
2652                Vector3 vec = up - right;
2653                for (int orient = 0; orient <= 3; ++orient) {
2654                    Vector3 tmp = U[orient] - prev_pt_v;
2655                    tmp.normalise();
2656                    Double dotp = dot(vec, tmp);
2657                    if (dotp > maxdotp) {
2658                        maxdotp = dotp;
2659                        shift = orient;
2660                    }
2661                }
2662                if (shift) {
2663                    if (shift != 2) {
2664                        Vector3 temp(U[0]);
2665                        U[0] = U[shift];
2666                        U[shift] = U[2];
2667                        U[2] = U[shift ^ 2];
2668                        U[shift ^ 2] = temp;
2669                    } else {
2670                        swap(U[0], U[2]);
2671                        swap(U[1], U[3]);
2672                    }
2673                }
2674#if 0
2675                // Check that the above code actually permuted
2676                // the vertices correctly.
2677                shift = 0;
2678                maxdotp = 0;
2679                for (int j = 0; j <= 3; ++j) {
2680                    Vector3 tmp = U[j] - prev_pt_v;
2681                    tmp.normalise();
2682                    Double dotp = dot(vec, tmp);
2683                    if (dotp > maxdotp) {
2684                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
2685                        shift = j;
2686                    }
2687                }
2688                if (shift) {
2689                    printf("New shift = %d!\n", shift);
2690                    shift = 0;
2691                    maxdotp = 0;
2692                    for (int j = 0; j <= 3; ++j) {
2693                        Vector3 tmp = U[j] - prev_pt_v;
2694                        tmp.normalise();
2695                        Double dotp = dot(vec, tmp);
2696                        printf("    %d : %.8f\n", j, dotp);
2697                    }
2698                }
2699#endif
2700            } else if (r2.magnitude() == 0) {
2701                Vector3 n = leg2_v;
2702                n.normalise();
2703                z_pitch_adjust = n.GetZ();
2704                //up = Vector3(0, 0, leg2_v.GetZ());
2705                //up = right * up;
2706                up = up_v;
2707            } else {
2708                up = up_v;
2709            }
2710            last_right = right;
2711            static_date_hack = pt_v.GetDate();
2712        }
2713
2714        // Scale to unit vectors in the LRUD plane.
2715        right.normalise();
2716        up.normalise();
2717
2718        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
2719
2720        Double l = fabs(pt_v.GetL());
2721        Double r = fabs(pt_v.GetR());
2722        Double u = fabs(pt_v.GetU());
2723        Double d = fabs(pt_v.GetD());
2724
2725        // Produce coordinates of the corners of the LRUD "plane".
2726        Vector3 v[4];
2727        v[0] = pt_v - right * l + up * u;
2728        v[1] = pt_v + right * r + up * u;
2729        v[2] = pt_v + right * r - up * d;
2730        v[3] = pt_v - right * l - up * d;
2731
2732        if (segment > 0) {
2733            (this->*AddQuad)(v[0], v[1], U[1], U[0]);
2734            (this->*AddQuad)(v[2], v[3], U[3], U[2]);
2735            (this->*AddQuad)(v[1], v[2], U[2], U[1]);
2736            (this->*AddQuad)(v[3], v[0], U[0], U[3]);
2737        }
2738
2739        if (cover_end) {
2740            (this->*AddQuad)(v[3], v[2], v[1], v[0]);
2741        }
2742
2743        prev_pt_v = pt_v;
2744        U[0] = v[0];
2745        U[1] = v[1];
2746        U[2] = v[2];
2747        U[3] = v[3];
2748
2749        ++segment;
2750    }
2751}
2752
2753void GfxCore::FullScreenMode()
2754{
2755    m_Parent->ViewFullScreen();
2756}
2757
2758bool GfxCore::IsFullScreen() const
2759{
2760    return m_Parent->IsFullScreen();
2761}
2762
2763void
2764GfxCore::MoveViewer(double forward, double up, double right)
2765{
2766    double cT = cos(rad(m_TiltAngle));
2767    double sT = sin(rad(m_TiltAngle));
2768    double cP = cos(rad(m_PanAngle));
2769    double sP = sin(rad(m_PanAngle));
2770    Vector3 v_forward(cT * sP, cT * cP, -sT);
2771    Vector3 v_up(-sT * sP, -sT * cP, -cT);
2772    Vector3 v_right(-cP, sP, 0);
2773    assert(fabs(dot(v_forward, v_up)) < 1e-6);
2774    assert(fabs(dot(v_forward, v_right)) < 1e-6);
2775    assert(fabs(dot(v_right, v_up)) < 1e-6);
2776    Vector3 move = v_forward * forward + v_up * up + v_right * right;
2777    AddTranslation(-move);
2778    // Show current position.
2779    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
2780    ForceRefresh();
2781}
2782
2783PresentationMark GfxCore::GetView() const
2784{
2785    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
2786                            m_PanAngle, m_TiltAngle, m_Scale);
2787}
2788
2789void GfxCore::SetView(const PresentationMark & p)
2790{
2791    m_SwitchingTo = 0;
2792    SetTranslation(p - m_Parent->GetOffset());
2793    m_PanAngle = p.angle;
2794    m_TiltAngle = p.tilt_angle;
2795    SetRotation(m_PanAngle, m_TiltAngle);
2796    SetScale(p.scale);
2797    ForceRefresh();
2798}
2799
2800void GfxCore::PlayPres(double speed, bool change_speed) {
2801    if (!change_speed || presentation_mode == 0) {
2802        if (speed == 0.0) {
2803            presentation_mode = 0;
2804            return;
2805        }
2806        presentation_mode = PLAYING;
2807        next_mark = m_Parent->GetPresMark(MARK_FIRST);
2808        SetView(next_mark);
2809        next_mark_time = 0; // There already!
2810        this_mark_total = 0;
2811        pres_reverse = (speed < 0);
2812    }
2813
2814    if (change_speed) pres_speed = speed;
2815
2816    if (speed != 0.0) {
2817        bool new_pres_reverse = (speed < 0);
2818        if (new_pres_reverse != pres_reverse) {
2819            pres_reverse = new_pres_reverse;
2820            if (pres_reverse) {
2821                next_mark = m_Parent->GetPresMark(MARK_PREV);
2822            } else {
2823                next_mark = m_Parent->GetPresMark(MARK_NEXT);
2824            }
2825            swap(this_mark_total, next_mark_time);
2826        }
2827    }
2828}
2829
2830void GfxCore::SetColourBy(int colour_by) {
2831    m_ColourBy = colour_by;
2832    switch (colour_by) {
2833        case COLOUR_BY_DEPTH:
2834            AddQuad = &GfxCore::AddQuadrilateralDepth;
2835            AddPoly = &GfxCore::AddPolylineDepth;
2836            break;
2837        case COLOUR_BY_DATE:
2838            AddQuad = &GfxCore::AddQuadrilateralDate;
2839            AddPoly = &GfxCore::AddPolylineDate;
2840            break;
2841        case COLOUR_BY_ERROR:
2842            AddQuad = &GfxCore::AddQuadrilateralError;
2843            AddPoly = &GfxCore::AddPolylineError;
2844            break;
2845        default: // case COLOUR_BY_NONE:
2846            AddQuad = &GfxCore::AddQuadrilateral;
2847            AddPoly = &GfxCore::AddPolyline;
2848            break;
2849    }
2850
2851    InvalidateList(LIST_UNDERGROUND_LEGS);
2852    InvalidateList(LIST_SURFACE_LEGS);
2853    InvalidateList(LIST_TUBES);
2854
2855    ForceRefresh();
2856}
2857
2858bool GfxCore::ExportMovie(const wxString & fnm)
2859{
2860    int width;
2861    int height;
2862    GetSize(&width, &height);
2863    // Round up to next multiple of 2 (required by ffmpeg).
2864    width += (width & 1);
2865    height += (height & 1);
2866
2867    mpeg = new MovieMaker();
2868
2869    if (!mpeg->Open(fnm.fn_str(), width, height)) {
2870        // FIXME : sort out reporting actual errors from ffmpeg library
2871        wxGetApp().ReportError(wxString::Format(wmsg(/*Error writing to file `%s'*/110), fnm.c_str()));
2872        delete mpeg;
2873        mpeg = 0;
2874        return false;
2875    }
2876
2877    PlayPres(1, false);
2878    return true;
2879}
2880
2881void
2882GfxCore::OnPrint(const wxString &filename, const wxString &title,
2883                 const wxString &datestamp)
2884{
2885    svxPrintDlg * p;
2886    p = new svxPrintDlg(m_Parent, filename, title, datestamp,
2887                        m_PanAngle, m_TiltAngle,
2888                        m_Names, m_Crosses, m_Legs, m_Surface,
2889                        true);
2890    p->Show(TRUE);
2891}
2892
2893void
2894GfxCore::OnExport(const wxString &filename, const wxString &title)
2895{
2896    svxPrintDlg * p;
2897    p = new svxPrintDlg(m_Parent, filename, title, wxString(),
2898                        m_PanAngle, m_TiltAngle,
2899                        m_Names, m_Crosses, m_Legs, m_Surface,
2900                        false);
2901    p->Show(TRUE);
2902}
2903
2904static wxCursor
2905make_cursor(const unsigned char * bits, const unsigned char * mask,
2906            int hotx, int hoty)
2907{
2908#if defined __WXMSW__ || defined __WXMAC__
2909    wxBitmap cursor_bitmap(reinterpret_cast<const char *>(bits), 32, 32);
2910    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
2911    cursor_bitmap.SetMask(new wxMask(mask_bitmap));
2912    wxImage cursor_image = cursor_bitmap.ConvertToImage();
2913    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
2914    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
2915    return wxCursor(cursor_image);
2916#else
2917    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
2918                    (const char *)mask, wxWHITE, wxBLACK);
2919#endif
2920}
2921
2922const
2923#include "hand.xbm"
2924const
2925#include "handmask.xbm"
2926
2927const
2928#include "brotate.xbm"
2929const
2930#include "brotatemask.xbm"
2931
2932const
2933#include "vrotate.xbm"
2934const
2935#include "vrotatemask.xbm"
2936
2937const
2938#include "rotate.xbm"
2939const
2940#include "rotatemask.xbm"
2941
2942const
2943#include "rotatezoom.xbm"
2944const
2945#include "rotatezoommask.xbm"
2946
2947void
2948GfxCore::SetCursor(GfxCore::cursor new_cursor)
2949{
2950    // Check if we're already showing that cursor.
2951    if (current_cursor == new_cursor) return;
2952
2953    current_cursor = new_cursor;
2954    switch (current_cursor) {
2955        case GfxCore::CURSOR_DEFAULT:
2956            GLACanvas::SetCursor(wxNullCursor);
2957            break;
2958        case GfxCore::CURSOR_POINTING_HAND:
2959            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
2960            break;
2961        case GfxCore::CURSOR_DRAGGING_HAND:
2962            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
2963            break;
2964        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
2965            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
2966            break;
2967        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
2968            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
2969            break;
2970        case GfxCore::CURSOR_ROTATE_VERTICALLY:
2971            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
2972            break;
2973        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
2974            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
2975            break;
2976        case GfxCore::CURSOR_ZOOM:
2977            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
2978            break;
2979        case GfxCore::CURSOR_ZOOM_ROTATE:
2980            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
2981            break;
2982    }
2983}
Note: See TracBrowser for help on using the repository browser.