source: git/src/gfxcore.cc @ f481ceb

Last change on this file since f481ceb was f481ceb, checked in by Olly Betts <olly@…>, 11 years ago

Formatting fixes

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