source: git/src/gfxcore.cc @ 6b061db

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

src/gfxcore.cc,src/gfxcore.h,src/mainfrm.cc: Don't redraw the survey
on every mouse movement in the survey pane unless the measuring line
is (or just was) active. (ticket #17)

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

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