source: git/src/gfxcore.cc @ 88707e0b

RELEASE/1.1RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-data
Last change on this file since 88707e0b was 88707e0b, checked in by Olly Betts <olly@…>, 14 years ago

Initialise all GfxCore?'s member variables so we don't use them uninitialised.

git-svn-id: file:///home/survex-svn/survex/branches/survex-1_1@3363 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

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