Added debug prints for tile amount (currently disabled)
[situare] / src / map / mapengine.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5        Sami Rämö - sami.ramo@ixonos.com
6        Jussi Laitinen - jussi.laitinen@ixonos.com
7        Pekka Nissinen - pekka.nissinen@ixonos.com
8
9    Situare is free software; you can redistribute it and/or
10    modify it under the terms of the GNU General Public License
11    version 2 as published by the Free Software Foundation.
12
13    Situare is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with Situare; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
21    USA.
22 */
23
24 #include <QDebug>
25 #include <QString>
26 #include <QStringList>
27 #include <QUrl>
28 #include <QHash>
29 #include <QHashIterator>
30 #include <QRect>
31
32 #include "mapengine.h"
33 #include "maptile.h"
34
35 MapEngine::MapEngine(QObject *parent)
36     : QObject(parent)
37     , m_centerTile(QPoint(UNDEFINED, UNDEFINED))
38     , m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
39     , m_zoomLevel(DEFAULT_ZOOM_LEVEL)
40 {
41     m_mapScene = new MapScene(this);
42
43     m_mapFetcher = new MapFetcher(new QNetworkAccessManager(this), this);
44     connect(this, SIGNAL(fetchImage(QUrl)), m_mapFetcher, SLOT(fetchMapImage(QUrl)));
45     connect(m_mapFetcher, SIGNAL(mapImageReceived(QUrl,QPixmap)), this,
46             SLOT(mapImageReceived(QUrl, QPixmap)));
47
48     m_mapZoomPanel = new MapZoomPanel(NULL, MAP_ZOOM_PANEL_POSITION_X, MAP_ZOOM_PANEL_POSITION_Y);
49     m_mapScene->addItem(m_mapZoomPanel);
50     connect(m_mapZoomPanel, SIGNAL(zoomInPressed()), this, SLOT(zoomIn()));
51     connect(m_mapZoomPanel, SIGNAL(zoomOutPressed()), this, SLOT(zoomOut()));
52 }
53
54 void MapEngine::init()
55 {
56     emit zoomLevelChanged(m_zoomLevel);
57     setViewLocation(QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE));
58 }
59
60 void MapEngine::setViewLocation(QPointF latLonCoordinate)
61 {
62     qDebug() << __PRETTY_FUNCTION__;
63     setLocation(convertLatLonToSceneCoordinate(latLonCoordinate));
64 }
65
66 QUrl MapEngine::buildURL(int zoomLevel, QPoint tileNumbers)
67 {
68     QString url = QString("http://tile.openstreetmap.org/mapnik/%1/%2/%3.png")
69                   .arg(zoomLevel).arg(tileNumbers.x()).arg(tileNumbers.y());
70
71     return QUrl(url);
72 }
73
74 void MapEngine::parseURL(const QUrl &url, int &zoom, int &x, int &y)
75 {
76     QString path = url.path();
77     QStringList pathParts = path.split("/", QString::SkipEmptyParts);
78
79     int size = pathParts.size();
80
81     if (size >= 3) {
82         zoom = (pathParts.at(size-3)).toInt();
83         x = (pathParts.at(size-2)).toInt();
84         QString yString = pathParts.at(size-1);
85         yString.chop(4);
86         y = yString.toInt();
87     }
88 }
89
90 void MapEngine::mapImageReceived(const QUrl &url, const QPixmap &pixmap)
91 {
92     //qDebug() << __PRETTY_FUNCTION__;
93
94     int zoom = UNDEFINED;
95     int x = UNDEFINED;
96     int y = UNDEFINED;
97
98     parseURL(url, zoom, x, y);
99     QString hashKey = tilePath(zoom, x, y);
100     if (!m_mapScene->isTileInScene(hashKey)) {
101
102         MapTile *mapTile = new MapTile();
103         mapTile->setZoomLevel(zoom);
104         mapTile->setTileNumber(QPoint(x, y));
105         mapTile->setPixmap(pixmap);
106
107         m_mapScene->addTile(mapTile, hashKey);
108
109         m_mapScene->debugItemsCount();
110
111         m_mapScene->removeStackedTiles(mapTile, viewRect());
112    }
113 }
114
115 QGraphicsScene* MapEngine::scene()
116 {
117     return dynamic_cast<QGraphicsScene *>(m_mapScene);
118 }
119
120 int MapEngine::tileMaxValue(int zoomLevel)
121 {
122     return (1 << zoomLevel) - 1;
123 }
124
125 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
126 {
127     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
128     int gridWidth = (m_viewSize.width()/TILE_SIZE_X + 1) + (GRID_PADDING*2);
129     int gridHeight = (m_viewSize.height()/TILE_SIZE_Y + 1) + (GRID_PADDING*2);
130     int topLeftX = tileCoordinate.x() - (gridWidth/2);
131     int topLeftY = tileCoordinate.y() - (gridHeight/2);
132
133     return QRect(topLeftX, topLeftY, gridWidth, gridHeight);
134 }
135
136 void MapEngine::alignImmovableItems(QPoint viewTopLeft)
137 {
138     m_mapZoomPanel->setPos(viewTopLeft);
139
140 //    qDebug() << __PRETTY_FUNCTION__ << "viewTopLeft:" << viewTopLeft;
141 }
142
143 void MapEngine::setLocation(QPoint sceneCoordinate)
144 {
145 //    qDebug() << __PRETTY_FUNCTION__;
146
147     m_sceneCoordinate = sceneCoordinate;
148     emit locationChanged(m_sceneCoordinate);
149
150     if (isCenterTileChanged(sceneCoordinate)) {
151         getTiles(sceneCoordinate);
152         m_mapScene->removeOutOfViewTiles(viewRect());
153     }
154 }
155
156 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
157 {
158     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
159     QPoint temp = m_centerTile;
160     m_centerTile = centerTile;
161
162     return (centerTile != temp);
163 }
164
165 void MapEngine::getTiles(QPoint sceneCoordinate)
166 {
167 //    qDebug() << __PRETTY_FUNCTION__;
168
169     m_viewGrid = calculateTileGrid(sceneCoordinate);
170
171     int topLeftX = m_viewGrid.topLeft().x();
172     int topLeftY = m_viewGrid.topLeft().y();
173     int bottomRightX = m_viewGrid.bottomRight().x();
174     int bottomRightY = m_viewGrid.bottomRight().y();
175
176     int tileMaxVal = tileMaxValue(m_zoomLevel);
177
178     for (int x = topLeftX; x <= bottomRightX; ++x) {
179         for (int y = topLeftY; y <= bottomRightY; ++y) {
180
181             int tileX = x;
182             int tileY = y;
183
184             if (tileX < 0)
185                 tileX += tileMaxVal;
186             else if (tileX > tileMaxVal)
187                 tileX -= tileMaxVal;
188
189             if (tileY < 0)
190                 tileY += tileMaxVal;
191             else if (tileY > tileMaxVal)
192                 tileY -= tileMaxVal;
193
194             QUrl url = buildURL(m_zoomLevel, QPoint(tileX, tileY));
195
196             if (!m_mapScene->isTileInScene(tilePath(m_zoomLevel, tileX, tileY)))
197                 emit fetchImage(url);
198         }
199     }
200 }
201
202 QRect MapEngine::viewRect()
203 {
204     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewGrid.topLeft());
205     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewGrid.bottomRight()
206                                                              + QPoint(1, 1));
207     return QRect(topLeft, bottomRight);
208 }
209
210 void MapEngine::viewResized(const QSize &size)
211 {
212     m_viewSize = size;
213     getTiles(m_sceneCoordinate);
214     m_mapScene->removeOutOfViewTiles(viewRect());
215 }
216
217 void MapEngine::viewZoomInFinished()
218 {
219     qDebug() << __PRETTY_FUNCTION__;
220     m_mapScene->removeOutOfViewTiles(viewRect());
221 }
222
223 void MapEngine::zoomIn()
224 {
225 //    qDebug() << __PRETTY_FUNCTION__;
226
227     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
228         m_zoomLevel++;
229         emit zoomLevelChanged(m_zoomLevel);
230
231         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
232
233         getTiles(m_sceneCoordinate);
234     }
235 }
236
237 void MapEngine::zoomOut()
238 {
239 //    qDebug() << __PRETTY_FUNCTION__;
240
241     if (m_zoomLevel > MIN_MAP_ZOOM_LEVEL) {
242         m_zoomLevel--;
243         emit zoomLevelChanged(m_zoomLevel);
244
245         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
246
247         getTiles(m_sceneCoordinate);
248     }
249 }
250
251 QString MapEngine::tilePath(int zoomLevel, int x, int y)
252 {
253     QString tilePathString(QString::number(zoomLevel) + "/");
254     tilePathString.append(QString::number(x) + "/");
255     tilePathString.append(QString::number(y));
256
257     return tilePathString;
258 }
259
260 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
261 {
262     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
263     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X*pow));
264     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y*pow));
265
266     return QPoint(x, y);
267 }
268
269 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
270 {
271     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
272     int x = tileNumber.x() * TILE_SIZE_X * pow;
273     int y = tileNumber.y() * TILE_SIZE_Y * pow;
274
275     return QPoint(x, y);
276 }
277
278 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
279 {
280 //    qDebug() << __PRETTY_FUNCTION__;
281
282     qreal longitude = latLonCoordinate.x();
283     qreal latitude = latLonCoordinate.y();
284
285     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
286         return QPoint(UNDEFINED, UNDEFINED);
287     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
288         return QPoint(UNDEFINED, UNDEFINED);
289
290     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
291
292     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
293     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
294                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
295
296     return QPointF(x*z*TILE_SIZE_X, y*z*TILE_SIZE_Y).toPoint();
297 }