source: git/src/gfxcore.cc @ 6cfc88c

RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since 6cfc88c was 90430f2, checked in by Olly Betts <olly@…>, 14 years ago

src/: Push survey pane size tracking down into GLACanvas, and
automatically track which lists should be invalidated on a
changes in the width or the height of the pane.

git-svn-id: file:///home/survex-svn/survex/trunk@3786 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

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