source: git/src/gfxcore.cc @ 40c38bb

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

src/gfxcore.cc: Make COLOUR_KEY_OFFSET_X and COLOUR_KEY_OFFSET_Y the
actual offsets, rather than taking COLOUR_KEY_MARGIN off them.

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

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