source: git/src/gfxcore.cc @ 03e2031

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

src/aven.cc,src/gfxcore.cc: No point checking for NULL before calling
delete.

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

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