source: git/src/gfxcore.cc @ 250025f

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

src/gfxcore.cc: Apply COLOUR_KEY_OFFSET_Y by moving the point where
we plot the key rather than including it in the calculations of the
key's coordinates.

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

  • Property mode set to 100644
File size: 80.4 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_OFFSET_Y = 16;
77static const int COLOUR_KEY_EXTRA_LEFT_MARGIN = 2;
78static const int COLOUR_KEY_BLOCK_WIDTH = 20;
79static const int COLOUR_KEY_BLOCK_HEIGHT = 16;
80static const int COLOUR_KEY_MARGIN = 6;
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 if (scale > 6144.0) {
278        scale = 6144.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_MARGIN);
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_BLOCK_WIDTH - COLOUR_KEY_MARGIN - size;
822
823    DrawRectangle(col_BLACK, col_DARK_GREY,
824                  left - COLOUR_KEY_MARGIN - COLOUR_KEY_EXTRA_LEFT_MARGIN,
825                  top - COLOUR_KEY_MARGIN * 2,
826                  COLOUR_KEY_BLOCK_WIDTH + size + COLOUR_KEY_MARGIN * 3 +
827                      COLOUR_KEY_EXTRA_LEFT_MARGIN,
828                  total_block_height + COLOUR_KEY_MARGIN*4);
829
830    int y = top;
831    for (band = 0; band < GetNumColourBands() - 1; ++band) {
832        DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
833                            COLOUR_KEY_BLOCK_WIDTH, COLOUR_KEY_BLOCK_HEIGHT);
834        y += COLOUR_KEY_BLOCK_HEIGHT;
835    }
836
837    y = top - GetFontSize() / 2;
838    left += COLOUR_KEY_BLOCK_WIDTH + 5;
839
840    SetColour(TEXT_COLOUR);
841    for (band = 0; band < GetNumColourBands(); ++band) {
842        DrawIndicatorText(left, y, strs[band]);
843        y += COLOUR_KEY_BLOCK_HEIGHT;
844    }
845
846    delete[] strs;
847}
848
849void GfxCore::DrawDatebar()
850{
851    int total_block_height;
852    int num_bands;
853    if (m_Parent->GetDateExtent() == 0) {
854        num_bands = 1;
855        total_block_height = COLOUR_KEY_BLOCK_HEIGHT;
856    } else {
857        num_bands = GetNumColourBands();
858        total_block_height = COLOUR_KEY_BLOCK_HEIGHT * (num_bands - 1);
859    }
860    if (!m_Parent->HasCompleteDateInfo())
861        total_block_height += COLOUR_KEY_BLOCK_HEIGHT * 2;
862    const int top = -(total_block_height + COLOUR_KEY_MARGIN);
863
864    int size = 0;
865    if (!m_Parent->HasCompleteDateInfo()) {
866        GetTextExtent(wmsg(/*Undated*/221), &size, NULL);
867    }
868
869    wxString* strs = new wxString[num_bands];
870    int band;
871    for (band = 0; band < num_bands; ++band) {
872        int y, m, d;
873        int days = m_Parent->GetDateMin();
874        if (band)
875            days += m_Parent->GetDateExtent() * band / (num_bands - 1);
876        ymd_from_days_since_1900(days, &y, &m, &d);
877        strs[band].Printf(wxT("%04d-%02d-%02d"), y, m, d);
878
879        int x;
880        GetTextExtent(strs[band], &x, NULL);
881        if (x > size) size = x;
882    }
883
884    int left = -COLOUR_KEY_BLOCK_WIDTH - COLOUR_KEY_MARGIN - size;
885
886    DrawRectangle(col_BLACK, col_DARK_GREY,
887                  left - COLOUR_KEY_MARGIN - COLOUR_KEY_EXTRA_LEFT_MARGIN,
888                  top - COLOUR_KEY_MARGIN * 2,
889                  COLOUR_KEY_BLOCK_WIDTH + size + COLOUR_KEY_MARGIN * 3 +
890                      COLOUR_KEY_EXTRA_LEFT_MARGIN,
891                  total_block_height + COLOUR_KEY_MARGIN*4);
892
893    int y = top;
894
895    if (!m_Parent->HasCompleteDateInfo()) {
896        DrawShadedRectangle(GetSurfacePen(), GetSurfacePen(), left, y,
897                            COLOUR_KEY_BLOCK_WIDTH, COLOUR_KEY_BLOCK_HEIGHT);
898        y += COLOUR_KEY_BLOCK_HEIGHT * 2;
899    }
900
901    if (num_bands == 1) {
902        DrawShadedRectangle(GetPen(0), GetPen(0), left, y,
903                            COLOUR_KEY_BLOCK_WIDTH, COLOUR_KEY_BLOCK_HEIGHT);
904    } else {
905        for (band = 0; band < num_bands - 1; ++band) {
906            DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
907                                COLOUR_KEY_BLOCK_WIDTH, COLOUR_KEY_BLOCK_HEIGHT);
908            y += COLOUR_KEY_BLOCK_HEIGHT;
909        }
910    }
911
912    y = top - GetFontSize() / 2;
913    left += COLOUR_KEY_BLOCK_WIDTH + 5;
914
915    SetColour(TEXT_COLOUR);
916
917    if (!m_Parent->HasCompleteDateInfo()) {
918        y += COLOUR_KEY_BLOCK_HEIGHT / 2;
919        DrawIndicatorText(left, y, wmsg(/*Undated*/221));
920        y += COLOUR_KEY_BLOCK_HEIGHT * 2 - COLOUR_KEY_BLOCK_HEIGHT / 2;
921    }
922
923    if (num_bands == 1) {
924        y += COLOUR_KEY_BLOCK_HEIGHT / 2;
925        DrawIndicatorText(left, y, strs[0]);
926    } else {
927        for (band = 0; band < num_bands; ++band) {
928            DrawIndicatorText(left, y, strs[band]);
929            y += COLOUR_KEY_BLOCK_HEIGHT;
930        }
931    }
932
933    delete[] strs;
934}
935
936void GfxCore::DrawErrorbar()
937{
938    int total_block_height = COLOUR_KEY_BLOCK_HEIGHT * (GetNumColourBands() - 1);
939    // Always show the "Not in loop" legend for now (FIXME).
940    total_block_height += COLOUR_KEY_BLOCK_HEIGHT * 2;
941    const int top = -(total_block_height + COLOUR_KEY_MARGIN);
942
943    int size = 0;
944    GetTextExtent(wmsg(/*Not in loop*/290), &size, NULL);
945
946    wxString* strs = new wxString[GetNumColourBands()];
947    int band;
948    for (band = 0; band < GetNumColourBands(); ++band) {
949        double E = MAX_ERROR * band / (GetNumColourBands() - 1);
950        strs[band].Printf(wxT("%.2f"), E);
951
952        int x;
953        GetTextExtent(strs[band], &x, NULL);
954        if (x > size) size = x;
955    }
956
957    int left = -COLOUR_KEY_BLOCK_WIDTH - COLOUR_KEY_MARGIN - size;
958
959    DrawRectangle(col_BLACK, col_DARK_GREY,
960                  left - COLOUR_KEY_MARGIN - COLOUR_KEY_EXTRA_LEFT_MARGIN,
961                  top - COLOUR_KEY_MARGIN * 2,
962                  COLOUR_KEY_BLOCK_WIDTH + size + COLOUR_KEY_MARGIN * 3 +
963                      COLOUR_KEY_EXTRA_LEFT_MARGIN,
964                  total_block_height + COLOUR_KEY_MARGIN*4);
965
966    int y = top;
967
968    DrawShadedRectangle(GetSurfacePen(), GetSurfacePen(), left, y,
969            COLOUR_KEY_BLOCK_WIDTH, COLOUR_KEY_BLOCK_HEIGHT);
970    y += COLOUR_KEY_BLOCK_HEIGHT * 2;
971
972    for (band = 0; band < GetNumColourBands() - 1; ++band) {
973        DrawShadedRectangle(GetPen(band), GetPen(band + 1), left, y,
974                            COLOUR_KEY_BLOCK_WIDTH, COLOUR_KEY_BLOCK_HEIGHT);
975        y += COLOUR_KEY_BLOCK_HEIGHT;
976    }
977
978    y = top - GetFontSize() / 2;
979    left += COLOUR_KEY_BLOCK_WIDTH + 5;
980
981    SetColour(TEXT_COLOUR);
982
983    y += COLOUR_KEY_BLOCK_HEIGHT / 2;
984    DrawIndicatorText(left, y, wmsg(/*Not in loop*/290));
985    y += COLOUR_KEY_BLOCK_HEIGHT * 2 - COLOUR_KEY_BLOCK_HEIGHT / 2;
986
987    for (band = 0; band < GetNumColourBands(); ++band) {
988        DrawIndicatorText(left, y, strs[band]);
989        y += COLOUR_KEY_BLOCK_HEIGHT;
990    }
991
992    delete[] strs;
993}
994
995wxString GfxCore::FormatLength(Double size_snap, bool scalebar)
996{
997    wxString str;
998    bool negative = (size_snap < 0.0);
999
1000    if (negative) {
1001        size_snap = -size_snap;
1002    }
1003
1004    if (size_snap == 0.0) {
1005        str = wxT("0");
1006    } else if (m_Metric) {
1007#ifdef SILLY_UNITS
1008        if (size_snap < 1e-12) {
1009            str.Printf(wxT("%.3gpm"), size_snap * 1e12);
1010        } else if (size_snap < 1e-9) {
1011            str.Printf(wxT("%.fpm"), size_snap * 1e12);
1012        } else if (size_snap < 1e-6) {
1013            str.Printf(wxT("%.fnm"), size_snap * 1e9);
1014        } else if (size_snap < 1e-3) {
1015            str.Printf(wxT("%.fum"), size_snap * 1e6);
1016#else
1017        if (size_snap < 1e-3) {
1018            str.Printf(wxT("%.3gmm"), size_snap * 1e3);
1019#endif
1020        } else if (size_snap < 1e-2) {
1021            str.Printf(wxT("%.fmm"), size_snap * 1e3);
1022        } else if (size_snap < 1.0) {
1023            str.Printf(wxT("%.fcm"), size_snap * 100.0);
1024        } else if (size_snap < 1e3) {
1025            str.Printf(wxT("%.fm"), size_snap);
1026#ifdef SILLY_UNITS
1027        } else if (size_snap < 1e6) {
1028            str.Printf(wxT("%.fkm"), size_snap * 1e-3);
1029        } else if (size_snap < 1e9) {
1030            str.Printf(wxT("%.fMm"), size_snap * 1e-6);
1031        } else {
1032            str.Printf(wxT("%.fGm"), size_snap * 1e-9);
1033#else
1034        } else {
1035            str.Printf(scalebar ? wxT("%.fkm") : wxT("%.2fkm"), size_snap * 1e-3);
1036#endif
1037        }
1038    } else {
1039        size_snap /= METRES_PER_FOOT;
1040        if (scalebar) {
1041            Double inches = size_snap * 12;
1042            if (inches < 1.0) {
1043                str.Printf(wxT("%.3gin"), inches);
1044            } else if (size_snap < 1.0) {
1045                str.Printf(wxT("%.fin"), inches);
1046            } else if (size_snap < 5279.5) {
1047                str.Printf(wxT("%.fft"), size_snap);
1048            } else {
1049                str.Printf(wxT("%.f miles"), size_snap / 5280.0);
1050            }
1051        } else {
1052            str.Printf(wxT("%.fft"), size_snap);
1053        }
1054    }
1055
1056    return negative ? wxString(wxT("-")) + str : str;
1057}
1058
1059void GfxCore::DrawScalebar()
1060{
1061    // Draw the scalebar.
1062    if (GetPerspective()) return;
1063
1064    // Calculate how many metres of survey are currently displayed across the
1065    // screen.
1066    Double across_screen = SurveyUnitsAcrossViewport();
1067
1068    double f = double(GetClinoXPosition() - INDICATOR_BOX_SIZE / 2 - SCALE_BAR_OFFSET_X) / m_XSize;
1069    if (f > 0.75) {
1070        f = 0.75;
1071    } else if (f < 0.5) {
1072        // Stop it getting squeezed to nothing.
1073        // FIXME: In this case we should probably move the compass and clino up
1074        // to make room rather than letting stuff overlap.
1075        f = 0.5;
1076    }
1077
1078    // Convert to imperial measurements if required.
1079    Double multiplier = 1.0;
1080    if (!m_Metric) {
1081        across_screen /= METRES_PER_FOOT;
1082        multiplier = METRES_PER_FOOT;
1083        if (across_screen >= 5280.0 / f) {
1084            across_screen /= 5280.0;
1085            multiplier *= 5280.0;
1086        }
1087    }
1088
1089    // Calculate the length of the scale bar.
1090    Double size_snap = pow(10.0, floor(log10(f * across_screen)));
1091    Double t = across_screen * f / size_snap;
1092    if (t >= 5.0) {
1093        size_snap *= 5.0;
1094    } else if (t >= 2.0) {
1095        size_snap *= 2.0;
1096    }
1097
1098    if (!m_Metric) size_snap *= multiplier;
1099
1100    // Actual size of the thing in pixels:
1101    int size = int((size_snap / SurveyUnitsAcrossViewport()) * m_XSize);
1102    m_ScaleBarWidth = size;
1103
1104    // Draw it...
1105    const int end_y = SCALE_BAR_OFFSET_Y + SCALE_BAR_HEIGHT;
1106    int interval = size / 10;
1107
1108    gla_colour col = col_WHITE;
1109    for (int ix = 0; ix < 10; ix++) {
1110        int x = SCALE_BAR_OFFSET_X + int(ix * ((Double) size / 10.0));
1111
1112        DrawRectangle(col, col, x, end_y, interval + 2, SCALE_BAR_HEIGHT);
1113
1114        col = (col == col_WHITE) ? col_GREY : col_WHITE;
1115    }
1116
1117    // Add labels.
1118    wxString str = FormatLength(size_snap);
1119
1120    int text_width, text_height;
1121    GetTextExtent(str, &text_width, &text_height);
1122    const int text_y = end_y - text_height + 1;
1123    SetColour(TEXT_COLOUR);
1124    DrawIndicatorText(SCALE_BAR_OFFSET_X, text_y, wxT("0"));
1125    DrawIndicatorText(SCALE_BAR_OFFSET_X + size - text_width, text_y, str);
1126}
1127
1128bool GfxCore::CheckHitTestGrid(const wxPoint& point, bool centre)
1129{
1130    if (Animating()) return false;
1131
1132    if (point.x < 0 || point.x >= m_XSize ||
1133        point.y < 0 || point.y >= m_YSize) {
1134        return false;
1135    }
1136
1137    SetDataTransform();
1138
1139    if (!m_HitTestGridValid) CreateHitTestGrid();
1140
1141    int grid_x = (point.x * (HITTEST_SIZE - 1)) / m_XSize;
1142    int grid_y = (point.y * (HITTEST_SIZE - 1)) / m_YSize;
1143
1144    LabelInfo *best = NULL;
1145    int dist_sqrd = 25;
1146    int square = grid_x + grid_y * HITTEST_SIZE;
1147    list<LabelInfo*>::iterator iter = m_PointGrid[square].begin();
1148
1149    while (iter != m_PointGrid[square].end()) {
1150        LabelInfo *pt = *iter++;
1151
1152        double cx, cy, cz;
1153
1154        Transform(*pt, &cx, &cy, &cz);
1155
1156        cy = m_YSize - cy;
1157
1158        int dx = point.x - int(cx);
1159        int ds = dx * dx;
1160        if (ds >= dist_sqrd) continue;
1161        int dy = point.y - int(cy);
1162
1163        ds += dy * dy;
1164        if (ds >= dist_sqrd) continue;
1165
1166        dist_sqrd = ds;
1167        best = pt;
1168
1169        if (ds == 0) break;
1170    }
1171
1172    if (best) {
1173        m_Parent->ShowInfo(best);
1174        if (centre) {
1175            // FIXME: allow Ctrl-Click to not set there or something?
1176            CentreOn(*best);
1177            WarpPointer(m_XSize / 2, m_YSize / 2);
1178            SetThere(*best);
1179            m_Parent->SelectTreeItem(best);
1180        }
1181    } else {
1182        // Left-clicking not on a survey cancels the measuring line.
1183        if (centre) {
1184            ClearTreeSelection();
1185        } else {
1186            m_Parent->ShowInfo(best);
1187            double x, y, z;
1188            ReverseTransform(point.x, m_YSize - point.y, &x, &y, &z);
1189            SetHere(Point(Vector3(x, y, z)));
1190            m_here_is_temporary = true;
1191        }
1192    }
1193
1194    return best;
1195}
1196
1197void GfxCore::OnSize(wxSizeEvent& event)
1198{
1199    // Handle a change in window size.
1200
1201    wxSize size = event.GetSize();
1202
1203    if (size.GetWidth() <= 0 || size.GetHeight() <= 0) {
1204        // Before things are fully initialised, we sometimes get a bogus
1205        // resize message...
1206        // FIXME have changes in MainFrm cured this?  It still happens with
1207        // 1.0.32 and wxGTK 2.5.2 (load a file from the command line).
1208        // With 1.1.6 and wxGTK 2.4.2 we only get negative sizes if MainFrm
1209        // is resized such that the GfxCore window isn't visible.
1210        //printf("OnSize(%d,%d)\n", size.GetWidth(), size.GetHeight());
1211        return;
1212    }
1213
1214    wxGLCanvas::OnSize(event);
1215
1216    m_XSize = size.GetWidth();
1217    m_YSize = size.GetHeight();
1218
1219    if (m_DoneFirstShow) {
1220        TryToFreeArrays();
1221
1222        m_HitTestGridValid = false;
1223
1224        ForceRefresh();
1225    }
1226}
1227
1228void GfxCore::DefaultParameters()
1229{
1230    // Set default viewing parameters.
1231
1232    m_Surface = false;
1233    if (!m_Parent->HasUndergroundLegs()) {
1234        if (m_Parent->HasSurfaceLegs()) {
1235            // If there are surface legs, but no underground legs, turn
1236            // surface surveys on.
1237            m_Surface = true;
1238        } else {
1239            // If there are no legs (e.g. after loading a .pos file), turn
1240            // crosses on.
1241            m_Crosses = true;
1242        }
1243    }
1244
1245    m_PanAngle = 0.0;
1246    if (m_Parent->IsExtendedElevation()) {
1247        m_TiltAngle = 0.0;
1248    } else {
1249        m_TiltAngle = 90.0;
1250    }
1251
1252    SetRotation(m_PanAngle, m_TiltAngle);
1253    SetTranslation(Vector3());
1254
1255    m_RotationStep = 30.0;
1256    m_Rotating = false;
1257    m_SwitchingTo = 0;
1258    m_Entrances = false;
1259    m_FixedPts = false;
1260    m_ExportedPts = false;
1261    m_Grid = false;
1262    m_BoundingBox = false;
1263    m_Tubes = false;
1264    if (GetPerspective()) TogglePerspective();
1265}
1266
1267void GfxCore::Defaults()
1268{
1269    // Restore default scale, rotation and translation parameters.
1270    DefaultParameters();
1271    SetScale(1.0);
1272
1273    // Invalidate all the cached lists.
1274    GLACanvas::FirstShow();
1275
1276    ForceRefresh();
1277}
1278
1279// return: true if animation occured (and ForceRefresh() needs to be called)
1280bool GfxCore::Animate()
1281{
1282    if (!Animating()) return false;
1283
1284    // Don't show pointer coordinates while animating.
1285    // FIXME : only do this when we *START* animating!  Use a static copy
1286    // of the value of "Animating()" last time we were here to track this?
1287    // MainFrm now checks if we're trying to clear already cleared labels
1288    // and just returns, but it might be simpler to check here!
1289    ClearCoords();
1290    m_Parent->ShowInfo(NULL);
1291
1292    static double last_t = 0;
1293    double t;
1294    if (movie) {
1295        ReadPixels(movie->GetWidth(), movie->GetHeight(), movie->GetBuffer());
1296        movie->AddFrame();
1297        t = 1.0 / 25.0; // 25 frames per second
1298    } else {
1299        t = timer.Time() * 1.0e-3;
1300        if (t == 0) t = 0.001;
1301        else if (t > 1.0) t = 1.0;
1302        if (last_t > 0) t = (t + last_t) / 2;
1303        last_t = t;
1304    }
1305
1306    if (presentation_mode == PLAYING && pres_speed != 0.0) {
1307        t *= fabs(pres_speed);
1308        while (t >= next_mark_time) {
1309            t -= next_mark_time;
1310            this_mark_total = 0;
1311            PresentationMark prev_mark = next_mark;
1312            if (prev_mark.angle < 0) prev_mark.angle += 360.0;
1313            else if (prev_mark.angle >= 360.0) prev_mark.angle -= 360.0;
1314            if (pres_reverse)
1315                next_mark = m_Parent->GetPresMark(MARK_PREV);
1316            else
1317                next_mark = m_Parent->GetPresMark(MARK_NEXT);
1318            if (!next_mark.is_valid()) {
1319                SetView(prev_mark);
1320                presentation_mode = 0;
1321                delete movie;
1322                movie = NULL;
1323                break;
1324            }
1325
1326            double tmp = (pres_reverse ? prev_mark.time : next_mark.time);
1327            if (tmp > 0) {
1328                next_mark_time = tmp;
1329            } else {
1330                double d = (next_mark - prev_mark).magnitude();
1331                // FIXME: should ignore component of d which is unseen in
1332                // non-perspective mode?
1333                next_mark_time = sqrd(d / 30.0);
1334                double a = next_mark.angle - prev_mark.angle;
1335                if (a > 180.0) {
1336                    next_mark.angle -= 360.0;
1337                    a = 360.0 - a;
1338                } else if (a < -180.0) {
1339                    next_mark.angle += 360.0;
1340                    a += 360.0;
1341                } else {
1342                    a = fabs(a);
1343                }
1344                next_mark_time += sqrd(a / 60.0);
1345                double ta = fabs(next_mark.tilt_angle - prev_mark.tilt_angle);
1346                next_mark_time += sqrd(ta / 60.0);
1347                double s = fabs(log(next_mark.scale) - log(prev_mark.scale));
1348                next_mark_time += sqrd(s / 2.0);
1349                next_mark_time = sqrt(next_mark_time);
1350                // was: next_mark_time = max(max(d / 30, s / 2), max(a, ta) / 60);
1351                //printf("*** %.6f from (\nd: %.6f\ns: %.6f\na: %.6f\nt: %.6f )\n",
1352                //       next_mark_time, d/30.0, s/2.0, a/60.0, ta/60.0);
1353                if (tmp < 0) next_mark_time /= -tmp;
1354            }
1355        }
1356
1357        if (presentation_mode) {
1358            // Advance position towards next_mark
1359            double p = t / next_mark_time;
1360            double q = 1 - p;
1361            PresentationMark here = GetView();
1362            if (next_mark.angle < 0) {
1363                if (here.angle >= next_mark.angle + 360.0)
1364                    here.angle -= 360.0;
1365            } else if (next_mark.angle >= 360.0) {
1366                if (here.angle <= next_mark.angle - 360.0)
1367                    here.angle += 360.0;
1368            }
1369            here.assign(q * here + p * next_mark);
1370            here.angle = q * here.angle + p * next_mark.angle;
1371            if (here.angle < 0) here.angle += 360.0;
1372            else if (here.angle >= 360.0) here.angle -= 360.0;
1373            here.tilt_angle = q * here.tilt_angle + p * next_mark.tilt_angle;
1374            here.scale = exp(q * log(here.scale) + p * log(next_mark.scale));
1375            SetView(here);
1376            this_mark_total += t;
1377            next_mark_time -= t;
1378        }
1379    }
1380
1381    // When rotating...
1382    if (m_Rotating) {
1383        TurnCave(m_RotationStep * t);
1384    }
1385
1386    if (m_SwitchingTo == PLAN) {
1387        // When switching to plan view...
1388        TiltCave(90.0 * t);
1389        if (m_TiltAngle == 90.0) {
1390            m_SwitchingTo = 0;
1391        }
1392    } else if (m_SwitchingTo == ELEVATION) {
1393        // When switching to elevation view...
1394        if (fabs(m_TiltAngle) < 90.0 * t) {
1395            m_SwitchingTo = 0;
1396            TiltCave(-m_TiltAngle);
1397        } else if (m_TiltAngle < 0.0) {
1398            TiltCave(90.0 * t);
1399        } else {
1400            TiltCave(-90.0 * t);
1401        }
1402    } else if (m_SwitchingTo) {
1403        int angle = (m_SwitchingTo - NORTH) * 90;
1404        double diff = angle - m_PanAngle;
1405        if (diff < -180) diff += 360;
1406        if (diff > 180) diff -= 360;
1407        double move = 90.0 * t;
1408        if (move >= fabs(diff)) {
1409            TurnCave(diff);
1410            m_SwitchingTo = 0;
1411        } else if (diff < 0) {
1412            TurnCave(-move);
1413        } else {
1414            TurnCave(move);
1415        }
1416    }
1417
1418    return true;
1419}
1420
1421// How much to allow around the box - this is because of the ring shape
1422// at one end of the line.
1423static const int HIGHLIGHTED_PT_SIZE = 2; // FIXME: tie in to blob and ring size
1424#define MARGIN (HIGHLIGHTED_PT_SIZE * 2 + 1)
1425void GfxCore::RefreshLine(const Point &a, const Point &b, const Point &c)
1426{
1427    // Best of all might be to copy the window contents before we draw the
1428    // line, then replace each time we redraw.
1429
1430    // Calculate the minimum rectangle which includes the old and new
1431    // measuring lines to minimise the redraw time
1432    int l = INT_MAX, r = INT_MIN, u = INT_MIN, d = INT_MAX;
1433    double X, Y, Z;
1434    if (a.IsValid()) {
1435        if (!Transform(a, &X, &Y, &Z)) {
1436            printf("oops\n");
1437        } else {
1438            int x = int(X);
1439            int y = m_YSize - 1 - int(Y);
1440            l = x - MARGIN;
1441            r = x + MARGIN;
1442            u = y + MARGIN;
1443            d = y - MARGIN;
1444        }
1445    }
1446    if (b.IsValid()) {
1447        if (!Transform(b, &X, &Y, &Z)) {
1448            printf("oops\n");
1449        } else {
1450            int x = int(X);
1451            int y = m_YSize - 1 - int(Y);
1452            l = min(l, x - MARGIN);
1453            r = max(r, x + MARGIN);
1454            u = max(u, y + MARGIN);
1455            d = min(d, y - MARGIN);
1456        }
1457    }
1458    if (c.IsValid()) {
1459        if (!Transform(c, &X, &Y, &Z)) {
1460            printf("oops\n");
1461        } else {
1462            int x = int(X);
1463            int y = m_YSize - 1 - int(Y);
1464            l = min(l, x - MARGIN);
1465            r = max(r, x + MARGIN);
1466            u = max(u, y + MARGIN);
1467            d = min(d, y - MARGIN);
1468        }
1469    }
1470    const wxRect R(l, d, r - l, u - d);
1471    Refresh(false, &R);
1472}
1473
1474void GfxCore::SetHere()
1475{
1476    if (!m_here.IsValid()) return;
1477    bool line_active = MeasuringLineActive();
1478    Point old = m_here;
1479    m_here.Invalidate();
1480    if (line_active || MeasuringLineActive())
1481        RefreshLine(old, m_there, m_here);
1482}
1483
1484void GfxCore::SetHere(const Point &p)
1485{
1486    bool line_active = MeasuringLineActive();
1487    Point old = m_here;
1488    m_here = p;
1489    if (line_active || MeasuringLineActive())
1490        RefreshLine(old, m_there, m_here);
1491    m_here_is_temporary = false;
1492}
1493
1494void GfxCore::SetThere()
1495{
1496    if (!m_there.IsValid()) return;
1497    Point old = m_there;
1498    m_there.Invalidate();
1499    RefreshLine(m_here, old, m_there);
1500}
1501
1502void GfxCore::SetThere(const Point &p)
1503{
1504    Point old = m_there;
1505    m_there = p;
1506    RefreshLine(m_here, old, m_there);
1507}
1508
1509void GfxCore::CreateHitTestGrid()
1510{
1511    // Clear hit-test grid.
1512    for (int i = 0; i < HITTEST_SIZE * HITTEST_SIZE; i++) {
1513        m_PointGrid[i].clear();
1514    }
1515
1516    // Fill the grid.
1517    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
1518    list<LabelInfo*>::const_iterator end = m_Parent->GetLabelsEnd();
1519    while (pos != end) {
1520        LabelInfo* label = *pos++;
1521
1522        if (!((m_Surface && label->IsSurface()) ||
1523              (m_Legs && label->IsUnderground()) ||
1524              (!label->IsSurface() && !label->IsUnderground()))) {
1525            // if this station isn't to be displayed, skip to the next
1526            // (last case is for stns with no legs attached)
1527            continue;
1528        }
1529
1530        // Calculate screen coordinates.
1531        double cx, cy, cz;
1532        Transform(*label, &cx, &cy, &cz);
1533        if (cx < 0 || cx >= m_XSize) continue;
1534        if (cy < 0 || cy >= m_YSize) continue;
1535
1536        cy = m_YSize - cy;
1537
1538        // On-screen, so add to hit-test grid...
1539        int grid_x = int((cx * (HITTEST_SIZE - 1)) / m_XSize);
1540        int grid_y = int((cy * (HITTEST_SIZE - 1)) / m_YSize);
1541
1542        m_PointGrid[grid_x + grid_y * HITTEST_SIZE].push_back(label);
1543    }
1544
1545    m_HitTestGridValid = true;
1546}
1547
1548//
1549//  Methods for controlling the orientation of the survey
1550//
1551
1552void GfxCore::TurnCave(Double angle)
1553{
1554    // Turn the cave around its z-axis by a given angle.
1555
1556    m_PanAngle += angle;
1557    if (m_PanAngle >= 360.0) {
1558        m_PanAngle -= 360.0;
1559    } else if (m_PanAngle < 0.0) {
1560        m_PanAngle += 360.0;
1561    }
1562
1563    m_HitTestGridValid = false;
1564    if (m_here_is_temporary) SetHere();
1565
1566    SetRotation(m_PanAngle, m_TiltAngle);
1567}
1568
1569void GfxCore::TurnCaveTo(Double angle)
1570{
1571    timer.Start(drawtime);
1572    int new_switching_to = ((int)angle) / 90 + NORTH;
1573    if (new_switching_to == m_SwitchingTo) {
1574        // A second order to switch takes us there right away
1575        TurnCave(angle - m_PanAngle);
1576        m_SwitchingTo = 0;
1577        ForceRefresh();
1578    } else {
1579        m_SwitchingTo = new_switching_to;
1580    }
1581}
1582
1583void GfxCore::TiltCave(Double tilt_angle)
1584{
1585    // Tilt the cave by a given angle.
1586    if (m_TiltAngle + tilt_angle > 90.0) {
1587        m_TiltAngle = 90.0;
1588    } else if (m_TiltAngle + tilt_angle < -90.0) {
1589        m_TiltAngle = -90.0;
1590    } else {
1591        m_TiltAngle += tilt_angle;
1592    }
1593
1594    m_HitTestGridValid = false;
1595    if (m_here_is_temporary) SetHere();
1596
1597    SetRotation(m_PanAngle, m_TiltAngle);
1598}
1599
1600void GfxCore::TranslateCave(int dx, int dy)
1601{
1602    AddTranslationScreenCoordinates(dx, dy);
1603    m_HitTestGridValid = false;
1604
1605    if (m_here_is_temporary) SetHere();
1606
1607    ForceRefresh();
1608}
1609
1610void GfxCore::DragFinished()
1611{
1612    m_MouseOutsideCompass = m_MouseOutsideElev = false;
1613    ForceRefresh();
1614}
1615
1616void GfxCore::ClearCoords()
1617{
1618    m_Parent->ClearCoords();
1619}
1620
1621void GfxCore::SetCoords(wxPoint point)
1622{
1623    // We can't work out 2D coordinates from a perspective view, and it
1624    // doesn't really make sense to show coordinates while we're animating.
1625    if (GetPerspective() || Animating()) return;
1626
1627    // Update the coordinate or altitude display, given the (x, y) position in
1628    // window coordinates.  The relevant display is updated depending on
1629    // whether we're in plan or elevation view.
1630
1631    double cx, cy, cz;
1632
1633    SetDataTransform();
1634    ReverseTransform(point.x, m_YSize - 1 - point.y, &cx, &cy, &cz);
1635
1636    if (ShowingPlan()) {
1637        m_Parent->SetCoords(cx + m_Parent->GetOffset().GetX(),
1638                            cy + m_Parent->GetOffset().GetY());
1639    } else if (ShowingElevation()) {
1640        m_Parent->SetAltitude(cz + m_Parent->GetOffset().GetZ());
1641    } else {
1642        m_Parent->ClearCoords();
1643    }
1644}
1645
1646int GfxCore::GetCompassXPosition() const
1647{
1648    // Return the x-coordinate of the centre of the compass in window
1649    // coordinates.
1650    return m_XSize - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE / 2;
1651}
1652
1653int GfxCore::GetClinoXPosition() const
1654{
1655    // Return the x-coordinate of the centre of the compass in window
1656    // coordinates.
1657    return m_XSize - GetClinoOffset() - INDICATOR_BOX_SIZE / 2;
1658}
1659
1660int GfxCore::GetIndicatorYPosition() const
1661{
1662    // Return the y-coordinate of the centre of the indicators in window
1663    // coordinates.
1664    return m_YSize - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE / 2;
1665}
1666
1667int GfxCore::GetIndicatorRadius() const
1668{
1669    // Return the radius of each indicator.
1670    return (INDICATOR_BOX_SIZE - INDICATOR_MARGIN * 2) / 2;
1671}
1672
1673bool GfxCore::PointWithinCompass(wxPoint point) const
1674{
1675    // Determine whether a point (in window coordinates) lies within the
1676    // compass.
1677    if (!ShowingCompass()) return false;
1678
1679    glaCoord dx = point.x - GetCompassXPosition();
1680    glaCoord dy = point.y - GetIndicatorYPosition();
1681    glaCoord radius = GetIndicatorRadius();
1682
1683    return (dx * dx + dy * dy <= radius * radius);
1684}
1685
1686bool GfxCore::PointWithinClino(wxPoint point) const
1687{
1688    // Determine whether a point (in window coordinates) lies within the clino.
1689    if (!ShowingClino()) return false;
1690
1691    glaCoord dx = point.x - GetClinoXPosition();
1692    glaCoord dy = point.y - GetIndicatorYPosition();
1693    glaCoord radius = GetIndicatorRadius();
1694
1695    return (dx * dx + dy * dy <= radius * radius);
1696}
1697
1698bool GfxCore::PointWithinScaleBar(wxPoint point) const
1699{
1700    // Determine whether a point (in window coordinates) lies within the scale
1701    // bar.
1702    if (!ShowingScaleBar()) return false;
1703
1704    return (point.x >= SCALE_BAR_OFFSET_X &&
1705            point.x <= SCALE_BAR_OFFSET_X + m_ScaleBarWidth &&
1706            point.y <= m_YSize - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT &&
1707            point.y >= m_YSize - SCALE_BAR_OFFSET_Y - SCALE_BAR_HEIGHT*2);
1708}
1709
1710void GfxCore::SetCompassFromPoint(wxPoint point)
1711{
1712    // Given a point in window coordinates, set the heading of the survey.  If
1713    // the point is outside the compass, it snaps to 45 degree intervals;
1714    // otherwise it operates as normal.
1715
1716    wxCoord dx = point.x - GetCompassXPosition();
1717    wxCoord dy = point.y - GetIndicatorYPosition();
1718    wxCoord radius = GetIndicatorRadius();
1719
1720    double angle = deg(atan2(double(dx), double(dy))) - 180.0;
1721    if (dx * dx + dy * dy <= radius * radius) {
1722        TurnCave(angle - m_PanAngle);
1723        m_MouseOutsideCompass = false;
1724    } else {
1725        TurnCave(int(angle / 45.0) * 45.0 - m_PanAngle);
1726        m_MouseOutsideCompass = true;
1727    }
1728
1729    ForceRefresh();
1730}
1731
1732void GfxCore::SetClinoFromPoint(wxPoint point)
1733{
1734    // Given a point in window coordinates, set the elevation of the survey.
1735    // If the point is outside the clino, it snaps to 90 degree intervals;
1736    // otherwise it operates as normal.
1737
1738    glaCoord dx = point.x - GetClinoXPosition();
1739    glaCoord dy = point.y - GetIndicatorYPosition();
1740    glaCoord radius = GetIndicatorRadius();
1741
1742    if (dx >= 0 && dx * dx + dy * dy <= radius * radius) {
1743        TiltCave(deg(atan2(double(dy), double(dx))) - m_TiltAngle);
1744        m_MouseOutsideElev = false;
1745    } else if (dy >= INDICATOR_MARGIN) {
1746        TiltCave(90.0 - m_TiltAngle);
1747        m_MouseOutsideElev = true;
1748    } else if (dy <= -INDICATOR_MARGIN) {
1749        TiltCave(-90.0 - m_TiltAngle);
1750        m_MouseOutsideElev = true;
1751    } else {
1752        TiltCave(-m_TiltAngle);
1753        m_MouseOutsideElev = true;
1754    }
1755
1756    ForceRefresh();
1757}
1758
1759void GfxCore::SetScaleBarFromOffset(wxCoord dx)
1760{
1761    // Set the scale of the survey, given an offset as to how much the mouse has
1762    // been dragged over the scalebar since the last scale change.
1763
1764    SetScale((m_ScaleBarWidth + dx) * m_Scale / m_ScaleBarWidth);
1765    ForceRefresh();
1766}
1767
1768void GfxCore::RedrawIndicators()
1769{
1770    // Redraw the compass and clino indicators.
1771
1772    const wxRect r(m_XSize - INDICATOR_OFFSET_X - INDICATOR_BOX_SIZE*2 -
1773                     INDICATOR_GAP,
1774                   m_YSize - INDICATOR_OFFSET_Y - INDICATOR_BOX_SIZE,
1775                   INDICATOR_BOX_SIZE*2 + INDICATOR_GAP,
1776                   INDICATOR_BOX_SIZE);
1777
1778    Refresh(false, &r);
1779}
1780
1781void GfxCore::StartRotation()
1782{
1783    // Start the survey rotating.
1784
1785    m_Rotating = true;
1786    timer.Start(drawtime);
1787}
1788
1789void GfxCore::ToggleRotation()
1790{
1791    // Toggle the survey rotation on/off.
1792
1793    if (m_Rotating) {
1794        StopRotation();
1795    } else {
1796        StartRotation();
1797    }
1798}
1799
1800void GfxCore::StopRotation()
1801{
1802    // Stop the survey rotating.
1803
1804    m_Rotating = false;
1805    ForceRefresh();
1806}
1807
1808bool GfxCore::IsExtendedElevation() const
1809{
1810    return m_Parent->IsExtendedElevation();
1811}
1812
1813void GfxCore::ReverseRotation()
1814{
1815    // Reverse the direction of rotation.
1816
1817    m_RotationStep = -m_RotationStep;
1818}
1819
1820void GfxCore::RotateSlower(bool accel)
1821{
1822    // Decrease the speed of rotation, optionally by an increased amount.
1823
1824    m_RotationStep /= accel ? 1.44 : 1.2;
1825    if (m_RotationStep < 1.0) {
1826        m_RotationStep = 1.0;
1827    }
1828}
1829
1830void GfxCore::RotateFaster(bool accel)
1831{
1832    // Increase the speed of rotation, optionally by an increased amount.
1833
1834    m_RotationStep *= accel ? 1.44 : 1.2;
1835    if (m_RotationStep > 450.0) {
1836        m_RotationStep = 450.0;
1837    }
1838}
1839
1840void GfxCore::SwitchToElevation()
1841{
1842    // Perform an animated switch to elevation view.
1843
1844    switch (m_SwitchingTo) {
1845        case 0:
1846            timer.Start(drawtime);
1847            m_SwitchingTo = ELEVATION;
1848            break;
1849
1850        case PLAN:
1851            m_SwitchingTo = ELEVATION;
1852            break;
1853
1854        case ELEVATION:
1855            // a second order to switch takes us there right away
1856            TiltCave(-m_TiltAngle);
1857            m_SwitchingTo = 0;
1858            ForceRefresh();
1859    }
1860}
1861
1862void GfxCore::SwitchToPlan()
1863{
1864    // Perform an animated switch to plan view.
1865
1866    switch (m_SwitchingTo) {
1867        case 0:
1868            timer.Start(drawtime);
1869            m_SwitchingTo = PLAN;
1870            break;
1871
1872        case ELEVATION:
1873            m_SwitchingTo = PLAN;
1874            break;
1875
1876        case PLAN:
1877            // A second order to switch takes us there right away
1878            TiltCave(90.0 - m_TiltAngle);
1879            m_SwitchingTo = 0;
1880            ForceRefresh();
1881    }
1882}
1883
1884void GfxCore::SetViewTo(Double xmin, Double xmax, Double ymin, Double ymax, Double zmin, Double zmax)
1885{
1886
1887    SetTranslation(-Vector3((xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2));
1888    Double scale = HUGE_VAL;
1889    const Vector3 ext = m_Parent->GetExtent();
1890    if (xmax > xmin) {
1891        Double s = ext.GetX() / (xmax - xmin);
1892        if (s < scale) scale = s;
1893    }
1894    if (ymax > ymin) {
1895        Double s = ext.GetY() / (ymax - ymin);
1896        if (s < scale) scale = s;
1897    }
1898    if (!ShowingPlan() && zmax > zmin) {
1899        Double s = ext.GetZ() / (zmax - zmin);
1900        if (s < scale) scale = s;
1901    }
1902    if (scale != HUGE_VAL) SetScale(scale);
1903    ForceRefresh();
1904}
1905
1906bool GfxCore::CanRaiseViewpoint() const
1907{
1908    // Determine if the survey can be viewed from a higher angle of elevation.
1909
1910    return GetPerspective() ? (m_TiltAngle > -90.0) : (m_TiltAngle < 90.0);
1911}
1912
1913bool GfxCore::CanLowerViewpoint() const
1914{
1915    // Determine if the survey can be viewed from a lower angle of elevation.
1916
1917    return GetPerspective() ? (m_TiltAngle < 90.0) : (m_TiltAngle > -90.0);
1918}
1919
1920bool GfxCore::HasDepth() const
1921{
1922    return m_Parent->GetDepthExtent() == 0.0;
1923}
1924
1925bool GfxCore::HasErrorInformation() const
1926{
1927    return m_Parent->HasErrorInformation();
1928}
1929
1930bool GfxCore::HasDateInformation() const
1931{
1932    return m_Parent->GetDateMin() >= 0;
1933}
1934
1935bool GfxCore::ShowingPlan() const
1936{
1937    // Determine if the survey is in plan view.
1938
1939    return (m_TiltAngle == 90.0);
1940}
1941
1942bool GfxCore::ShowingElevation() const
1943{
1944    // Determine if the survey is in elevation view.
1945
1946    return (m_TiltAngle == 0.0);
1947}
1948
1949bool GfxCore::ShowingMeasuringLine() const
1950{
1951    // Determine if the measuring line is being shown.
1952
1953    return (m_there.IsValid() && m_here.IsValid());
1954}
1955
1956void GfxCore::ToggleFlag(bool* flag, int update)
1957{
1958    *flag = !*flag;
1959    if (update == UPDATE_BLOBS) {
1960        UpdateBlobs();
1961    } else if (update == UPDATE_BLOBS_AND_CROSSES) {
1962        UpdateBlobs();
1963        InvalidateList(LIST_CROSSES);
1964    }
1965    ForceRefresh();
1966}
1967
1968int GfxCore::GetNumEntrances() const
1969{
1970    return m_Parent->GetNumEntrances();
1971}
1972
1973int GfxCore::GetNumFixedPts() const
1974{
1975    return m_Parent->GetNumFixedPts();
1976}
1977
1978int GfxCore::GetNumExportedPts() const
1979{
1980    return m_Parent->GetNumExportedPts();
1981}
1982
1983void GfxCore::ClearTreeSelection()
1984{
1985    m_Parent->ClearTreeSelection();
1986}
1987
1988void GfxCore::CentreOn(const Point &p)
1989{
1990    SetTranslation(-p);
1991    m_HitTestGridValid = false;
1992
1993    ForceRefresh();
1994}
1995
1996void GfxCore::ForceRefresh()
1997{
1998    Refresh(false);
1999}
2000
2001void GfxCore::GenerateList(unsigned int l)
2002{
2003    assert(m_HaveData);
2004
2005    switch (l) {
2006        case LIST_COMPASS:
2007            DrawCompass();
2008            break;
2009        case LIST_CLINO:
2010            DrawClino();
2011            break;
2012        case LIST_CLINO_BACK:
2013            DrawClinoBack();
2014            break;
2015        case LIST_DEPTHBAR:
2016            DrawDepthbar();
2017            break;
2018        case LIST_DATEBAR:
2019            DrawDatebar();
2020            break;
2021        case LIST_ERRORBAR:
2022            DrawErrorbar();
2023            break;
2024        case LIST_UNDERGROUND_LEGS:
2025            GenerateDisplayList();
2026            break;
2027        case LIST_TUBES:
2028            GenerateDisplayListTubes();
2029            break;
2030        case LIST_SURFACE_LEGS:
2031            GenerateDisplayListSurface();
2032            break;
2033        case LIST_BLOBS:
2034            GenerateBlobsDisplayList();
2035            break;
2036        case LIST_CROSSES: {
2037            BeginCrosses();
2038            SetColour(col_LIGHT_GREY);
2039            list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2040            while (pos != m_Parent->GetLabelsEnd()) {
2041                const LabelInfo* label = *pos++;
2042
2043                if ((m_Surface && label->IsSurface()) ||
2044                    (m_Legs && label->IsUnderground()) ||
2045                    (!label->IsSurface() && !label->IsUnderground())) {
2046                    // Check if this station should be displayed
2047                    // (last case is for stns with no legs attached)
2048                    DrawCross(label->GetX(), label->GetY(), label->GetZ());
2049                }
2050            }
2051            EndCrosses();
2052            break;
2053        }
2054        case LIST_GRID:
2055            DrawGrid();
2056            break;
2057        case LIST_SHADOW:
2058            GenerateDisplayListShadow();
2059            break;
2060        default:
2061            assert(false);
2062            break;
2063    }
2064}
2065
2066void GfxCore::ToggleSmoothShading()
2067{
2068    GLACanvas::ToggleSmoothShading();
2069    InvalidateList(LIST_TUBES);
2070    ForceRefresh();
2071}
2072
2073void GfxCore::GenerateDisplayList()
2074{
2075    // Generate the display list for the underground legs.
2076    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2077    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2078    while (trav != tend) {
2079        (this->*AddPoly)(*trav);
2080        ++trav;
2081    }
2082}
2083
2084void GfxCore::GenerateDisplayListTubes()
2085{
2086    // Generate the display list for the tubes.
2087    list<vector<XSect> >::const_iterator trav = m_Parent->tubes_begin();
2088    list<vector<XSect> >::const_iterator tend = m_Parent->tubes_end();
2089    while (trav != tend) {
2090        SkinPassage(*trav);
2091        ++trav;
2092    }
2093}
2094
2095void GfxCore::GenerateDisplayListSurface()
2096{
2097    // Generate the display list for the surface legs.
2098    EnableDashedLines();
2099    list<traverse>::const_iterator trav = m_Parent->surface_traverses_begin();
2100    list<traverse>::const_iterator tend = m_Parent->surface_traverses_end();
2101    while (trav != tend) {
2102        if (m_ColourBy == COLOUR_BY_ERROR) {
2103            AddPolylineError(*trav);
2104        } else {
2105            AddPolyline(*trav);
2106        }
2107        ++trav;
2108    }
2109    DisableDashedLines();
2110}
2111
2112void GfxCore::GenerateDisplayListShadow()
2113{
2114    SetColour(col_BLACK);
2115    list<traverse>::const_iterator trav = m_Parent->traverses_begin();
2116    list<traverse>::const_iterator tend = m_Parent->traverses_end();
2117    while (trav != tend) {
2118        AddPolylineShadow(*trav);
2119        ++trav;
2120    }
2121}
2122
2123// Plot blobs.
2124void GfxCore::GenerateBlobsDisplayList()
2125{
2126    if (!(m_Entrances || m_FixedPts || m_ExportedPts ||
2127          m_Parent->GetNumHighlightedPts()))
2128        return;
2129
2130    // Plot blobs.
2131    gla_colour prev_col = col_BLACK; // not a colour used for blobs
2132    list<LabelInfo*>::const_iterator pos = m_Parent->GetLabels();
2133    BeginBlobs();
2134    while (pos != m_Parent->GetLabelsEnd()) {
2135        const LabelInfo* label = *pos++;
2136
2137        // When more than one flag is set on a point:
2138        // search results take priority over entrance highlighting
2139        // which takes priority over fixed point
2140        // highlighting, which in turn takes priority over exported
2141        // point highlighting.
2142
2143        if (!((m_Surface && label->IsSurface()) ||
2144              (m_Legs && label->IsUnderground()) ||
2145              (!label->IsSurface() && !label->IsUnderground()))) {
2146            // if this station isn't to be displayed, skip to the next
2147            // (last case is for stns with no legs attached)
2148            continue;
2149        }
2150
2151        gla_colour col;
2152
2153        if (label->IsHighLighted()) {
2154            col = col_YELLOW;
2155        } else if (m_Entrances && label->IsEntrance()) {
2156            col = col_GREEN;
2157        } else if (m_FixedPts && label->IsFixedPt()) {
2158            col = col_RED;
2159        } else if (m_ExportedPts && label->IsExportedPt()) {
2160            col = col_TURQUOISE;
2161        } else {
2162            continue;
2163        }
2164
2165        // Stations are sorted by blob type, so colour changes are infrequent.
2166        if (col != prev_col) {
2167            SetColour(col);
2168            prev_col = col;
2169        }
2170        DrawBlob(label->GetX(), label->GetY(), label->GetZ());
2171    }
2172    EndBlobs();
2173}
2174
2175void GfxCore::DrawIndicators()
2176{
2177    // Draw colour key.
2178    if (m_ColourKey) {
2179        if (m_ColourBy == COLOUR_BY_DEPTH && m_Parent->GetDepthExtent() != 0.0) {
2180            DrawList2D(LIST_DEPTHBAR, m_XSize - COLOUR_KEY_OFFSET_X,
2181                       m_YSize - COLOUR_KEY_OFFSET_Y, 0);
2182        } else if (m_ColourBy == COLOUR_BY_DATE && HasDateInformation()) {
2183            DrawList2D(LIST_DATEBAR, m_XSize - COLOUR_KEY_OFFSET_X,
2184                       m_YSize - COLOUR_KEY_OFFSET_Y, 0);
2185        } else if (m_ColourBy == COLOUR_BY_ERROR && m_Parent->HasErrorInformation()) {
2186            DrawList2D(LIST_ERRORBAR, m_XSize - COLOUR_KEY_OFFSET_X,
2187                       m_YSize - COLOUR_KEY_OFFSET_Y, 0);
2188        }
2189    }
2190
2191    // Draw compass or elevation/heading indicators.
2192    if (m_Compass || m_Clino) {
2193        if (!m_Parent->IsExtendedElevation()) Draw2dIndicators();
2194    }
2195
2196    // Draw scalebar.
2197    if (m_Scalebar) {
2198        DrawScalebar();
2199    }
2200}
2201
2202void GfxCore::PlaceVertexWithColour(const Vector3 & v,
2203                                    glaTexCoord tex_x, glaTexCoord tex_y,
2204                                    Double factor)
2205{
2206    SetColour(GetSurfacePen(), factor); // FIXME : assumes surface pen is white!
2207    PlaceVertex(v, tex_x, tex_y);
2208}
2209
2210void GfxCore::SetDepthColour(Double z, Double factor) {
2211    // Set the drawing colour based on the altitude.
2212    Double z_ext = m_Parent->GetDepthExtent();
2213    assert(z_ext > 0);
2214
2215    z -= m_Parent->GetDepthMin();
2216    // points arising from tubes may be slightly outside the limits...
2217    if (z < 0) z = 0;
2218    if (z > z_ext) z = z_ext;
2219
2220    Double how_far = z / z_ext;
2221    assert(how_far >= 0.0);
2222    assert(how_far <= 1.0);
2223
2224    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2225    GLAPen pen1 = GetPen(band);
2226    if (band < GetNumColourBands() - 1) {
2227        const GLAPen& pen2 = GetPen(band + 1);
2228
2229        Double interval = z_ext / (GetNumColourBands() - 1);
2230        Double into_band = z / interval - band;
2231
2232//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2233//             z_offset, interval, band);
2234        // FIXME: why do we need to clamp here?  Is it because the walls can
2235        // extend further up/down than the centre-line?
2236        if (into_band < 0.0) into_band = 0.0;
2237        if (into_band > 1.0) into_band = 1.0;
2238        assert(into_band >= 0.0);
2239        assert(into_band <= 1.0);
2240
2241        pen1.Interpolate(pen2, into_band);
2242    }
2243    SetColour(pen1, factor);
2244}
2245
2246void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v, Double factor)
2247{
2248    SetDepthColour(v.GetZ(), factor);
2249    PlaceVertex(v);
2250}
2251
2252void GfxCore::PlaceVertexWithDepthColour(const Vector3 &v,
2253                                         glaTexCoord tex_x, glaTexCoord tex_y,
2254                                         Double factor)
2255{
2256    SetDepthColour(v.GetZ(), factor);
2257    PlaceVertex(v, tex_x, tex_y);
2258}
2259
2260void GfxCore::SplitLineAcrossBands(int band, int band2,
2261                                   const Vector3 &p, const Vector3 &q,
2262                                   Double factor)
2263{
2264    const int step = (band < band2) ? 1 : -1;
2265    for (int i = band; i != band2; i += step) {
2266        const Double z = GetDepthBoundaryBetweenBands(i, i + step);
2267
2268        // Find the intersection point of the line p -> q
2269        // with the plane parallel to the xy-plane with z-axis intersection z.
2270        assert(q.GetZ() - p.GetZ() != 0.0);
2271
2272        const Double t = (z - p.GetZ()) / (q.GetZ() - p.GetZ());
2273//      assert(0.0 <= t && t <= 1.0);           FIXME: rounding problems!
2274
2275        const Double x = p.GetX() + t * (q.GetX() - p.GetX());
2276        const Double y = p.GetY() + t * (q.GetY() - p.GetY());
2277
2278        PlaceVertexWithDepthColour(Vector3(x, y, z), factor);
2279    }
2280}
2281
2282int GfxCore::GetDepthColour(Double z) const
2283{
2284    // Return the (0-based) depth colour band index for a z-coordinate.
2285    Double z_ext = m_Parent->GetDepthExtent();
2286    assert(z_ext > 0);
2287    z -= m_Parent->GetDepthMin();
2288    z += z_ext / 2;
2289    return int(z / z_ext * (GetNumColourBands() - 1));
2290}
2291
2292Double GfxCore::GetDepthBoundaryBetweenBands(int a, int b) const
2293{
2294    // Return the z-coordinate of the depth colour boundary between
2295    // two adjacent depth colour bands (specified by 0-based indices).
2296
2297    assert((a == b - 1) || (a == b + 1));
2298    if (GetNumColourBands() == 1) return 0;
2299
2300    int band = (a > b) ? a : b; // boundary N lies on the bottom of band N.
2301    Double z_ext = m_Parent->GetDepthExtent();
2302    return (z_ext * band / (GetNumColourBands() - 1)) - z_ext / 2
2303        + m_Parent->GetDepthMin();
2304}
2305
2306void GfxCore::AddPolyline(const traverse & centreline)
2307{
2308    BeginPolyline();
2309    SetColour(GetSurfacePen());
2310    vector<PointInfo>::const_iterator i = centreline.begin();
2311    PlaceVertex(*i);
2312    ++i;
2313    while (i != centreline.end()) {
2314        PlaceVertex(*i);
2315        ++i;
2316    }
2317    EndPolyline();
2318}
2319
2320void GfxCore::AddPolylineShadow(const traverse & centreline)
2321{
2322    BeginPolyline();
2323    const double z = -0.5 * m_Parent->GetZExtent();
2324    vector<PointInfo>::const_iterator i = centreline.begin();
2325    PlaceVertex(i->GetX(), i->GetY(), z);
2326    ++i;
2327    while (i != centreline.end()) {
2328        PlaceVertex(i->GetX(), i->GetY(), z);
2329        ++i;
2330    }
2331    EndPolyline();
2332}
2333
2334void GfxCore::AddPolylineDepth(const traverse & centreline)
2335{
2336    BeginPolyline();
2337    vector<PointInfo>::const_iterator i, prev_i;
2338    i = centreline.begin();
2339    int band0 = GetDepthColour(i->GetZ());
2340    PlaceVertexWithDepthColour(*i);
2341    prev_i = i;
2342    ++i;
2343    while (i != centreline.end()) {
2344        int band = GetDepthColour(i->GetZ());
2345        if (band != band0) {
2346            SplitLineAcrossBands(band0, band, *prev_i, *i);
2347            band0 = band;
2348        }
2349        PlaceVertexWithDepthColour(*i);
2350        prev_i = i;
2351        ++i;
2352    }
2353    EndPolyline();
2354}
2355
2356void GfxCore::AddQuadrilateral(const Vector3 &a, const Vector3 &b,
2357                               const Vector3 &c, const Vector3 &d)
2358{
2359    Vector3 normal = (a - c) * (d - b);
2360    normal.normalise();
2361    Double factor = dot(normal, light) * .3 + .7;
2362    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2363    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
2364    // FIXME: should plot triangles instead to avoid rendering glitches.
2365    BeginQuadrilaterals();
2366    PlaceVertexWithColour(a, 0, 0, factor);
2367    PlaceVertexWithColour(b, w, 0, factor);
2368    PlaceVertexWithColour(c, w, h, factor);
2369    PlaceVertexWithColour(d, 0, h, factor);
2370    EndQuadrilaterals();
2371}
2372
2373void GfxCore::AddQuadrilateralDepth(const Vector3 &a, const Vector3 &b,
2374                                    const Vector3 &c, const Vector3 &d)
2375{
2376    Vector3 normal = (a - c) * (d - b);
2377    normal.normalise();
2378    Double factor = dot(normal, light) * .3 + .7;
2379    int a_band, b_band, c_band, d_band;
2380    a_band = GetDepthColour(a.GetZ());
2381    a_band = min(max(a_band, 0), GetNumColourBands());
2382    b_band = GetDepthColour(b.GetZ());
2383    b_band = min(max(b_band, 0), GetNumColourBands());
2384    c_band = GetDepthColour(c.GetZ());
2385    c_band = min(max(c_band, 0), GetNumColourBands());
2386    d_band = GetDepthColour(d.GetZ());
2387    d_band = min(max(d_band, 0), GetNumColourBands());
2388    // All this splitting is incorrect - we need to make a separate polygon
2389    // for each depth band...
2390    glaTexCoord w(ceil(((b - a).magnitude() + (d - c).magnitude()) * .5));
2391    glaTexCoord h(ceil(((b - c).magnitude() + (d - a).magnitude()) * .5));
2392    BeginPolygon();
2393////    PlaceNormal(normal);
2394    PlaceVertexWithDepthColour(a, 0, 0, factor);
2395    if (a_band != b_band) {
2396        SplitLineAcrossBands(a_band, b_band, a, b, factor);
2397    }
2398    PlaceVertexWithDepthColour(b, w, 0, factor);
2399    if (b_band != c_band) {
2400        SplitLineAcrossBands(b_band, c_band, b, c, factor);
2401    }
2402    PlaceVertexWithDepthColour(c, w, h, factor);
2403    if (c_band != d_band) {
2404        SplitLineAcrossBands(c_band, d_band, c, d, factor);
2405    }
2406    PlaceVertexWithDepthColour(d, 0, h, factor);
2407    if (d_band != a_band) {
2408        SplitLineAcrossBands(d_band, a_band, d, a, factor);
2409    }
2410    EndPolygon();
2411}
2412
2413void GfxCore::SetColourFromDate(int date, Double factor)
2414{
2415    // Set the drawing colour based on a date.
2416
2417    if (date == -1) {
2418        // Undated.
2419        SetColour(GetSurfacePen(), factor);
2420        return;
2421    }
2422
2423    int date_offset = date - m_Parent->GetDateMin();
2424    if (date_offset == 0) {
2425        // Earliest date - handle as a special case for the single date case.
2426        SetColour(GetPen(0), factor);
2427        return;
2428    }
2429
2430    int date_ext = m_Parent->GetDateExtent();
2431    Double how_far = (Double)date_offset / date_ext;
2432    assert(how_far >= 0.0);
2433    assert(how_far <= 1.0);
2434
2435    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2436    GLAPen pen1 = GetPen(band);
2437    if (band < GetNumColourBands() - 1) {
2438        const GLAPen& pen2 = GetPen(band + 1);
2439
2440        Double interval = date_ext / (GetNumColourBands() - 1);
2441        Double into_band = date_offset / interval - band;
2442
2443//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2444//             z_offset, interval, band);
2445        // FIXME: why do we need to clamp here?  Is it because the walls can
2446        // extend further up/down than the centre-line?
2447        if (into_band < 0.0) into_band = 0.0;
2448        if (into_band > 1.0) into_band = 1.0;
2449        assert(into_band >= 0.0);
2450        assert(into_band <= 1.0);
2451
2452        pen1.Interpolate(pen2, into_band);
2453    }
2454    SetColour(pen1, factor);
2455}
2456
2457void GfxCore::AddPolylineDate(const traverse & centreline)
2458{
2459    BeginPolyline();
2460    vector<PointInfo>::const_iterator i, prev_i;
2461    i = centreline.begin();
2462    int date = i->GetDate();
2463    SetColourFromDate(date, 1.0);
2464    PlaceVertex(*i);
2465    prev_i = i;
2466    while (++i != centreline.end()) {
2467        int newdate = i->GetDate();
2468        if (newdate != date) {
2469            EndPolyline();
2470            BeginPolyline();
2471            date = newdate;
2472            SetColourFromDate(date, 1.0);
2473            PlaceVertex(*prev_i);
2474        }
2475        PlaceVertex(*i);
2476        prev_i = i;
2477    }
2478    EndPolyline();
2479}
2480
2481static int static_date_hack; // FIXME
2482
2483void GfxCore::AddQuadrilateralDate(const Vector3 &a, const Vector3 &b,
2484                                   const Vector3 &c, const Vector3 &d)
2485{
2486    Vector3 normal = (a - c) * (d - b);
2487    normal.normalise();
2488    Double factor = dot(normal, light) * .3 + .7;
2489    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2490    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2491    // FIXME: should plot triangles instead to avoid rendering glitches.
2492    BeginQuadrilaterals();
2493////    PlaceNormal(normal);
2494    SetColourFromDate(static_date_hack, factor);
2495    PlaceVertex(a, 0, 0);
2496    PlaceVertex(b, w, 0);
2497    PlaceVertex(c, w, h);
2498    PlaceVertex(d, 0, h);
2499    EndQuadrilaterals();
2500}
2501
2502static double static_E_hack; // FIXME
2503
2504void GfxCore::SetColourFromError(double E, Double factor)
2505{
2506    // Set the drawing colour based on an error value.
2507
2508    if (E < 0) {
2509        SetColour(GetSurfacePen(), factor);
2510        return;
2511    }
2512
2513    Double how_far = E / MAX_ERROR;
2514    assert(how_far >= 0.0);
2515    if (how_far > 1.0) how_far = 1.0;
2516
2517    int band = int(floor(how_far * (GetNumColourBands() - 1)));
2518    GLAPen pen1 = GetPen(band);
2519    if (band < GetNumColourBands() - 1) {
2520        const GLAPen& pen2 = GetPen(band + 1);
2521
2522        Double interval = MAX_ERROR / (GetNumColourBands() - 1);
2523        Double into_band = E / interval - band;
2524
2525//      printf("%g z_offset=%g interval=%g band=%d\n", into_band,
2526//             z_offset, interval, band);
2527        // FIXME: why do we need to clamp here?  Is it because the walls can
2528        // extend further up/down than the centre-line?
2529        if (into_band < 0.0) into_band = 0.0;
2530        if (into_band > 1.0) into_band = 1.0;
2531        assert(into_band >= 0.0);
2532        assert(into_band <= 1.0);
2533
2534        pen1.Interpolate(pen2, into_band);
2535    }
2536    SetColour(pen1, factor);
2537}
2538
2539void GfxCore::AddQuadrilateralError(const Vector3 &a, const Vector3 &b,
2540                                    const Vector3 &c, const Vector3 &d)
2541{
2542    Vector3 normal = (a - c) * (d - b);
2543    normal.normalise();
2544    Double factor = dot(normal, light) * .3 + .7;
2545    int w = int(ceil(((b - a).magnitude() + (d - c).magnitude()) / 2));
2546    int h = int(ceil(((b - c).magnitude() + (d - a).magnitude()) / 2));
2547    // FIXME: should plot triangles instead to avoid rendering glitches.
2548    BeginQuadrilaterals();
2549////    PlaceNormal(normal);
2550    SetColourFromError(static_E_hack, factor);
2551    PlaceVertex(a, 0, 0);
2552    PlaceVertex(b, w, 0);
2553    PlaceVertex(c, w, h);
2554    PlaceVertex(d, 0, h);
2555    EndQuadrilaterals();
2556}
2557
2558void GfxCore::AddPolylineError(const traverse & centreline)
2559{
2560    BeginPolyline();
2561    SetColourFromError(centreline.E, 1.0);
2562    vector<PointInfo>::const_iterator i;
2563    for(i = centreline.begin(); i != centreline.end(); ++i) {
2564        PlaceVertex(*i);
2565    }
2566    EndPolyline();
2567}
2568
2569void
2570GfxCore::SkinPassage(const vector<XSect> & centreline)
2571{
2572    assert(centreline.size() > 1);
2573    Vector3 U[4];
2574    XSect prev_pt_v;
2575    Vector3 last_right(1.0, 0.0, 0.0);
2576
2577//  FIXME: it's not simple to set the colour of a tube based on error...
2578//    static_E_hack = something...
2579    vector<XSect>::const_iterator i = centreline.begin();
2580    vector<XSect>::size_type segment = 0;
2581    while (i != centreline.end()) {
2582        // get the coordinates of this vertex
2583        const XSect & pt_v = *i++;
2584
2585        double z_pitch_adjust = 0.0;
2586        bool cover_end = false;
2587
2588        Vector3 right, up;
2589
2590        const Vector3 up_v(0.0, 0.0, 1.0);
2591
2592        if (segment == 0) {
2593            assert(i != centreline.end());
2594            // first segment
2595
2596            // get the coordinates of the next vertex
2597            const XSect & next_pt_v = *i;
2598
2599            // calculate vector from this pt to the next one
2600            Vector3 leg_v = next_pt_v - pt_v;
2601
2602            // obtain a vector in the LRUD plane
2603            right = leg_v * up_v;
2604            if (right.magnitude() == 0) {
2605                right = last_right;
2606                // Obtain a second vector in the LRUD plane,
2607                // perpendicular to the first.
2608                //up = right * leg_v;
2609                up = up_v;
2610            } else {
2611                last_right = right;
2612                up = up_v;
2613            }
2614
2615            cover_end = true;
2616            static_date_hack = next_pt_v.GetDate();
2617        } else if (segment + 1 == centreline.size()) {
2618            // last segment
2619
2620            // Calculate vector from the previous pt to this one.
2621            Vector3 leg_v = pt_v - prev_pt_v;
2622
2623            // Obtain a horizontal vector in the LRUD plane.
2624            right = leg_v * up_v;
2625            if (right.magnitude() == 0) {
2626                right = Vector3(last_right.GetX(), last_right.GetY(), 0.0);
2627                // Obtain a second vector in the LRUD plane,
2628                // perpendicular to the first.
2629                //up = right * leg_v;
2630                up = up_v;
2631            } else {
2632                last_right = right;
2633                up = up_v;
2634            }
2635
2636            cover_end = true;
2637            static_date_hack = pt_v.GetDate();
2638        } else {
2639            assert(i != centreline.end());
2640            // Intermediate segment.
2641
2642            // Get the coordinates of the next vertex.
2643            const XSect & next_pt_v = *i;
2644
2645            // Calculate vectors from this vertex to the
2646            // next vertex, and from the previous vertex to
2647            // this one.
2648            Vector3 leg1_v = pt_v - prev_pt_v;
2649            Vector3 leg2_v = next_pt_v - pt_v;
2650
2651            // Obtain horizontal vectors perpendicular to
2652            // both legs, then normalise and average to get
2653            // a horizontal bisector.
2654            Vector3 r1 = leg1_v * up_v;
2655            Vector3 r2 = leg2_v * up_v;
2656            r1.normalise();
2657            r2.normalise();
2658            right = r1 + r2;
2659            if (right.magnitude() == 0) {
2660                // This is the "mid-pitch" case...
2661                right = last_right;
2662            }
2663            if (r1.magnitude() == 0) {
2664                Vector3 n = leg1_v;
2665                n.normalise();
2666                z_pitch_adjust = n.GetZ();
2667                //up = Vector3(0, 0, leg1_v.GetZ());
2668                //up = right * up;
2669                up = up_v;
2670
2671                // Rotate pitch section to minimise the
2672                // "tortional stress" - FIXME: use
2673                // triangles instead of rectangles?
2674                int shift = 0;
2675                Double maxdotp = 0;
2676
2677                // Scale to unit vectors in the LRUD plane.
2678                right.normalise();
2679                up.normalise();
2680                Vector3 vec = up - right;
2681                for (int orient = 0; orient <= 3; ++orient) {
2682                    Vector3 tmp = U[orient] - prev_pt_v;
2683                    tmp.normalise();
2684                    Double dotp = dot(vec, tmp);
2685                    if (dotp > maxdotp) {
2686                        maxdotp = dotp;
2687                        shift = orient;
2688                    }
2689                }
2690                if (shift) {
2691                    if (shift != 2) {
2692                        Vector3 temp(U[0]);
2693                        U[0] = U[shift];
2694                        U[shift] = U[2];
2695                        U[2] = U[shift ^ 2];
2696                        U[shift ^ 2] = temp;
2697                    } else {
2698                        swap(U[0], U[2]);
2699                        swap(U[1], U[3]);
2700                    }
2701                }
2702#if 0
2703                // Check that the above code actually permuted
2704                // the vertices correctly.
2705                shift = 0;
2706                maxdotp = 0;
2707                for (int j = 0; j <= 3; ++j) {
2708                    Vector3 tmp = U[j] - prev_pt_v;
2709                    tmp.normalise();
2710                    Double dotp = dot(vec, tmp);
2711                    if (dotp > maxdotp) {
2712                        maxdotp = dotp + 1e-6; // Add small tolerance to stop 45 degree offset cases being flagged...
2713                        shift = j;
2714                    }
2715                }
2716                if (shift) {
2717                    printf("New shift = %d!\n", shift);
2718                    shift = 0;
2719                    maxdotp = 0;
2720                    for (int j = 0; j <= 3; ++j) {
2721                        Vector3 tmp = U[j] - prev_pt_v;
2722                        tmp.normalise();
2723                        Double dotp = dot(vec, tmp);
2724                        printf("    %d : %.8f\n", j, dotp);
2725                    }
2726                }
2727#endif
2728            } else if (r2.magnitude() == 0) {
2729                Vector3 n = leg2_v;
2730                n.normalise();
2731                z_pitch_adjust = n.GetZ();
2732                //up = Vector3(0, 0, leg2_v.GetZ());
2733                //up = right * up;
2734                up = up_v;
2735            } else {
2736                up = up_v;
2737            }
2738            last_right = right;
2739            static_date_hack = pt_v.GetDate();
2740        }
2741
2742        // Scale to unit vectors in the LRUD plane.
2743        right.normalise();
2744        up.normalise();
2745
2746        if (z_pitch_adjust != 0) up += Vector3(0, 0, fabs(z_pitch_adjust));
2747
2748        Double l = fabs(pt_v.GetL());
2749        Double r = fabs(pt_v.GetR());
2750        Double u = fabs(pt_v.GetU());
2751        Double d = fabs(pt_v.GetD());
2752
2753        // Produce coordinates of the corners of the LRUD "plane".
2754        Vector3 v[4];
2755        v[0] = pt_v - right * l + up * u;
2756        v[1] = pt_v + right * r + up * u;
2757        v[2] = pt_v + right * r - up * d;
2758        v[3] = pt_v - right * l - up * d;
2759
2760        if (segment > 0) {
2761            (this->*AddQuad)(v[0], v[1], U[1], U[0]);
2762            (this->*AddQuad)(v[2], v[3], U[3], U[2]);
2763            (this->*AddQuad)(v[1], v[2], U[2], U[1]);
2764            (this->*AddQuad)(v[3], v[0], U[0], U[3]);
2765        }
2766
2767        if (cover_end) {
2768            (this->*AddQuad)(v[3], v[2], v[1], v[0]);
2769        }
2770
2771        prev_pt_v = pt_v;
2772        U[0] = v[0];
2773        U[1] = v[1];
2774        U[2] = v[2];
2775        U[3] = v[3];
2776
2777        ++segment;
2778    }
2779}
2780
2781void GfxCore::FullScreenMode()
2782{
2783    m_Parent->ViewFullScreen();
2784}
2785
2786bool GfxCore::IsFullScreen() const
2787{
2788    return m_Parent->IsFullScreen();
2789}
2790
2791void
2792GfxCore::MoveViewer(double forward, double up, double right)
2793{
2794    double cT = cos(rad(m_TiltAngle));
2795    double sT = sin(rad(m_TiltAngle));
2796    double cP = cos(rad(m_PanAngle));
2797    double sP = sin(rad(m_PanAngle));
2798    Vector3 v_forward(cT * sP, cT * cP, -sT);
2799    Vector3 v_up(-sT * sP, -sT * cP, -cT);
2800    Vector3 v_right(-cP, sP, 0);
2801    assert(fabs(dot(v_forward, v_up)) < 1e-6);
2802    assert(fabs(dot(v_forward, v_right)) < 1e-6);
2803    assert(fabs(dot(v_right, v_up)) < 1e-6);
2804    Vector3 move = v_forward * forward + v_up * up + v_right * right;
2805    AddTranslation(-move);
2806    // Show current position.
2807    m_Parent->SetCoords(m_Parent->GetOffset() - GetTranslation());
2808    ForceRefresh();
2809}
2810
2811PresentationMark GfxCore::GetView() const
2812{
2813    return PresentationMark(GetTranslation() + m_Parent->GetOffset(),
2814                            m_PanAngle, m_TiltAngle, m_Scale);
2815}
2816
2817void GfxCore::SetView(const PresentationMark & p)
2818{
2819    m_SwitchingTo = 0;
2820    SetTranslation(p - m_Parent->GetOffset());
2821    m_PanAngle = p.angle;
2822    m_TiltAngle = p.tilt_angle;
2823    SetRotation(m_PanAngle, m_TiltAngle);
2824    SetScale(p.scale);
2825    ForceRefresh();
2826}
2827
2828void GfxCore::PlayPres(double speed, bool change_speed) {
2829    if (!change_speed || presentation_mode == 0) {
2830        if (speed == 0.0) {
2831            presentation_mode = 0;
2832            return;
2833        }
2834        presentation_mode = PLAYING;
2835        next_mark = m_Parent->GetPresMark(MARK_FIRST);
2836        SetView(next_mark);
2837        next_mark_time = 0; // There already!
2838        this_mark_total = 0;
2839        pres_reverse = (speed < 0);
2840    }
2841
2842    if (change_speed) pres_speed = speed;
2843
2844    if (speed != 0.0) {
2845        bool new_pres_reverse = (speed < 0);
2846        if (new_pres_reverse != pres_reverse) {
2847            pres_reverse = new_pres_reverse;
2848            if (pres_reverse) {
2849                next_mark = m_Parent->GetPresMark(MARK_PREV);
2850            } else {
2851                next_mark = m_Parent->GetPresMark(MARK_NEXT);
2852            }
2853            swap(this_mark_total, next_mark_time);
2854        }
2855    }
2856}
2857
2858void GfxCore::SetColourBy(int colour_by) {
2859    m_ColourBy = colour_by;
2860    switch (colour_by) {
2861        case COLOUR_BY_DEPTH:
2862            AddQuad = &GfxCore::AddQuadrilateralDepth;
2863            AddPoly = &GfxCore::AddPolylineDepth;
2864            break;
2865        case COLOUR_BY_DATE:
2866            AddQuad = &GfxCore::AddQuadrilateralDate;
2867            AddPoly = &GfxCore::AddPolylineDate;
2868            break;
2869        case COLOUR_BY_ERROR:
2870            AddQuad = &GfxCore::AddQuadrilateralError;
2871            AddPoly = &GfxCore::AddPolylineError;
2872            break;
2873        default: // case COLOUR_BY_NONE:
2874            AddQuad = &GfxCore::AddQuadrilateral;
2875            AddPoly = &GfxCore::AddPolyline;
2876            break;
2877    }
2878
2879    InvalidateList(LIST_UNDERGROUND_LEGS);
2880    InvalidateList(LIST_SURFACE_LEGS);
2881    InvalidateList(LIST_TUBES);
2882
2883    ForceRefresh();
2884}
2885
2886bool GfxCore::ExportMovie(const wxString & fnm)
2887{
2888    int width;
2889    int height;
2890    GetSize(&width, &height);
2891    // Round up to next multiple of 2 (required by ffmpeg).
2892    width += (width & 1);
2893    height += (height & 1);
2894
2895    movie = new MovieMaker();
2896
2897    // FIXME: This should really use fn_str() - currently we probably can't
2898    // save to a Unicode path on wxmsw.
2899    if (!movie->Open(fnm.mb_str(), width, height)) {
2900        wxGetApp().ReportError(wxString(movie->get_error_string(), wxConvUTF8));
2901        delete movie;
2902        movie = NULL;
2903        return false;
2904    }
2905
2906    PlayPres(1);
2907    return true;
2908}
2909
2910void
2911GfxCore::OnPrint(const wxString &filename, const wxString &title,
2912                 const wxString &datestamp)
2913{
2914    svxPrintDlg * p;
2915    p = new svxPrintDlg(m_Parent, filename, title, datestamp,
2916                        m_PanAngle, m_TiltAngle,
2917                        m_Names, m_Crosses, m_Legs, m_Surface,
2918                        true);
2919    p->Show(TRUE);
2920}
2921
2922void
2923GfxCore::OnExport(const wxString &filename, const wxString &title)
2924{
2925    svxPrintDlg * p;
2926    p = new svxPrintDlg(m_Parent, filename, title, wxString(),
2927                        m_PanAngle, m_TiltAngle,
2928                        m_Names, m_Crosses, m_Legs, m_Surface,
2929                        false);
2930    p->Show(TRUE);
2931}
2932
2933static wxCursor
2934make_cursor(const unsigned char * bits, const unsigned char * mask,
2935            int hotx, int hoty)
2936{
2937#if defined __WXMSW__ || defined __WXMAC__
2938    wxBitmap cursor_bitmap(reinterpret_cast<const char *>(bits), 32, 32);
2939    wxBitmap mask_bitmap(reinterpret_cast<const char *>(mask), 32, 32);
2940    cursor_bitmap.SetMask(new wxMask(mask_bitmap));
2941    wxImage cursor_image = cursor_bitmap.ConvertToImage();
2942    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_X, hotx);
2943    cursor_image.SetOption(wxIMAGE_OPTION_CUR_HOTSPOT_Y, hoty);
2944    return wxCursor(cursor_image);
2945#else
2946    return wxCursor((const char *)bits, 32, 32, hotx, hoty,
2947                    (const char *)mask, wxWHITE, wxBLACK);
2948#endif
2949}
2950
2951const
2952#include "hand.xbm"
2953const
2954#include "handmask.xbm"
2955
2956const
2957#include "brotate.xbm"
2958const
2959#include "brotatemask.xbm"
2960
2961const
2962#include "vrotate.xbm"
2963const
2964#include "vrotatemask.xbm"
2965
2966const
2967#include "rotate.xbm"
2968const
2969#include "rotatemask.xbm"
2970
2971const
2972#include "rotatezoom.xbm"
2973const
2974#include "rotatezoommask.xbm"
2975
2976void
2977GfxCore::SetCursor(GfxCore::cursor new_cursor)
2978{
2979    // Check if we're already showing that cursor.
2980    if (current_cursor == new_cursor) return;
2981
2982    current_cursor = new_cursor;
2983    switch (current_cursor) {
2984        case GfxCore::CURSOR_DEFAULT:
2985            GLACanvas::SetCursor(wxNullCursor);
2986            break;
2987        case GfxCore::CURSOR_POINTING_HAND:
2988            GLACanvas::SetCursor(wxCursor(wxCURSOR_HAND));
2989            break;
2990        case GfxCore::CURSOR_DRAGGING_HAND:
2991            GLACanvas::SetCursor(make_cursor(hand_bits, handmask_bits, 12, 18));
2992            break;
2993        case GfxCore::CURSOR_HORIZONTAL_RESIZE:
2994            GLACanvas::SetCursor(wxCursor(wxCURSOR_SIZEWE));
2995            break;
2996        case GfxCore::CURSOR_ROTATE_HORIZONTALLY:
2997            GLACanvas::SetCursor(make_cursor(rotate_bits, rotatemask_bits, 15, 15));
2998            break;
2999        case GfxCore::CURSOR_ROTATE_VERTICALLY:
3000            GLACanvas::SetCursor(make_cursor(vrotate_bits, vrotatemask_bits, 15, 15));
3001            break;
3002        case GfxCore::CURSOR_ROTATE_EITHER_WAY:
3003            GLACanvas::SetCursor(make_cursor(brotate_bits, brotatemask_bits, 15, 15));
3004            break;
3005        case GfxCore::CURSOR_ZOOM:
3006            GLACanvas::SetCursor(wxCursor(wxCURSOR_MAGNIFIER));
3007            break;
3008        case GfxCore::CURSOR_ZOOM_ROTATE:
3009            GLACanvas::SetCursor(make_cursor(rotatezoom_bits, rotatezoommask_bits, 15, 15));
3010            break;
3011    }
3012}
3013
3014bool GfxCore::MeasuringLineActive() const
3015{
3016    if (Animating()) return false;
3017    return (m_here.IsValid() && !m_here_is_temporary) || m_there.IsValid();
3018}
3019
3020bool GfxCore::HandleRClick(wxPoint point)
3021{
3022    if (PointWithinCompass(point)) {
3023        // Pop up menu.
3024        wxMenu menu;
3025        menu.Append(menu_ORIENT_MOVE_NORTH, wmsg(/*View &North*/240));
3026        menu.Append(menu_ORIENT_MOVE_EAST, wmsg(/*View &East*/241));
3027        menu.Append(menu_ORIENT_MOVE_SOUTH, wmsg(/*View &South*/242));
3028        menu.Append(menu_ORIENT_MOVE_WEST, wmsg(/*View &West*/243));
3029        menu.AppendSeparator();
3030        menu.AppendCheckItem(menu_IND_COMPASS, wmsg(/*&Hide Compass*/344));
3031        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3032        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&MainFrm::ProcessEvent, NULL, m_Parent);
3033        PopupMenu(&menu);
3034        return true;
3035    }
3036
3037    if (PointWithinClino(point)) {
3038        // Pop up menu.
3039        wxMenu menu;
3040        menu.Append(menu_ORIENT_PLAN, wmsg(/*&Plan View*/248));
3041        menu.Append(menu_ORIENT_ELEVATION, wmsg(/*Ele&vation*/249));
3042        menu.AppendSeparator();
3043        menu.AppendCheckItem(menu_IND_CLINO, wmsg(/*&Hide Clino*/384));
3044        menu.AppendCheckItem(menu_CTL_DEGREES, wmsg(/*&Degrees*/343));
3045        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&MainFrm::ProcessEvent, NULL, m_Parent);
3046        PopupMenu(&menu);
3047        return true;
3048    }
3049
3050    if (PointWithinScaleBar(point)) {
3051        // Pop up menu.
3052        wxMenu menu;
3053        menu.AppendCheckItem(menu_IND_SCALE_BAR, wmsg(/*&Hide scale bar*/385));
3054        menu.AppendCheckItem(menu_CTL_METRIC, wmsg(/*&Metric*/342));
3055        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&MainFrm::ProcessEvent, NULL, m_Parent);
3056        PopupMenu(&menu);
3057        return true;
3058    }
3059
3060#if 0 // FIXME: Don't yet have PointWithinColourKey() method.
3061    if (PointWithinColourKey(point)) {
3062        // Pop up menu.
3063        wxMenu menu;
3064        menu.AppendCheckItem(menu_IND_COLOUR_KEY, wmsg(/*&Hide colour key*/386));
3065        menu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&MainFrm::OnToggleMetric, NULL, m_Parent);
3066        PopupMenu(&menu);
3067        return true;
3068    }
3069#endif
3070
3071    return false;
3072}
Note: See TracBrowser for help on using the repository browser.