source: git/src/gfxcore.cc @ 9c37beb

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

src/gfxcore.cc,src/gfxcore.h: Cache the scale bar in a GLAList since
it often gets redrawn exactly the same - for example, when rotating,
panning, etc.

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

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