File: terraintexturemode.cpp

package info (click to toggle)
openmw 0.50.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,076 kB
  • sloc: cpp: 380,958; xml: 2,192; sh: 1,449; python: 911; makefile: 26; javascript: 5
file content (776 lines) | stat: -rw-r--r-- 31,156 bytes parent folder | download
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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
#include "terraintexturemode.hpp"

#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <exception>
#include <limits>
#include <string>

#include <QDropEvent>
#include <QIcon>
#include <QSlider>
#include <QWidget>

#include <osg/Vec2f>
#include <osg/Vec3d>

#include <apps/opencs/model/prefs/category.hpp>
#include <apps/opencs/model/prefs/setting.hpp>
#include <apps/opencs/model/world/cellcoordinates.hpp>
#include <apps/opencs/model/world/cellselection.hpp>
#include <apps/opencs/model/world/columnimp.hpp>
#include <apps/opencs/model/world/columns.hpp>
#include <apps/opencs/model/world/idcollection.hpp>
#include <apps/opencs/model/world/record.hpp>
#include <apps/opencs/view/render/terrainselection.hpp>
#include <apps/opencs/view/widget/scenetool.hpp>

#include <components/misc/scalableicon.hpp>
#include <components/misc/strings/conversion.hpp>

#include "../widget/scenetoolbar.hpp"
#include "../widget/scenetooltexturebrush.hpp"

#include "../../model/doc/document.hpp"
#include "../../model/prefs/state.hpp"
#include "../../model/world/commands.hpp"
#include "../../model/world/data.hpp"
#include "../../model/world/idtable.hpp"
#include "../../model/world/idtree.hpp"
#include "../../model/world/tablemimedata.hpp"
#include "../../model/world/universalid.hpp"

#include "brushdraw.hpp"
#include "editmode.hpp"
#include "mask.hpp"
#include "pagedworldspacewidget.hpp"
#include "worldspacewidget.hpp"

CSVRender::TerrainTextureMode::TerrainTextureMode(
    WorldspaceWidget* worldspaceWidget, osg::Group* parentNode, QWidget* parent)
    : EditMode(worldspaceWidget, Misc::ScalableIcon::load(":scenetoolbar/editing-terrain-texture"),
        Mask_Terrain | Mask_Reference, "Terrain texture editing", parent)
    , mBrushSize(1)
    , mBrushShape(CSVWidget::BrushShape_Point)
    , mTextureBrushScenetool(nullptr)
    , mDragMode(InteractionType_None)
    , mParentNode(parentNode)
    , mIsEditing(false)
{
}

void CSVRender::TerrainTextureMode::activate(CSVWidget::SceneToolbar* toolbar)
{
    if (!mTextureBrushScenetool)
    {
        mTextureBrushScenetool = new CSVWidget::SceneToolTextureBrush(
            toolbar, "scenetooltexturebrush", getWorldspaceWidget().getDocument());
        connect(mTextureBrushScenetool, &CSVWidget::SceneTool::clicked, mTextureBrushScenetool,
            &CSVWidget::SceneToolTextureBrush::activate);
        connect(mTextureBrushScenetool->mTextureBrushWindow, &CSVWidget::TextureBrushWindow::passBrushSize, this,
            &TerrainTextureMode::setBrushSize);
        connect(mTextureBrushScenetool->mTextureBrushWindow, &CSVWidget::TextureBrushWindow::passBrushShape, this,
            &TerrainTextureMode::setBrushShape);
        connect(mTextureBrushScenetool->mTextureBrushWindow->mSizeSliders->mBrushSizeSlider, &QSlider::valueChanged,
            this, &TerrainTextureMode::setBrushSize);
        connect(mTextureBrushScenetool, &CSVWidget::SceneToolTextureBrush::passTextureId, this,
            &TerrainTextureMode::setBrushTexture);
        connect(mTextureBrushScenetool->mTextureBrushWindow, &CSVWidget::TextureBrushWindow::passTextureId, this,
            &TerrainTextureMode::setBrushTexture);

        connect(mTextureBrushScenetool, qOverload<QDropEvent*>(&CSVWidget::SceneToolTextureBrush::passEvent), this,
            &TerrainTextureMode::handleDropEvent);
        connect(this, &TerrainTextureMode::passBrushTexture, mTextureBrushScenetool->mTextureBrushWindow,
            &CSVWidget::TextureBrushWindow::setBrushTexture);
        connect(this, &TerrainTextureMode::passBrushTexture, mTextureBrushScenetool,
            &CSVWidget::SceneToolTextureBrush::updateBrushHistory);
    }

    if (!mTerrainTextureSelection)
    {
        mTerrainTextureSelection
            = std::make_shared<TerrainSelection>(mParentNode, &getWorldspaceWidget(), TerrainSelectionType::Texture);
    }

    if (!mBrushDraw)
        mBrushDraw = std::make_unique<BrushDraw>(mParentNode, true);

    EditMode::activate(toolbar);
    toolbar->addTool(mTextureBrushScenetool);
}

void CSVRender::TerrainTextureMode::deactivate(CSVWidget::SceneToolbar* toolbar)
{
    if (mTextureBrushScenetool)
    {
        toolbar->removeTool(mTextureBrushScenetool);
        delete mTextureBrushScenetool;
        mTextureBrushScenetool = nullptr;
    }

    if (mTerrainTextureSelection)
    {
        mTerrainTextureSelection.reset();
    }

    if (mBrushDraw)
        mBrushDraw.reset();

    EditMode::deactivate(toolbar);
}

void CSVRender::TerrainTextureMode::primaryOpenPressed(const WorldspaceHitResult& hit) // Apply changes here
{
}

void CSVRender::TerrainTextureMode::primaryEditPressed(const WorldspaceHitResult& hit) // Apply changes here
{
    CSMDoc::Document& document = getWorldspaceWidget().getDocument();
    CSMWorld::IdTable& landTable
        = dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
    CSMWorld::IdTable& ltexTable
        = dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));

    mCellId = getWorldspaceWidget().getCellId(hit.worldPos);

    QUndoStack& undoStack = document.getUndoStack();
    CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = document.getData().getLandTextures();
    int index = landtexturesCollection.searchId(mBrushTexture);

    if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted() && hit.hit && hit.tag == nullptr)
    {
        undoStack.beginMacro("Edit texture records");
        if (allowLandTextureEditing(mCellId))
        {
            undoStack.push(new CSMWorld::TouchLandCommand(landTable, ltexTable, mCellId));
            editTerrainTextureGrid(hit);
        }
        undoStack.endMacro();
    }
}

void CSVRender::TerrainTextureMode::primarySelectPressed(const WorldspaceHitResult& hit)
{
    if (hit.hit && hit.tag == nullptr)
    {
        selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 0);
        mTerrainTextureSelection->clearTemporarySelection();
    }
}

void CSVRender::TerrainTextureMode::secondarySelectPressed(const WorldspaceHitResult& hit)
{
    if (hit.hit && hit.tag == nullptr)
    {
        selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 1);
        mTerrainTextureSelection->clearTemporarySelection();
    }
}

bool CSVRender::TerrainTextureMode::primaryEditStartDrag(const QPoint& pos)
{
    WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());

    CSMDoc::Document& document = getWorldspaceWidget().getDocument();
    CSMWorld::IdTable& landTable
        = dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
    CSMWorld::IdTable& ltexTable
        = dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));

    mCellId = getWorldspaceWidget().getCellId(hit.worldPos);

    QUndoStack& undoStack = document.getUndoStack();

    mDragMode = InteractionType_PrimaryEdit;

    CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = document.getData().getLandTextures();
    const int index = landtexturesCollection.searchId(mBrushTexture);

    if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted() && hit.hit && hit.tag == nullptr)
    {
        undoStack.beginMacro("Edit texture records");
        mIsEditing = true;
        if (allowLandTextureEditing(mCellId))
        {
            undoStack.push(new CSMWorld::TouchLandCommand(landTable, ltexTable, mCellId));
            editTerrainTextureGrid(hit);
        }
    }

    return true;
}

bool CSVRender::TerrainTextureMode::secondaryEditStartDrag(const QPoint& pos)
{
    return false;
}

bool CSVRender::TerrainTextureMode::primarySelectStartDrag(const QPoint& pos)
{
    WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
    mDragMode = InteractionType_PrimarySelect;
    if (!hit.hit || hit.tag != nullptr)
    {
        mDragMode = InteractionType_None;
        return false;
    }
    selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 0);
    return true;
}

bool CSVRender::TerrainTextureMode::secondarySelectStartDrag(const QPoint& pos)
{
    WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
    mDragMode = InteractionType_SecondarySelect;
    if (!hit.hit || hit.tag != nullptr)
    {
        mDragMode = InteractionType_None;
        return false;
    }
    selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 1);
    return true;
}

void CSVRender::TerrainTextureMode::drag(const QPoint& pos, int diffX, int diffY, double speedFactor)
{
    if (mDragMode == InteractionType_PrimaryEdit)
    {
        WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
        std::string cellId = getWorldspaceWidget().getCellId(hit.worldPos);
        CSMDoc::Document& document = getWorldspaceWidget().getDocument();

        CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = document.getData().getLandTextures();
        const int index = landtexturesCollection.searchId(mBrushTexture);

        if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted() && hit.hit && hit.tag == nullptr)
        {
            editTerrainTextureGrid(hit);
        }
    }

    if (mDragMode == InteractionType_PrimarySelect)
    {
        WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
        if (hit.hit && hit.tag == nullptr)
            selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 0);
    }

    if (mDragMode == InteractionType_SecondarySelect)
    {
        WorldspaceHitResult hit = getWorldspaceWidget().mousePick(pos, getWorldspaceWidget().getInteractionMask());
        if (hit.hit && hit.tag == nullptr)
            selectTerrainTextures(CSMWorld::CellCoordinates::toTextureCoords(hit.worldPos), 1);
    }
}

void CSVRender::TerrainTextureMode::dragCompleted(const QPoint& pos)
{
    if (mDragMode == InteractionType_PrimaryEdit && mIsEditing)
    {
        CSMDoc::Document& document = getWorldspaceWidget().getDocument();
        QUndoStack& undoStack = document.getUndoStack();

        CSMWorld::IdCollection<ESM::LandTexture>& landtexturesCollection = document.getData().getLandTextures();
        const int index = landtexturesCollection.searchId(mBrushTexture);

        if (index != -1 && !landtexturesCollection.getRecord(index).isDeleted())
        {
            undoStack.endMacro();
            mIsEditing = false;
        }
    }

    mTerrainTextureSelection->clearTemporarySelection();
}

void CSVRender::TerrainTextureMode::dragAborted() {}

void CSVRender::TerrainTextureMode::dragWheel(int diff, double speedFactor) {}

void CSVRender::TerrainTextureMode::handleDropEvent(QDropEvent* event)
{
    const CSMWorld::TableMimeData* mime = dynamic_cast<const CSMWorld::TableMimeData*>(event->mimeData());

    if (!mime) // May happen when non-records (e.g. plain text) are dragged and dropped
        return;

    if (mime->holdsType(CSMWorld::UniversalId::Type_LandTexture))
    {
        const std::vector<CSMWorld::UniversalId> ids = mime->getData();

        for (const CSMWorld::UniversalId& uid : ids)
        {
            mBrushTexture = ESM::RefId::stringRefId(uid.getId());
            emit passBrushTexture(mBrushTexture);
        }
    }
}

void CSVRender::TerrainTextureMode::editTerrainTextureGrid(const WorldspaceHitResult& hit)
{
    CSMDoc::Document& document = getWorldspaceWidget().getDocument();
    CSMWorld::IdTable& landTable
        = dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));

    mCellId = getWorldspaceWidget().getCellId(hit.worldPos);
    if (allowLandTextureEditing(mCellId))
    {
    }

    std::pair<CSMWorld::CellCoordinates, bool> cellCoordinatesPair = CSMWorld::CellCoordinates::fromId(mCellId);

    int cellX = cellCoordinatesPair.first.getX();
    int cellY = cellCoordinatesPair.first.getY();

    // The coordinates of hit in mCellId
    int xHitInCell(float(((hit.worldPos.x() - (cellX * cellSize)) * landTextureSize / cellSize) - 0.25));
    int yHitInCell(float(((hit.worldPos.y() - (cellY * cellSize)) * landTextureSize / cellSize) + 0.25));
    if (xHitInCell < 0)
    {
        xHitInCell = xHitInCell + landTextureSize;
        cellX = cellX - 1;
    }
    if (yHitInCell > 15)
    {
        yHitInCell = yHitInCell - landTextureSize;
        cellY = cellY + 1;
    }

    mCellId = CSMWorld::CellCoordinates::generateId(cellX, cellY);
    if (allowLandTextureEditing(mCellId))
    {
    }

    std::string iteratedCellId;

    int textureColumn = landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandTexturesIndex);

    // All indices are offset by +1
    uint32_t brushInt = document.getData().getLandTextures().getRecord(mBrushTexture).get().mIndex + 1;

    int r = static_cast<float>(mBrushSize) / 2;

    if (mBrushShape == CSVWidget::BrushShape_Point)
    {
        CSMWorld::LandTexturesColumn::DataType newTerrain
            = landTable.data(landTable.getModelIndex(mCellId, textureColumn))
                  .value<CSMWorld::LandTexturesColumn::DataType>();

        if (allowLandTextureEditing(mCellId))
        {
            newTerrain[yHitInCell * landTextureSize + xHitInCell] = brushInt;
            pushEditToCommand(newTerrain, document, landTable, mCellId);
        }
    }

    if (mBrushShape == CSVWidget::BrushShape_Square)
    {
        int upperLeftCellX = cellX - std::floor(r / landTextureSize);
        int upperLeftCellY = cellY - std::floor(r / landTextureSize);
        if (xHitInCell - (r % landTextureSize) < 0)
            upperLeftCellX--;
        if (yHitInCell - (r % landTextureSize) < 0)
            upperLeftCellY--;

        int lowerrightCellX = cellX + std::floor(r / landTextureSize);
        int lowerrightCellY = cellY + std::floor(r / landTextureSize);
        if (xHitInCell + (r % landTextureSize) > landTextureSize - 1)
            lowerrightCellX++;
        if (yHitInCell + (r % landTextureSize) > landTextureSize - 1)
            lowerrightCellY++;

        for (int iCell = upperLeftCellX; iCell <= lowerrightCellX; iCell++)
        {
            for (int jCell = upperLeftCellY; jCell <= lowerrightCellY; jCell++)
            {
                iteratedCellId = CSMWorld::CellCoordinates::generateId(iCell, jCell);
                if (allowLandTextureEditing(iteratedCellId))
                {
                    CSMWorld::LandTexturesColumn::DataType newTerrain
                        = landTable.data(landTable.getModelIndex(iteratedCellId, textureColumn))
                              .value<CSMWorld::LandTexturesColumn::DataType>();
                    for (int i = 0; i < landTextureSize; i++)
                    {
                        for (int j = 0; j < landTextureSize; j++)
                        {

                            if (iCell == cellX && jCell == cellY && abs(i - xHitInCell) < r && abs(j - yHitInCell) < r)
                            {
                                newTerrain[j * landTextureSize + i] = brushInt;
                            }
                            else
                            {
                                int distanceX(0);
                                int distanceY(0);
                                if (iCell < cellX)
                                    distanceX = xHitInCell + landTextureSize * abs(iCell - cellX) - i;
                                if (jCell < cellY)
                                    distanceY = yHitInCell + landTextureSize * abs(jCell - cellY) - j;
                                if (iCell > cellX)
                                    distanceX = -xHitInCell + landTextureSize * abs(iCell - cellX) + i;
                                if (jCell > cellY)
                                    distanceY = -yHitInCell + landTextureSize * abs(jCell - cellY) + j;
                                if (iCell == cellX)
                                    distanceX = abs(i - xHitInCell);
                                if (jCell == cellY)
                                    distanceY = abs(j - yHitInCell);
                                if (distanceX < r && distanceY < r)
                                    newTerrain[j * landTextureSize + i] = brushInt;
                            }
                        }
                    }
                    pushEditToCommand(newTerrain, document, landTable, iteratedCellId);
                }
            }
        }
    }

    if (mBrushShape == CSVWidget::BrushShape_Circle)
    {
        int upperLeftCellX = cellX - std::floor(r / landTextureSize);
        int upperLeftCellY = cellY - std::floor(r / landTextureSize);
        if (xHitInCell - (r % landTextureSize) < 0)
            upperLeftCellX--;
        if (yHitInCell - (r % landTextureSize) < 0)
            upperLeftCellY--;

        int lowerrightCellX = cellX + std::floor(r / landTextureSize);
        int lowerrightCellY = cellY + std::floor(r / landTextureSize);
        if (xHitInCell + (r % landTextureSize) > landTextureSize - 1)
            lowerrightCellX++;
        if (yHitInCell + (r % landTextureSize) > landTextureSize - 1)
            lowerrightCellY++;

        for (int iCell = upperLeftCellX; iCell <= lowerrightCellX; iCell++)
        {
            for (int jCell = upperLeftCellY; jCell <= lowerrightCellY; jCell++)
            {
                iteratedCellId = CSMWorld::CellCoordinates::generateId(iCell, jCell);
                if (allowLandTextureEditing(iteratedCellId))
                {
                    CSMWorld::LandTexturesColumn::DataType newTerrain
                        = landTable.data(landTable.getModelIndex(iteratedCellId, textureColumn))
                              .value<CSMWorld::LandTexturesColumn::DataType>();
                    for (int i = 0; i < landTextureSize; i++)
                    {
                        for (int j = 0; j < landTextureSize; j++)
                        {
                            if (iCell == cellX && jCell == cellY && abs(i - xHitInCell) < r && abs(j - yHitInCell) < r)
                            {
                                int distanceX = abs(i - xHitInCell);
                                int distanceY = abs(j - yHitInCell);
                                float distance = std::round(sqrt(pow(distanceX, 2) + pow(distanceY, 2)));
                                float rf = static_cast<float>(mBrushSize) / 2;
                                if (distance < rf)
                                    newTerrain[j * landTextureSize + i] = brushInt;
                            }
                            else
                            {
                                int distanceX(0);
                                int distanceY(0);
                                if (iCell < cellX)
                                    distanceX = xHitInCell + landTextureSize * abs(iCell - cellX) - i;
                                if (jCell < cellY)
                                    distanceY = yHitInCell + landTextureSize * abs(jCell - cellY) - j;
                                if (iCell > cellX)
                                    distanceX = -xHitInCell + landTextureSize * abs(iCell - cellX) + i;
                                if (jCell > cellY)
                                    distanceY = -yHitInCell + landTextureSize * abs(jCell - cellY) + j;
                                if (iCell == cellX)
                                    distanceX = abs(i - xHitInCell);
                                if (jCell == cellY)
                                    distanceY = abs(j - yHitInCell);
                                float distance = std::round(sqrt(pow(distanceX, 2) + pow(distanceY, 2)));
                                float rf = static_cast<float>(mBrushSize) / 2;
                                if (distance < rf)
                                    newTerrain[j * landTextureSize + i] = brushInt;
                            }
                        }
                    }
                    pushEditToCommand(newTerrain, document, landTable, iteratedCellId);
                }
            }
        }
    }

    if (mBrushShape == CSVWidget::BrushShape_Custom)
    {
        CSMWorld::LandTexturesColumn::DataType newTerrain
            = landTable.data(landTable.getModelIndex(mCellId, textureColumn))
                  .value<CSMWorld::LandTexturesColumn::DataType>();

        if (allowLandTextureEditing(mCellId) && !mCustomBrushShape.empty())
        {
            for (auto const& value : mCustomBrushShape)
            {
                if (yHitInCell + value.second >= 0 && yHitInCell + value.second <= 15 && xHitInCell + value.first >= 0
                    && xHitInCell + value.first <= 15)
                {
                    newTerrain[(yHitInCell + value.second) * landTextureSize + xHitInCell + value.first] = brushInt;
                }
                else
                {
                    int cellXDifference = std::floor(1.0f * (xHitInCell + value.first) / landTextureSize);
                    int cellYDifference = std::floor(1.0f * (yHitInCell + value.second) / landTextureSize);
                    int xInOtherCell = xHitInCell + value.first - cellXDifference * landTextureSize;
                    int yInOtherCell = yHitInCell + value.second - cellYDifference * landTextureSize;

                    std::string cellId
                        = CSMWorld::CellCoordinates::generateId(cellX + cellXDifference, cellY + cellYDifference);
                    if (allowLandTextureEditing(cellId))
                    {
                        CSMWorld::LandTexturesColumn::DataType newTerrainOtherCell
                            = landTable.data(landTable.getModelIndex(cellId, textureColumn))
                                  .value<CSMWorld::LandTexturesColumn::DataType>();
                        newTerrainOtherCell[yInOtherCell * landTextureSize + xInOtherCell] = brushInt;
                        pushEditToCommand(newTerrainOtherCell, document, landTable, std::move(cellId));
                    }
                }
            }
            pushEditToCommand(newTerrain, document, landTable, mCellId);
        }
    }
}

bool CSVRender::TerrainTextureMode::isInCellSelection(int globalSelectionX, int globalSelectionY)
{
    if (CSVRender::PagedWorldspaceWidget* paged
        = dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
    {
        std::pair<int, int> textureCoords = std::make_pair(globalSelectionX, globalSelectionY);
        std::string cellId = CSMWorld::CellCoordinates::textureGlobalToCellId(textureCoords);
        return paged->getCellSelection().has(CSMWorld::CellCoordinates::fromId(cellId).first);
    }
    return false;
}

void CSVRender::TerrainTextureMode::selectTerrainTextures(
    const std::pair<int, int>& texCoords, unsigned char selectMode)
{
    int r = mBrushSize / 2;
    std::vector<std::pair<int, int>> selections;

    if (mBrushShape == CSVWidget::BrushShape_Point)
    {
        if (isInCellSelection(texCoords.first, texCoords.second))
            selections.emplace_back(texCoords);
    }

    if (mBrushShape == CSVWidget::BrushShape_Square)
    {
        for (int i = -r; i <= r; i++)
        {
            for (int j = -r; j <= r; j++)
            {
                int x = i + texCoords.first;
                int y = j + texCoords.second;
                if (isInCellSelection(x, y))
                {
                    selections.emplace_back(x, y);
                }
            }
        }
    }

    if (mBrushShape == CSVWidget::BrushShape_Circle)
    {
        for (int i = -r; i <= r; i++)
        {
            for (int j = -r; j <= r; j++)
            {
                osg::Vec2f coords(i, j);
                float rf = static_cast<float>(mBrushSize) / 2;
                if (std::round(coords.length()) < rf)
                {
                    int x = i + texCoords.first;
                    int y = j + texCoords.second;
                    if (isInCellSelection(x, y))
                    {
                        selections.emplace_back(x, y);
                    }
                }
            }
        }
    }

    if (mBrushShape == CSVWidget::BrushShape_Custom)
    {
        if (!mCustomBrushShape.empty())
        {
            for (auto const& value : mCustomBrushShape)
            {
                int x = texCoords.first + value.first;
                int y = texCoords.second + value.second;
                if (isInCellSelection(x, y))
                {
                    selections.emplace_back(x, y);
                }
            }
        }
    }

    std::string selectAction;

    if (selectMode == 0)
        selectAction = CSMPrefs::get()["3D Scene Editing"]["primary-select-action"].toString();
    else
        selectAction = CSMPrefs::get()["3D Scene Editing"]["secondary-select-action"].toString();

    if (selectAction == "Select only")
        mTerrainTextureSelection->onlySelect(selections);
    else if (selectAction == "Add to selection")
        mTerrainTextureSelection->addSelect(selections);
    else if (selectAction == "Remove from selection")
        mTerrainTextureSelection->removeSelect(selections);
    else if (selectAction == "Invert selection")
        mTerrainTextureSelection->toggleSelect(selections);
}

void CSVRender::TerrainTextureMode::pushEditToCommand(CSMWorld::LandTexturesColumn::DataType& newLandGrid,
    CSMDoc::Document& document, CSMWorld::IdTable& landTable, std::string cellId)
{
    CSMWorld::IdTable& ltexTable
        = dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_LandTextures));

    QVariant changedLand;
    changedLand.setValue(newLandGrid);

    QModelIndex index(
        landTable.getModelIndex(cellId, landTable.findColumnIndex(CSMWorld::Columns::ColumnId_LandTexturesIndex)));

    QUndoStack& undoStack = document.getUndoStack();
    undoStack.push(new CSMWorld::ModifyCommand(landTable, index, changedLand));
    undoStack.push(new CSMWorld::TouchLandCommand(landTable, ltexTable, cellId));
}

bool CSVRender::TerrainTextureMode::allowLandTextureEditing(const std::string& cellId)
{
    CSMDoc::Document& document = getWorldspaceWidget().getDocument();
    CSMWorld::IdTable& landTable
        = dynamic_cast<CSMWorld::IdTable&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Land));
    CSMWorld::IdTree& cellTable
        = dynamic_cast<CSMWorld::IdTree&>(*document.getData().getTableModel(CSMWorld::UniversalId::Type_Cells));

    const ESM::RefId cellRefId = ESM::RefId::stringRefId(cellId);
    const bool noCell = document.getData().getCells().searchId(cellRefId) == -1;
    const bool noLand = document.getData().getLand().searchId(cellRefId) == -1;

    if (noCell)
    {
        std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-landedit"].toString();

        // target cell does not exist
        if (mode == "Discard")
            return false;

        if (mode == "Create cell and land, then edit")
        {
            auto createCommand = std::make_unique<CSMWorld::CreateCommand>(cellTable, cellId);
            int parentIndex = cellTable.findColumnIndex(CSMWorld::Columns::ColumnId_Cell);
            int index = cellTable.findNestedColumnIndex(parentIndex, CSMWorld::Columns::ColumnId_Interior);
            createCommand->addNestedValue(parentIndex, index, false);
            document.getUndoStack().push(createCommand.release());

            if (CSVRender::PagedWorldspaceWidget* paged
                = dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
            {
                CSMWorld::CellSelection selection = paged->getCellSelection();
                selection.add(CSMWorld::CellCoordinates::fromId(cellId).first);
                paged->setCellSelection(selection);
            }
        }
    }
    else if (CSVRender::PagedWorldspaceWidget* paged
        = dynamic_cast<CSVRender::PagedWorldspaceWidget*>(&getWorldspaceWidget()))
    {
        CSMWorld::CellSelection selection = paged->getCellSelection();
        if (!selection.has(CSMWorld::CellCoordinates::fromId(cellId).first))
        {
            // target cell exists, but is not shown
            std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-visible-landedit"].toString();

            if (mode == "Discard")
                return false;

            if (mode == "Show cell and edit")
            {
                selection.add(CSMWorld::CellCoordinates::fromId(cellId).first);
                paged->setCellSelection(selection);
            }
        }
    }

    if (noLand)
    {
        std::string mode = CSMPrefs::get()["3D Scene Editing"]["outside-landedit"].toString();

        // target cell does not exist
        if (mode == "Discard")
            return false;

        if (mode == "Create cell and land, then edit")
        {
            document.getUndoStack().push(new CSMWorld::CreateCommand(landTable, cellId));
        }
    }

    return true;
}

void CSVRender::TerrainTextureMode::dragMoveEvent(QDragMoveEvent* event) {}

void CSVRender::TerrainTextureMode::mouseMoveEvent(QMouseEvent* event)
{
    WorldspaceHitResult hit = getWorldspaceWidget().mousePick(event->position().toPoint(), getInteractionMask());
    if (hit.hit && mBrushDraw)
        mBrushDraw->update(hit.worldPos, mBrushSize, mBrushShape);
    if (!hit.hit && mBrushDraw)
        mBrushDraw->hide();
}

std::shared_ptr<CSVRender::TerrainSelection> CSVRender::TerrainTextureMode::getTerrainSelection()
{
    return mTerrainTextureSelection;
}

void CSVRender::TerrainTextureMode::setBrushSize(int brushSize)
{
    mBrushSize = brushSize;
}

void CSVRender::TerrainTextureMode::setBrushShape(CSVWidget::BrushShape brushShape)
{
    mBrushShape = brushShape;

    // Set custom brush shape
    if (mBrushShape == CSVWidget::BrushShape_Custom && !mTerrainTextureSelection->getTerrainSelection().empty())
    {
        auto terrainSelection = mTerrainTextureSelection->getTerrainSelection();
        int selectionCenterX = 0;
        int selectionCenterY = 0;
        int selectionAmount = 0;

        for (auto const& value : terrainSelection)
        {
            selectionCenterX += value.first;
            selectionCenterY += value.second;
            ++selectionAmount;
        }

        if (selectionAmount != 0)
        {
            selectionCenterX /= selectionAmount;
            selectionCenterY /= selectionAmount;
        }

        mCustomBrushShape.clear();
        for (auto const& value : terrainSelection)
            mCustomBrushShape.emplace_back(value.first - selectionCenterX, value.second - selectionCenterY);
    }
}

void CSVRender::TerrainTextureMode::setBrushTexture(ESM::RefId brushTexture)
{
    mBrushTexture = brushTexture;
}