source: git/src/gfxcore.cc @ 2043961

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

src/gfxcore.cc,src/mainfrm.cc: Enable "colour by date" if there are
any surveys with date information. Move the "Undated" / "Not in
loop" entry down a little to improve the appearance. Make each
entry in the colour keys a pixel taller so it's an even number of
pixels and will divide by two exactly.

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

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