source: git/src/gfxcore.cc @ a874142

RELEASE/1.2debug-cidebug-ci-sanitisersstereowalls-datawalls-data-hanging-as-warning
Last change on this file since a874142 was a874142, checked in by Olly Betts <olly@…>, 10 years ago

src/gfxcore.cc: Don't crash with assertion failure when showing
passages for a cave with no vertical extent. Reported by Jonny
Prouty.

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