| 1 | // This file is part of Dust Racing 2D. |
| 2 | // Copyright (C) 2018 Jussi Lind <[email protected]> |
| 3 | // |
| 4 | // Dust Racing 2D is free software: you can redistribute it and/or modify |
| 5 | // it under the terms of the GNU General Public License as published by |
| 6 | // the Free Software Foundation, either version 3 of the License, or |
| 7 | // (at your option) any later version. |
| 8 | // Dust Racing 2D is distributed in the hope that it will be useful, |
| 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | // GNU General Public License for more details. |
| 12 | // |
| 13 | // You should have received a copy of the GNU General Public License |
| 14 | // along with Dust Racing 2D. If not, see <http://www.gnu.org/licenses/>. |
| 15 | |
| 16 | #include "floodfill.hpp" |
| 17 | #include "map.hpp" |
| 18 | #include "tracktile.hpp" |
| 19 | |
| 20 | #include <deque> |
| 21 | |
| 22 | #include <QAction> |
| 23 | |
| 24 | namespace FloodFill { |
| 25 | void setTileType(TrackTile & tile, QAction * action) |
| 26 | { |
| 27 | tile.setTileType(action->data().toString()); |
| 28 | tile.setPixmap(action->icon().pixmap(TrackTile::width(), TrackTile::height())); |
| 29 | } |
| 30 | } // namespace FloodFill |
| 31 | |
| 32 | void FloodFill::floodFill(TrackTile & tile, QAction * action, const QString & typeToFill, MapBase & map) |
| 33 | { |
| 34 | // Coordinates of neighbor tiles can be calculated by adding these offsets to tile coordinates. |
| 35 | const size_t directionCount = 4; |
| 36 | const QPoint neighborOffsets[directionCount] = { |
| 37 | { 1, 0 }, // right |
| 38 | { 0, -1 }, // up |
| 39 | { -1, 0 }, // left |
| 40 | { 0, 1 } // down |
| 41 | }; |
| 42 | |
| 43 | std::deque<QPoint> stack; |
| 44 | stack.push_back(tile.matrixLocation()); |
| 45 | while (stack.size()) |
| 46 | { |
| 47 | const auto location = stack.back(); |
| 48 | if (const auto tile = std::dynamic_pointer_cast<TrackTile>(map.getTile(location.x(), location.y()))) |
| 49 | { |
| 50 | setTileType(*tile, action); |
| 51 | } |
| 52 | stack.pop_back(); |
| 53 | |
| 54 | for (size_t i = 0; i < directionCount; ++i) |
| 55 | { |
| 56 | const int x = location.x() + neighborOffsets[i].x(); |
| 57 | const int y = location.y() + neighborOffsets[i].y(); |
| 58 | if (x >= 0 && y >= 0 && x < static_cast<int>(map.cols()) && y < static_cast<int>(map.rows())) |
| 59 | { |
| 60 | if (const auto tile = std::dynamic_pointer_cast<TrackTile>(map.getTile(x, y)); tile && tile->tileType() == typeToFill) |
| 61 | { |
| 62 | stack.push_back({ x, y }); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | } |