aboutsummaryrefslogtreecommitdiff
path: root/Source/MapEditor/mainwindow.cpp
blob: e641a4d6d6e1e89cbe948b34f2c33f31b589c728 (plain) (blame)
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
#include "mainwindow.h"
#include <QPainter>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QInputDialog>
#include <QMessageBox>
#include <QShortcut>

#define DEFAULT_AIRPORT_NAME    QByteArray("Default Airport\0")

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    level_size(0),
    selected_item(-1),
    tileSet(tr("Space"), this),
    tileMoveUp(tr("Up"), this)
{
    ui.setupUi(this);
    this->setWindowTitle(APP_FULL_NAME);

    connect(ui.LoadMap_Btn,            SIGNAL(released()),                 this,   SLOT(loadMap()));
    connect(ui.CreateMap_Btn,          SIGNAL(released()),                 this,   SLOT(onCreateMap()));
    connect(ui.saveMap_Btn,            SIGNAL(released()),                 this,   SLOT(onSaveMap(void)));
    connect(ui.showNumbers_Checkbox,   SIGNAL(stateChanged(int)),          this,   SLOT(onShowNumbers(int)));
    connect(ui.airportName_Label,      SIGNAL(textChanged(QString)),       this,   SLOT(onAirportNameModified(QString)));

    connect(&gscene, SIGNAL(positionClicked(QPointF)),   this,   SLOT(onMapItemClicked(QPointF)));
    connect(&gscene, SIGNAL(noItemSelected(void)),       this,   SLOT(onNoItemSelected(void)));
    connect(&gscene, SIGNAL(updateSelectedItem(void)),   this,   SLOT(onListItemSelected(void)));

    // Configure keyboard shortcuts.
    connect(&tileSet, SIGNAL(activated()), this, SLOT(onListItemSelected(void)));
    connect(&tileMoveUp, SIGNAL(activated(void)), this, SLOT(moveUp(void)));

    appSettings();
    loadTilesetData();
    loadBuildingData();
}

MainWindow::~MainWindow()
{
    foreach (QGraphicsTextItem* it, textItems)
    {
        if (it != nullptr)
        {
            delete it;
        }
    }
}

void MainWindow::loadBuildingData(void)
{
    const QString filePath = "./buildings.ini";

    QFile f(filePath);

    if (f.open(QFile::ReadOnly))
    {

    }
    else
    {
        showError(tr("Could not open file ") + filePath);
    }
}

void MainWindow::onShowNumbers(int)
{
    processMapFile(map_buffer);
}

void MainWindow::onMapItemClicked(QPointF pos)
{
    QPoint realPos;

    pos.setX(pos.x() - (TILE_SIZE / 2));

    realPos.setX(static_cast<int>(pos.x() + (pos.y() * 2)));
    realPos.setY(static_cast<int>((pos.y() * 2) - pos.x()));

    int tile_no = 0;

    tile_no = realPos.x() / TILE_SIZE;
    tile_no += (realPos.y() / TILE_SIZE) * level_size;

    if (tile_no < (level_size * level_size))
    {
        selected_item = tile_no;
        processMapFile(map_buffer);
    }
    else
    {
        selected_item = -1;
    }
}

void MainWindow::onListItemSelected(void)
{
    foreach (const QListWidgetItem* const it, ui.tileList->selectedItems())
    {
        if (it != nullptr)
        {
            if (selected_item != -1)
            {
                const int map_buffer_pos = static_cast<int>((DATA_HEADER_SIZE + 1)
                                            + (static_cast<unsigned long>(selected_item) * sizeof(quint16)));
                //map_buffer_pos++; // MSB: building data, LSB: terrain data.

                if (map_buffer_pos < map_buffer.count())
                {
                    const char row = static_cast<char>(ui.tileList->row(it));

                    map_buffer[map_buffer_pos] = row;

                    if (ui.mirror_CheckBox->isChecked() )
                    {
                        map_buffer[map_buffer_pos] = map_buffer[map_buffer_pos] | TILE_MIRROR_FLAG;
                    }

                    processMapFile(map_buffer);
                }
            }
        }
    }
}

void MainWindow::onSaveMap(void)
{
    const QString path = QFileDialog::getSaveFileName(this,
                                                      "Save map file",
                                                      _last_dir,
                                                      "Map files (*.LVL)");

    QFile f(path);

    if (checkFile(f, QFile::WriteOnly) == false)
    {
        return;
    }

    f.write(map_buffer);

    f.close();
}

void MainWindow::onNoItemSelected(void)
{
    selected_item = -1;
    processMapFile(map_buffer);
}

void MainWindow::onCreateMap(void)
{
    bool ok;
    QStringList items;

    items << "8";
    items << "16";
    items << "24";

    const QString strSize = QInputDialog::getItem(this,
                                                  tr("Create new map"),
                                                  tr("Select map size:"),
                                                  items,
                                                  0,
                                                  false,
                                                  &ok     );

    if (ok && (not strSize.isEmpty()))
    {
        QByteArray data;

        data.append("ATC");

        const quint8 size = static_cast<quint8>(strSize.toInt(&ok));

        if (ok)
        {
            switch (size)
            {
                case 8:
                    // Fall through.
                case 16:
                    // Fall through.
                case 24:
                    level_size = size;
                    data.append(static_cast<char>(size));
                break;

                default:
                    showError(tr("Invalid map size ") + strSize);
                break;
            }

            data.append(DEFAULT_AIRPORT_NAME);

            for (int i = 0x04 + DEFAULT_AIRPORT_NAME.count(); i < 0x1C; i++)
            {
                data.append('\0');
            }

            for (int i = (data.count() - 1); i < DATA_HEADER_SIZE; i++)
            {
                data.append(static_cast<char>(0xFF));
            }

            for (quint8 i = 0; i < size; i++)
            {
                for (quint8 j = 0; j < size; j++)
                {
                    data.append(static_cast<char>(0)); // Building data
                    data.append(static_cast<char>(0)); // Terrain data
                }
            }

            processMapFile(data);
        }
    }
}

void MainWindow::loadMap(void)
{
    const QString path = QFileDialog::getOpenFileName(this,
                                                      "Open map file",
                                                      _last_dir,
                                                      "Map files (*.LVL)");

    QFile f(path);

    if (checkFile(f))
    {   
        processMapFile(f.readAll());
    }
}

void MainWindow::processMapFile(const QByteArray& data)
{
    map_buffer = data;

    QDataStream ds(data);

    char header[3];

    ds.readRawData(header, 3);

    if (strncmp(header, "ATC", 3) == 0)
    {
        char ch;

        ds.readRawData(&ch, sizeof(char));

        level_size = ch;

        if (not tilesetPaths[0].isEmpty()
                    &&
            not tilesetPaths[1].isEmpty())
        {
            QPixmap tile1(tilesetPaths[0]);
            QPixmap tile2(tilesetPaths[1]);

            const int expected_filesize = (DATA_HEADER_SIZE + (level_size * level_size));

            if (data.count() >= expected_filesize)
            {
                parseMapData(ds, tile1, tile2);
            }
            else
            {
                showError(tr("Invalid file size. Expected ")
                          + QString::number(expected_filesize, 10));
            }
        }
    }
    else
    {
        showError(tr("Invalid header") + "\"" + header + "\"");
    }
}

void MainWindow::parseMapData(QDataStream& ds, const QPixmap& tileSet, const QPixmap& tileSet2)
{
    char airportName[0x1A];

    ds.readRawData(airportName, sizeof(airportName) / sizeof(airportName[0]));

    ui.airportName_Label->setText(QString(airportName));

    ds.skipRawData(0x3B - 0x1A);

    gscene.clear();
    gscene.clearFocus();

    for (int j = 0; j < level_size; j++)
    {
        for (int i = 0; i < level_size; i++)
        {
            enum
            {
                TILE_GRASS = 0,
                TILE_ASPHALT_WITH_BORDERS,
                TILE_WATER,
                TILE_ASPHALT,

                TILE_RWY_MID,
                TILE_RWY_START_1,
                TILE_RWY_START_2,
                TILE_PARKING,

                TILE_PARKING_2,
                TILE_TAXIWAY_INTERSECT_GRASS,
                TILE_TAXIWAY_GRASS,
                TILE_TAXIWAY_CORNER_GRASS,

                TILE_HALF_WATER_1,
                TILE_HALF_WATER_2,
                TILE_RWY_HOLDING_POINT,
                TILE_RWY_HOLDING_POINT_2,

                TILE_RWY_EXIT,
                TILE_TAXIWAY_CORNER_GRASS_2,
                TILE_TAXIWAY_4WAY_CROSSING,
                TILE_RWY_EXIT_2,

                LAST_TILE_TILESET1 = TILE_RWY_EXIT_2,

                TILE_UNUSED_1,
                TILE_TAXIWAY_CORNER_GRASS_3,

                FIRST_TILE_TILESET2 = TILE_UNUSED_1,
                LAST_TILE_TILESET2 = TILE_TAXIWAY_CORNER_GRASS_3
            };

            int u;
            int v;
            char byte[2];
            ds.readRawData(byte, 2);
            quint8 CurrentTile = static_cast<quint8>(byte[1]);
            quint8 CurrentBuilding = static_cast<quint8>(byte[0]);
            quint8 buildingNoMirror = CurrentBuilding & 0x7F;
            quint8 tileNoMirror = CurrentTile & 0x7F;
            const QPixmap* p = nullptr;

            if (tileNoMirror <= LAST_TILE_TILESET1)
            {
                p = &tileSet;
            }
            else if (tileNoMirror <= LAST_TILE_TILESET2)
            {
                p = &tileSet2;
                CurrentTile -= FIRST_TILE_TILESET2;
                tileNoMirror -= FIRST_TILE_TILESET2;
            }

            if (p != nullptr)
            {
                if (CurrentTile & TILE_MIRROR_FLAG)
                {
                    u = static_cast<int>((tileNoMirror % 4) * 64);
                    v = static_cast<int>((tileNoMirror / 4) * 48);
                }
                else
                {
                    u = static_cast<int>((CurrentTile % 4) * 64);
                    v = static_cast<int>((CurrentTile / 4) * 48);
                }

                QImage cropped = p->copy(u, v, 64, 48).toImage();

                if (CurrentTile & TILE_MIRROR_FLAG)
                {
                    cropped = cropped.mirrored(true, false);
                }

                bool selected = false;

                if (selected_item != -1)
                {
                    if (selected_item == ((j * level_size) + i))
                    {
                        selected = true;
                    }
                }

                cropped = cropped.convertToFormat(QImage::Format_ARGB32); // or maybe other format

                for (int i = 0; i < cropped.width(); i++)
                {
                    for (int j = 0; j < cropped.height(); j++)
                    {
                        QColor rgb = cropped.pixel(i, j);

                        if (rgb == QColor(Qt::magenta))
                        {
                            cropped.setPixel(i, j, qRgba(0,0,0,0));
                        }
                        else if (selected )
                        {
                            QColor c = cropped.pixelColor(i, j);

                            c.setRed(255 - c.red());
                            c.setBlue(255 - c.blue());
                            c.setGreen(255 - c.green());

                            cropped.setPixel(i, j, qRgb(c.red(), c.green(), c.blue()));
                        }
                    }
                }

                QGraphicsPixmapItem* const it = gscene.addPixmap(QPixmap::fromImage(cropped));

                if (it != nullptr)
                {
                    const int x = ((i * TILE_SIZE) - (i * (TILE_SIZE / 2))) - (j * (TILE_SIZE / 2));
                    const int y = (j * (TILE_SIZE / 4)) + (i * (TILE_SIZE / 4));

                    it->setX(x);
                    it->setY(y);

                    if (ui.showNumbers_Checkbox->isChecked() )
                    {
                        QGraphicsTextItem* const io = new QGraphicsTextItem();

                        if (io != nullptr)
                        {
                            io->setPos(x + (TILE_SIZE / 4), y);
                            io->setPlainText(QString::number(i + (j * level_size)));

                            gscene.addItem(io);

                            /* Append pointer to the list so it can be
                             * safely removed on the constructor. */
                            textItems.append(io);
                        }
                    }
                }
            }
        }
    }

    ui.graphicsView->setScene(&gscene);
    ui.graphicsView->show();
}

bool MainWindow::checkFile(QFile& f, QFile::OpenModeFlag flags)
{
    const QFileInfo fi(f);

    if (not f.open(flags))
    {
        return false;
    }

    QDir d(fi.absoluteFilePath());

    _last_dir = d.absolutePath();

    return true;
}

void MainWindow::appSettings(void)
{
    QSettings settings("./settings.ini", QSettings::IniFormat);

    settings.beginGroup("app_settings");

    _last_dir = settings.value("last_dir").toString();

    restoreGeometry(settings.value("window_geometry").toByteArray());

    settings.endGroup();
}

void MainWindow::closeEvent(QCloseEvent*)
{
    QSettings settings("./settings.ini", QSettings::IniFormat);

    settings.beginGroup("app_settings");

    settings.setValue("last_dir", _last_dir);
    settings.setValue("window_geometry", saveGeometry());

    settings.endGroup();
}

void MainWindow::loadTilesetData(void)
{
    const QString filePath = "./tileset.ini";

    QFile f(filePath);

    if (f.exists())
    {
        QSettings tilesetFile("./tileset.ini", QSettings::IniFormat);
        QStringList tilesets_to_check;

        tilesets_to_check << "tileset1";
        tilesets_to_check << "tileset2";

        int j = 0;
        int i = 0;

        foreach (QString tileset, tilesets_to_check)
        {
            tilesetFile.beginGroup(tileset);

            tilesetPaths[j++] = tilesetFile.value("path").toString();

            while (1)
            {
                QString tileNumber = "tile" + QString::number(i);
                QString tileName = tilesetFile.value(tileNumber, "").toString();

                if (tileName.isEmpty() )
                {
                    break;
                }

                tilesetData.insert(i++, tileName);
                ui.tileList->addItem(tileName);
            }

            tilesetFile.endGroup();
        }
    }
    else
    {
        showError(tr("Could not find tile data file ") + filePath);
    }
}

void MainWindow::onAirportNameModified(QString name)
{
    if (map_buffer.isEmpty() )
    {
        return;
    }

    for (int i = 0x04, j = 0; i < 0x1C; i++)
    {
        if (j < name.count() )
        {
            map_buffer[i] = name.at(j++).toLatin1();
        }
        else
        {
            map_buffer[i] = '\0';
        }
    }
}

void MainWindow::moveUp(void)
{

}

void MainWindow::showError(const QString& error)
{
    QMessageBox::critical(this, APP_FULL_NAME, error);
}