File: situationscene.cpp

package info (click to toggle)
boats 201307-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,424 kB
  • ctags: 1,486
  • sloc: cpp: 10,139; makefile: 13; xml: 10
file content (730 lines) | stat: -rw-r--r-- 25,834 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//
// C++ Implementation: situationscene
//
// Description:
//
//
// Author: Thibaut GRIDEL <tgridel@free.fr>
//
// Copyright (c) 2008-2011 Thibaut GRIDEL
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//
#include <iostream>
#include <cmath>

#include <QtGui>

#include "situationscene.h"

#include "commontypes.h"
#include "undocommands.h"

#include "situationmodel.h"
#include "trackmodel.h"
#include "boatmodel.h"
#include "markmodel.h"
#include "polylinemodel.h"
#include "pointmodel.h"
#include "windmodel.h"

#include "boat.h"
#include "track.h"
#include "mark.h"
#include "polyline.h"
#include "point.h"
#include "arrow.h"
#include "trackanimation.h"
#include "scenarioanimation.h"
#include "angleanimation.h"

extern int debugLevel;

SituationScene::SituationScene(SituationModel *situation)
        : QGraphicsScene(situation),
        m_situation(situation),
        m_scenarioAnimation(new ScenarioAnimation),
        m_trackCreated(0),
        m_state(NO_STATE),
        m_time(QTime::currentTime()),
        m_clickTime(QTime::currentTime()),
        m_clickState(SINGLE),
        m_defaultPopup(0),
        m_boatPopup(0),
        m_markPopup(0),
        m_pointPopup(0) {

    setItemIndexMethod(NoIndex);

    // set a minimum scene rect
    setSceneRect(-10000, -10000, 20000, 20000);

    // react to self change of selection
    connect(this, SIGNAL(selectionChanged()),
            this, SLOT(setSelectedModels()));

    // react to model track add
    connect(situation, SIGNAL(trackAdded(TrackModel*)),
            this, SLOT(addTrack(TrackModel*)));

    // react to model boat add
    connect(situation, SIGNAL(boatAdded(BoatModel*)),
            this, SLOT(addBoatItem(BoatModel*)));

    // react to model mark add
    connect(situation, SIGNAL(markAdded(MarkModel*)),
            this, SLOT(addMarkItem(MarkModel*)));

    // react to model line add
    connect(situation, SIGNAL(polyLineAdded(PolyLineModel*)),
            this, SLOT(addPolyLine(PolyLineModel*)));

    // react to model point add
    connect(situation, SIGNAL(pointAdded(PointModel*)),
            this, SLOT(addPoint(PointModel*)));

    // react to layline angle
    connect(situation, SIGNAL(laylineChanged(const int)),
            this, SLOT(setLaylines(const int)));

    connect(&situation->wind(), SIGNAL(windVisibleChanged(bool)),
            this, SLOT(setWind(bool)));

    connect(situation, SIGNAL(lookDirectionChanged(qreal)),
             this, SIGNAL(lookDirectionChanged(qreal)));
    connect(situation, SIGNAL(tiltChanged(qreal)),
            this, SIGNAL(tiltChanged(qreal)));

    setLaylines(situation->laylineAngle());

}

void SituationScene::setState(const SceneState& theValue, bool commit) {
    // undo previous state's settings
    switch(m_state) {
    case CREATE_TRACK:
    case CREATE_BOAT:
    case CREATE_MARK:
    case CREATE_LINE:
    case CREATE_POINT: {
            m_situation->undoStack()->endMacro();
            if (!commit) {
                m_situation->undoStack()->undo();
            }
        }
        break;
    default:
        break;
    }
    switch(theValue) {
    case CREATE_TRACK: {
            createTrack(m_curPosition);
        }
        break;
    case CREATE_BOAT: {
            createBoat(m_curPosition);
        }
        break;
    case CREATE_MARK: {
            createMark(m_curPosition);
        }
        break;
    case CREATE_LINE: {
            createLine(m_curPosition);
        }
        break;
    case CREATE_POINT: {
            createPoint(m_curPosition);
        }
        break;
    default:
        break;
    }
    m_state = theValue;
    emit stateChanged(m_state);
}

void SituationScene::addTrack(TrackModel *track) {
    if (debugLevel & 1 << VIEW) std::cout << "adding track graphics for model " << track << std::endl;
    TrackGraphicsItem *trackItem = new TrackGraphicsItem(track);
    addItem(trackItem);
}

void SituationScene::addBoatItem(BoatModel *boat) {
    if (debugLevel & 1 << VIEW) std::cout << "adding boat graphics for model " << boat << std::endl;
    BoatGraphicsItem *boatItem = new BoatGraphicsItem(boat);
    addItem(boatItem);
}

void SituationScene::addMarkItem(MarkModel *mark) {
    if (debugLevel & 1 << VIEW) std::cout << "adding mark graphics for model " << mark << std::endl;
    MarkGraphicsItem *markItem = new MarkGraphicsItem(mark);
    addItem(markItem);
}

void SituationScene::addPolyLine(PolyLineModel *polyline) {
    if (debugLevel & 1 << VIEW) std::cout << "adding line graphics for model " << polyline << std::endl;
    PolyLineGraphicsItem *polyLineItem = new PolyLineGraphicsItem(polyline);
    addItem(polyLineItem);
}

void SituationScene::addPoint(PointModel *point) {
    if (debugLevel & 1 << VIEW) std::cout << "adding point graphics for model " << point << std::endl;
    PointGraphicsItem *pointItem = new PointGraphicsItem(point);
    addItem(pointItem);
}

void SituationScene::setWind(bool visible) {
    if (visible) {
        if (debugLevel & 1 << VIEW) std::cout << "adding wind graphics" << std::endl;
        ArrowGraphicsItem *arrow= new ArrowGraphicsItem(&m_situation->wind());
        addItem(arrow);
    }
}

/**
    Prepares the Scene for animation mode.
    This method finds the maximum size of track, and sets the timer length
    accordingly.
    It then creates a BoatGraphicsItem for animation purpose, and associates
    an TrackAnimation.
*/

void SituationScene::setAnimation() {
    if (debugLevel & 1 << VIEW) std::cout << "preparing for Animation" << std::endl;
    int maxSize = 0;
    foreach (const TrackModel *track, m_situation->tracks()) {
        if (track->boats().size() > maxSize)
            maxSize = track->boats().size() - 1;
    }

    m_windAnimation = new QSequentialAnimationGroup(this);
    for (int i = 0; i < m_situation->wind().size()-1; ++i) {
        AngleAnimation *wind = new AngleAnimation(&m_situation->wind(), "direction");
        wind->setDuration(2000);
        wind->setStartValue(m_situation->wind().windAt(i));
        wind->setEndValue(m_situation->wind().windAt(i+1));
        m_windAnimation->addAnimation(wind);
    }
    m_scenarioAnimation->addAnimation(m_windAnimation);


    foreach (TrackModel *track, m_situation->tracks()) {
        BoatModel *boat = track->boats()[0];
        BoatGraphicsItem *boatItem = new BoatGraphicsItem(new BoatModel(track));
        addItem(boatItem);
        boatItem->boat()->setOrder(0);
        boatItem->setPosition(boat->position());
        boatItem->setHeading(boat->heading());
        boatItem->boat()->setWind(m_situation->wind().windAt(0));
        boatItem->boat()->setLaylines(boat->laylines());
        connect(&track->situation()->wind(), SIGNAL(directionChanged(qreal)),
                boatItem->boat(), SLOT(setWind(qreal)));
        QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect;
        shadow->setXOffset(4);
        shadow->setYOffset(4);
        shadow->setBlurRadius(4);
        boatItem->setGraphicsEffect(shadow);

        TrackAnimation *animation = new TrackAnimation(track, boatItem->boat(), m_scenarioAnimation);
        m_scenarioAnimation->addAnimation(animation);
        m_animationItems.push_back(animation);

        if(track->followTrack()) {
            connect(boatItem->boat(), SIGNAL(positionChanged(QPointF)),
                    this, SIGNAL(centerChanged(QPointF)));
            disconnect(m_situation, SIGNAL(lookDirectionChanged(qreal)));
            connect(boatItem->boat(), SIGNAL(headingChanged(qreal)),
                    this, SIGNAL(lookDirectionChanged(qreal)));
        }
    }

    foreach (MarkModel *mark, m_situation->marks()) {
        connect(&m_situation->wind(), SIGNAL(directionChanged(qreal)),
                mark, SLOT(setWind(qreal)));
    }

    foreach(PolyLineModel *poly, m_situation->polyLines()) {
        foreach(PointModel *point, poly->points()) {
            connect(&m_situation->wind(), SIGNAL(directionChanged(qreal)),
                    point, SLOT(setWind(qreal)));
        }
    }
}

/**
    Restores the Scene out of animation mode.
    This method brings the scene back to the normal drawing mode.
    For this it removes all TrackAnimation objects created in setAnimation().
*/

void SituationScene::unSetAnimation() {
    if (debugLevel & 1 << VIEW) std::cout << "ending Animation" << std::endl;

    m_situation->wind().setDirection(m_situation->wind().windAt(0));
    m_scenarioAnimation->removeAnimation(m_windAnimation);
    for (int i = 0; i < m_situation->wind().size()-1; ++i) {
        QAbstractAnimation *animation = m_windAnimation->animationAt(0);
        m_windAnimation->removeAnimation(animation);
        delete animation;
    }
    delete m_windAnimation;

    foreach (TrackAnimation *animation, m_animationItems) {
        // the boat was never really part of the track, we use situation signal
        // directly to have the graphicsitem removed
        animation->boat()->track()->situation()->removingBoat(animation->boat());
        m_scenarioAnimation->removeAnimation(animation);
        m_animationItems.removeOne(animation);
        delete animation->boat();
        delete animation;
    }

    foreach (MarkModel *mark, m_situation->marks()) {
        disconnect(mark, SLOT(setWind(qreal)));
    }
}

/**
    Reacts to user keyboard actions in the Scene
    This method modifies the associated SituationModel through the
    concerned Undo Framework class. Handled keys are for
    - heading of selected boats (+,-)
    - position of selected objects (H (left), L (right), J (down), K (up))
*/

void SituationScene::keyPressEvent(QKeyEvent *event) {

    if (!m_selectedBoatModels.isEmpty()) {
// Trim just the jib when ',' or '.' is pressed (TrimJibUndoCommand only trims the jib)
// But not when Ctrl is pressed - reserve that for spinTrim
        if (event->key() == Qt::Key_Comma && !(event->modifiers() & Qt::ControlModifier)) {
            m_situation->undoStack()->push(new TrimJibUndoCommand(m_selectedBoatModels, m_selectedBoatModels[0]->jibTrim() - 5));
        } else if (event->key() == Qt::Key_Period && !(event->modifiers() & Qt::ControlModifier)) {
            m_situation->undoStack()->push(new TrimJibUndoCommand(m_selectedBoatModels, m_selectedBoatModels[0]->jibTrim() + 5));
// Trim the spin when Ctrl+',' or Ctrl+'.' is pressed
        }else if (event->key() == Qt::Key_Comma && (event->modifiers() & Qt::ControlModifier)) {
            m_situation->undoStack()->push(new TrimSpinUndoCommand(m_selectedBoatModels, m_selectedBoatModels[0]->spinTrim() - 5));
        } else if (event->key() == Qt::Key_Period && (event->modifiers() & Qt::ControlModifier)) {
            m_situation->undoStack()->push(new TrimSpinUndoCommand(m_selectedBoatModels, m_selectedBoatModels[0]->spinTrim() + 5));
        }
    }

    if (!m_selectedModels.isEmpty()) {
        if (event->key() == Qt::Key_Left) {
            QPointF pos(-5,0);
            m_situation->undoStack()->push(new MoveModelUndoCommand(m_selectedModels, pos));

        } else if (event->key() == Qt::Key_Right) {
            QPointF pos(5,0);
            m_situation->undoStack()->push(new MoveModelUndoCommand(m_selectedModels, pos));

        } else if (event->key() == Qt::Key_Up) {
            QPointF pos(0,-5);
            m_situation->undoStack()->push(new MoveModelUndoCommand(m_selectedModels, pos));

        } else if (event->key() == Qt::Key_Down) {
            QPointF pos(0,5);
            m_situation->undoStack()->push(new MoveModelUndoCommand(m_selectedModels, pos));

        } else if (event->key() == Qt::Key_Plus) {
            m_situation->undoStack()->push(new RotateModelsUndoCommand(m_selectedModels, 5.0));

        } else if (event->key() == Qt::Key_Minus) {
            m_situation->undoStack()->push(new RotateModelsUndoCommand(m_selectedModels, -5.0));

        } else {
            QGraphicsScene::keyPressEvent(event);
        }
    } else {
        QGraphicsScene::keyPressEvent(event);
    }
}

/**
    Sets selection depending on modal status.
    Selection happens with left button in NO_STATE, and right button in CREATE_BOAT
    and CREATE_MARK modes.
*/

void SituationScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
    switch (m_state) {
        case NO_STATE:
            mouseSelectEvent(event);
            if (!m_selectedBoatModels.isEmpty()) {
                m_trackCreated = m_selectedBoatModels[0]->track();
            }
            if (!m_selectedPointModels.isEmpty()) {
                m_polyLineCreated = m_selectedPointModels[0]->polyLine();
            }
            break;
        case CREATE_TRACK:
        case CREATE_BOAT:
        case CREATE_MARK:
            if (event->buttons() == Qt::RightButton
                || (event->buttons() == Qt::LeftButton
                    && ((event->modifiers() & Qt::MetaModifier) != 0))) {
                mouseSelectEvent(event);
            }
            break;
        default:
            break;
    }

    m_clickTime.start();
}

/**
    Handles a timer to limit user interaction
    This method limits the move processing to one event handled per 40ms.
    This is very noticeable on Windows platform, and the
    culprit is the drawing, not the model setting.
*/

void SituationScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
    // limit update rate to 40ms
    if ((m_time.elapsed() <40) ) {
        return;
    }

    QGraphicsScene::mouseMoveEvent(event);

    switch (m_state) {
        case NO_STATE:
            if (event->buttons() == Qt::LeftButton
                && (event->modifiers() & Qt::MetaModifier) == 0) {
                moveModel(event->scenePos());
            }
            if (event->buttons() == Qt::RightButton
                || (event->buttons() == Qt::LeftButton
                    && ((event->modifiers() & Qt::MetaModifier) != 0))) {
                headingModel(event->scenePos());
            }
        break;
        case CREATE_TRACK:
            if (event->buttons() == Qt::NoButton) {
                m_trackCreated->boats().last()->setPosition(event->scenePos());
            }
            if (event->buttons() == Qt::RightButton
                || (event->buttons() == Qt::LeftButton
                    && ((event->modifiers() & Qt::MetaModifier) != 0))) {
                headingModel(event->scenePos());
            }
            break;
        case CREATE_BOAT:
            if (event->buttons() == Qt::NoButton) {
                qreal heading = m_trackCreated->headingForNext(
                        m_trackCreated->boats().size()-2, event->scenePos());
                m_trackCreated->boats().last()->setHeading(heading);
                m_trackCreated->boats().last()->setPosition(event->scenePos());
            }
            if (event->buttons() == Qt::RightButton
                || (event->buttons() == Qt::LeftButton
                    && ((event->modifiers() & Qt::MetaModifier) != 0))) {
                headingModel(event->scenePos());
            }
            break;
        case CREATE_MARK:
            if (event->buttons() == Qt::NoButton) {
                m_markCreated->setPosition(event->scenePos());
            }
            break;
        case CREATE_LINE:
        case CREATE_POINT:
            if (event->buttons() == Qt::NoButton) {
                m_polyLineCreated->points().last()->setPosition(event->scenePos());
            }
            break;
        default:
            break;
    }

    // trigger next update rate calculation
    m_time.start();
    m_curPosition = event->scenePos();
}

/**
    Performs action depending of button and mode
    This method will trigger performing of actions like:
    - setting position of selected objects
    - setting heading of selected BoatGraphicsItem
    - creating new TrackModel, BoatModel or MarkModel according to mode.
*/

void SituationScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
    QGraphicsScene::mouseReleaseEvent(event);

    if (m_clickState != SINGLE) {
        m_clickState = SINGLE;
        return;
    }
    mouseClickEvent(event);
}

void SituationScene::mouseClickEvent(QGraphicsSceneMouseEvent *event) {
    bool click = (m_clickTime.elapsed() < 250);
    if (click && (event->button() == Qt::RightButton
                || (event->button() == Qt::LeftButton
                    && ((event->modifiers() & Qt::MetaModifier) != 0)))) {
        if (!m_selectedModels.isEmpty()) {
            switch(selectedItems()[0]->type()) {
                case BOAT_TYPE: {
                    m_boatPopup->popup(event->screenPos());
                    return;
                }
                break;

                case MARK_TYPE: {
                    m_markPopup->popup(event->screenPos());
                    return;
                }
                break;
                case POINT_TYPE: {
                    m_pointPopup->popup(event->screenPos());
                    return;
                }
                break;
            }
        }
        m_defaultPopup->popup(event->screenPos());
        return;
    }

    switch (m_state) {
        case NO_STATE:
            if (event->button() == Qt::LeftButton
                && (event->modifiers() & Qt::MetaModifier) == 0) {
                moveModel(event->scenePos());
            }
            if (event->button() == Qt::RightButton
                || (event->button() == Qt::LeftButton
                    && ((event->modifiers() & Qt::MetaModifier) != 0))) {
                headingModel(event->scenePos());
            }
            break;
        case CREATE_TRACK:
            if (event->button() == Qt::LeftButton) {
                setState(CREATE_BOAT, true);
            }
            break;
        case CREATE_BOAT:
            if (event->button() == Qt::LeftButton) {
                if ((event->modifiers() & Qt::ControlModifier) != 0) {
                    setState(CREATE_BOAT, true);
                } else if ((event->modifiers() & Qt::MetaModifier) == 0) {
                    createBoat(event->scenePos());
                }
            }
            if (event->button() == Qt::RightButton
                || (event->button() == Qt::LeftButton
                    && ((event->modifiers() & Qt::MetaModifier) != 0))) {
                headingModel(event->scenePos());
            }
            break;
        case CREATE_MARK:
            if (event->button() == Qt::LeftButton) {
                createMark(event->scenePos());
            }
            break;
        case CREATE_LINE:
            if (event->button() == Qt::LeftButton) {
                setState(CREATE_POINT, true);
            }
            break;
        case CREATE_POINT:
            if (event->button() == Qt::LeftButton) {
                createPoint(event->scenePos());
            }
        default:
            break;
    }
}

void SituationScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) {
    Q_UNUSED(event);
    m_clickState = DOUBLE;
    setState(NO_STATE);
    m_situation->undoStack()->undo();
}

void SituationScene::mouseSelectEvent(QGraphicsSceneMouseEvent *event) {
    // propagate mouse event first for selected items
    QGraphicsScene::mousePressEvent(event);

    m_fromPosition = event->scenePos();
    if (debugLevel & 1 << VIEW) std::cout << "Mouse pressed with " << m_selectedModels.size()
    << " items selected" << std::endl;
}

void SituationScene::moveModel(QPointF pos) {
    if (!m_selectedModels.isEmpty() && pos != m_fromPosition) {
        m_situation->undoStack()->push(new MoveModelUndoCommand(m_selectedModels,(pos-m_fromPosition)));
        m_fromPosition = pos;
    }
}

void SituationScene::headingModel(QPointF pos) {
    if (!m_selectedModels.isEmpty() && pos != m_modelPressed->position()) {
        QPointF point = pos - m_modelPressed->position();
        qreal wind = m_modelPressed->wind();
        qreal theta = fmod((atan2 (point.x(), -point.y()) * 180 / M_PI) + 360.0, 360.0);
        qreal delta = fmod(theta - wind + 360, 360);
        qreal snap = m_situation->laylineAngle();
        // face to wind
        if (fabs(delta)<=5) {
            theta = wind;
        // port closehauled
        } else if (fabs(delta - snap)<=5) {
            theta = fmod(wind + snap, 360);
        // port downwind
        } else if (fabs(delta -(180-snap)) <=5) {
            theta = fmod(wind + 180-snap, 360);
        // deadwind
        } else if (fabs(delta - 180)<=5) {
            theta = fmod(wind - 180, 360);
        // starboard downwind
        } else if (fabs(delta - (180+snap)) <=5) {
            theta = fmod(wind + 180 + snap, 360);
        // starboard closehauled
        } else if (fabs(delta - (360-snap)) <=5) {
            theta = fmod(wind + 360 - snap, 360);
        }
        m_situation->undoStack()->push(new RotateModelsUndoCommand(m_selectedModels, theta-m_modelPressed->heading()));
    }
}

void SituationScene::createTrack(QPointF pos) {
    AddTrackUndoCommand *command = new AddTrackUndoCommand(m_situation);
    m_situation->undoStack()->push(command);
    TrackModel *track = command->track();
    BoatModel *boat = new BoatModel(track, track);
    boat->setDim(64);
    boat->setPosition(pos);
    track->addBoat(boat);
    m_trackCreated = track;
}

void SituationScene::createBoat(QPointF pos) {
    if (m_trackCreated) {
        m_situation->undoStack()->endMacro();
        m_trackCreated->boats().last()->setDim(255);
        qreal heading = m_trackCreated->boats().last()->heading();
        AddBoatUndoCommand *command = new AddBoatUndoCommand(m_trackCreated, pos, heading);
        command->boat()->setDim(64);
        m_situation->undoStack()->beginMacro("");
        m_situation->undoStack()->push(command);
    }
}

void SituationScene::createMark(QPointF pos) {
    m_situation->undoStack()->endMacro();
    AddMarkUndoCommand *command = new AddMarkUndoCommand(m_situation, pos);
    m_markCreated = command->mark();
    m_situation->undoStack()->beginMacro("");
    m_situation->undoStack()->push(command);
}

void SituationScene::createLine(QPointF pos) {
    AddPolyLineUndoCommand *command = new AddPolyLineUndoCommand(m_situation);
    m_situation->undoStack()->push(command);
    m_polyLineCreated = command->polyLine();
    PointModel *point = new PointModel(m_polyLineCreated);
    point->setPosition(pos);
    m_polyLineCreated->addPoint(point);
}

void SituationScene::createPoint(QPointF pos) {
    if (m_polyLineCreated) {
        m_situation->undoStack()->endMacro();
        AddPointUndoCommand *command = new AddPointUndoCommand(
                m_polyLineCreated, pos);
        m_situation->undoStack()->beginMacro("");
        m_situation->undoStack()->push(command);
    }
}

void SituationScene::setSelectedModels() {
    m_selectedModels.clear();
    m_selectedBoatModels.clear();
    m_selectedMarkModels.clear();
    m_selectedPointModels.clear();
    foreach (QGraphicsItem *item, selectedItems()) {
        switch(item->type()) {
            case BOAT_TYPE: {
                BoatModel *boat = (qgraphicsitem_cast<BoatGraphicsItem*>(item))->boat();
                m_selectedModels << boat;
                m_selectedBoatModels << boat;
                }
                break;
            case MARK_TYPE: {
                MarkModel *mark = (qgraphicsitem_cast<MarkGraphicsItem*>(item))->mark();
                m_selectedModels << mark;
                m_selectedMarkModels << mark;
                }
                break;
            case POINT_TYPE: {
                PointModel *point = (qgraphicsitem_cast<PointGraphicsItem*>(item))->point();
                m_selectedModels << point;
                m_selectedPointModels << point;
                }
                break;
            case ARROW_TYPE: {
                WindModel *wind = &m_situation->wind();
                m_selectedModels << wind;
            }
        }
    }
    if (debugLevel & 1 << VIEW) std::cout << "SelectedModels update " << m_selectedModels.size() << std::endl;
    emit selectedModelsChanged();
}


void SituationScene::setLaylines(const int angle) {
    if (!m_situation->showLayline()) {
        if (debugLevel & 1 << VIEW) std::cout << "reseting empty Background" << std::endl;
        setBackgroundBrush(Qt::NoBrush);
        return;
    }
    if (debugLevel & 1 << VIEW) std::cout << "creating layline Background for " << angle << std::endl;
    qreal theta = angle * M_PI /180;
    int length = Boats::seriesSizeList()[m_situation->situationSeries()];

    // draw 4 times as big, then use transform to scale back the brush
    // gives better precision grid
    qreal x = 2*length*sin(theta) * 4;
    qreal y = 2*length*cos(theta) * 4;

    QPixmap pixmap(x,y);
    pixmap.fill(Qt::transparent);
    QPainter painter(&pixmap);
    QPen pen;
    pen.setWidth(2);
    QVector<qreal> dashes;
    dashes << length/10.0 << length/5.0;
    pen.setStyle(Qt::CustomDashLine);
    pen.setDashPattern(dashes);
    painter.setPen(pen);
    painter.setRenderHints(QPainter::Antialiasing);
    painter.drawLine(QLineF(0,0,x,y));
    painter.drawLine(QLineF(0,y,x,0));

    QBrush brush;
    QTransform transform;
    transform.scale(0.25, 0.25);
    brush.setTransform(transform);
    brush.setTexture(pixmap);
    setBackgroundBrush(brush);
}