source: git/src/gfxcore.cc @ 8a329f2

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

src/gfxcore.cc: Remove assertion which uses deprecated wx method.

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

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