QGIS API Documentation  2.99.0-Master (01468d0)
qgsrasterlayerrenderer.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsrasterlayerrenderer.cpp
3  --------------------------------------
4  Date : December 2013
5  Copyright : (C) 2013 by Martin Dobias
6  Email : wonder dot sk at gmail dot com
7  ***************************************************************************
8  * *
9  * This program is free software; you can redistribute it and/or modify *
10  * it under the terms of the GNU General Public License as published by *
11  * the Free Software Foundation; either version 2 of the License, or *
12  * (at your option) any later version. *
13  * *
14  ***************************************************************************/
15 
16 #include "qgsrasterlayerrenderer.h"
17 
18 #include "qgsmessagelog.h"
19 #include "qgsrasterdataprovider.h"
20 #include "qgsrasterdrawer.h"
21 #include "qgsrasteriterator.h"
22 #include "qgsrasterlayer.h"
23 #include "qgsrasterprojector.h"
24 #include "qgsrendercontext.h"
25 #include "qgsproject.h"
26 #include "qgsexception.h"
27 
28 
30 
31 QgsRasterLayerRendererFeedback::QgsRasterLayerRendererFeedback( QgsRasterLayerRenderer *r )
33  , mR( r )
34  , mMinimalPreviewInterval( 250 )
35 {
36  setRenderPartialOutput( r->mContext.testFlag( QgsRenderContext::RenderPartialOutput ) );
37 }
38 
39 void QgsRasterLayerRendererFeedback::onNewData()
40 {
41  if ( !renderPartialOutput() )
42  return; // we were not asked for partial renders and we may not have a temporary image for overwriting...
43 
44  // update only once upon a time
45  // (preview itself takes some time)
46  if ( mLastPreview.isValid() && mLastPreview.msecsTo( QTime::currentTime() ) < mMinimalPreviewInterval )
47  return;
48 
49  // TODO: update only the area that got new data
50 
51  QgsDebugMsg( QString( "new raster preview! %1" ).arg( mLastPreview.msecsTo( QTime::currentTime() ) ) );
52  QTime t;
53  t.start();
54  QgsRasterBlockFeedback feedback;
55  feedback.setPreviewOnly( true );
56  feedback.setRenderPartialOutput( true );
57  QgsRasterIterator iterator( mR->mPipe->last() );
58  QgsRasterDrawer drawer( &iterator );
59  drawer.draw( mR->mPainter, mR->mRasterViewPort, mR->mMapToPixel, &feedback );
60  QgsDebugMsg( QString( "total raster preview time: %1 ms" ).arg( t.elapsed() ) );
61  mLastPreview = QTime::currentTime();
62 }
63 
67  : QgsMapLayerRenderer( layer->id() )
68  , mContext( rendererContext )
69  , mFeedback( new QgsRasterLayerRendererFeedback( this ) )
70 {
71  mPainter = rendererContext.painter();
72  const QgsMapToPixel &qgsMapToPixel = rendererContext.mapToPixel();
73  mMapToPixel = &qgsMapToPixel;
74 
75  QgsMapToPixel mapToPixel = qgsMapToPixel;
76  if ( mapToPixel.mapRotation() )
77  {
78  // unset rotation for the sake of local computations.
79  // Rotation will be handled by QPainter later
80  // TODO: provide a method of QgsMapToPixel to fetch map center
81  // in geographical units
82  QgsPointXY center = mapToPixel.toMapCoordinates(
83  mapToPixel.mapWidth() / 2.0,
84  mapToPixel.mapHeight() / 2.0
85  );
86  mapToPixel.setMapRotation( 0, center.x(), center.y() );
87  }
88 
89  QgsRectangle myProjectedViewExtent;
90  QgsRectangle myProjectedLayerExtent;
91 
92  if ( rendererContext.coordinateTransform().isValid() )
93  {
94  QgsDebugMsgLevel( "coordinateTransform set -> project extents.", 4 );
95  try
96  {
97  myProjectedViewExtent = rendererContext.coordinateTransform().transformBoundingBox( rendererContext.extent() );
98  }
99  catch ( QgsCsException &cs )
100  {
101  QgsMessageLog::logMessage( QObject::tr( "Could not reproject view extent: %1" ).arg( cs.what() ), QObject::tr( "Raster" ) );
102  myProjectedViewExtent.setMinimal();
103  }
104 
105  try
106  {
107  myProjectedLayerExtent = rendererContext.coordinateTransform().transformBoundingBox( layer->extent() );
108  }
109  catch ( QgsCsException &cs )
110  {
111  QgsMessageLog::logMessage( QObject::tr( "Could not reproject layer extent: %1" ).arg( cs.what() ), QObject::tr( "Raster" ) );
112  myProjectedLayerExtent.setMinimal();
113  }
114  }
115  else
116  {
117  QgsDebugMsgLevel( "coordinateTransform not set", 4 );
118  myProjectedViewExtent = rendererContext.extent();
119  myProjectedLayerExtent = layer->extent();
120  }
121 
122  // clip raster extent to view extent
123  QgsRectangle myRasterExtent = myProjectedViewExtent.intersect( &myProjectedLayerExtent );
124  if ( myRasterExtent.isEmpty() )
125  {
126  QgsDebugMsg( "draw request outside view extent." );
127  // nothing to do
128  return;
129  }
130 
131  QgsDebugMsgLevel( "theViewExtent is " + rendererContext.extent().toString(), 4 );
132  QgsDebugMsgLevel( "myProjectedViewExtent is " + myProjectedViewExtent.toString(), 4 );
133  QgsDebugMsgLevel( "myProjectedLayerExtent is " + myProjectedLayerExtent.toString(), 4 );
134  QgsDebugMsgLevel( "myRasterExtent is " + myRasterExtent.toString(), 4 );
135 
136  //
137  // The first thing we do is set up the QgsRasterViewPort. This struct stores all the settings
138  // relating to the size (in pixels and coordinate system units) of the raster part that is
139  // in view in the map window. It also stores the origin.
140  //
141  //this is not a class level member because every time the user pans or zooms
142  //the contents of the rasterViewPort will change
143  mRasterViewPort = new QgsRasterViewPort();
144 
145  mRasterViewPort->mDrawnExtent = myRasterExtent;
146  if ( rendererContext.coordinateTransform().isValid() )
147  {
148  mRasterViewPort->mSrcCRS = layer->crs();
149  mRasterViewPort->mDestCRS = rendererContext.coordinateTransform().destinationCrs();
150  mRasterViewPort->mSrcDatumTransform = rendererContext.coordinateTransform().sourceDatumTransform();
151  mRasterViewPort->mDestDatumTransform = rendererContext.coordinateTransform().destinationDatumTransform();
152  }
153  else
154  {
155  mRasterViewPort->mSrcCRS = QgsCoordinateReferenceSystem(); // will be invalid
156  mRasterViewPort->mDestCRS = QgsCoordinateReferenceSystem(); // will be invalid
157  mRasterViewPort->mSrcDatumTransform = -1;
158  mRasterViewPort->mDestDatumTransform = -1;
159  }
160 
161  // get dimensions of clipped raster image in device coordinate space (this is the size of the viewport)
162  mRasterViewPort->mTopLeftPoint = mapToPixel.transform( myRasterExtent.xMinimum(), myRasterExtent.yMaximum() );
163  mRasterViewPort->mBottomRightPoint = mapToPixel.transform( myRasterExtent.xMaximum(), myRasterExtent.yMinimum() );
164 
165  // align to output device grid, i.e. std::floor/ceil to integers
166  // TODO: this should only be done if paint device is raster - screen, image
167  // for other devices (pdf) it can have floating point origin
168  // we could use floating point for raster devices as well, but respecting the
169  // output device grid should make it more effective as the resampling is done in
170  // the provider anyway
171  mRasterViewPort->mTopLeftPoint.setX( std::floor( mRasterViewPort->mTopLeftPoint.x() ) );
172  mRasterViewPort->mTopLeftPoint.setY( std::floor( mRasterViewPort->mTopLeftPoint.y() ) );
173  mRasterViewPort->mBottomRightPoint.setX( std::ceil( mRasterViewPort->mBottomRightPoint.x() ) );
174  mRasterViewPort->mBottomRightPoint.setY( std::ceil( mRasterViewPort->mBottomRightPoint.y() ) );
175  // recalc myRasterExtent to aligned values
176  myRasterExtent.set(
177  mapToPixel.toMapCoordinatesF( mRasterViewPort->mTopLeftPoint.x(),
178  mRasterViewPort->mBottomRightPoint.y() ),
179  mapToPixel.toMapCoordinatesF( mRasterViewPort->mBottomRightPoint.x(),
180  mRasterViewPort->mTopLeftPoint.y() )
181  );
182 
183  //raster viewport top left / bottom right are already rounded to int
184  mRasterViewPort->mWidth = static_cast<int>( mRasterViewPort->mBottomRightPoint.x() - mRasterViewPort->mTopLeftPoint.x() );
185  mRasterViewPort->mHeight = static_cast<int>( mRasterViewPort->mBottomRightPoint.y() - mRasterViewPort->mTopLeftPoint.y() );
186 
187  //the drawable area can start to get very very large when you get down displaying 2x2 or smaller, this is because
188  //mapToPixel.mapUnitsPerPixel() is less then 1,
189  //so we will just get the pixel data and then render these special cases differently in paintImageToCanvas()
190 
191  QgsDebugMsgLevel( QString( "mapUnitsPerPixel = %1" ).arg( mapToPixel.mapUnitsPerPixel() ), 3 );
192  QgsDebugMsgLevel( QString( "mWidth = %1" ).arg( layer->width() ), 3 );
193  QgsDebugMsgLevel( QString( "mHeight = %1" ).arg( layer->height() ), 3 );
194  QgsDebugMsgLevel( QString( "myRasterExtent.xMinimum() = %1" ).arg( myRasterExtent.xMinimum() ), 3 );
195  QgsDebugMsgLevel( QString( "myRasterExtent.xMaximum() = %1" ).arg( myRasterExtent.xMaximum() ), 3 );
196  QgsDebugMsgLevel( QString( "myRasterExtent.yMinimum() = %1" ).arg( myRasterExtent.yMinimum() ), 3 );
197  QgsDebugMsgLevel( QString( "myRasterExtent.yMaximum() = %1" ).arg( myRasterExtent.yMaximum() ), 3 );
198 
199  QgsDebugMsgLevel( QString( "mTopLeftPoint.x() = %1" ).arg( mRasterViewPort->mTopLeftPoint.x() ), 3 );
200  QgsDebugMsgLevel( QString( "mBottomRightPoint.x() = %1" ).arg( mRasterViewPort->mBottomRightPoint.x() ), 3 );
201  QgsDebugMsgLevel( QString( "mTopLeftPoint.y() = %1" ).arg( mRasterViewPort->mTopLeftPoint.y() ), 3 );
202  QgsDebugMsgLevel( QString( "mBottomRightPoint.y() = %1" ).arg( mRasterViewPort->mBottomRightPoint.y() ), 3 );
203 
204  QgsDebugMsgLevel( QString( "mWidth = %1" ).arg( mRasterViewPort->mWidth ), 3 );
205  QgsDebugMsgLevel( QString( "mHeight = %1" ).arg( mRasterViewPort->mHeight ), 3 );
206 
207  // /\/\/\ - added to handle zoomed-in rasters
208 
209  // TODO R->mLastViewPort = *mRasterViewPort;
210 
211  // TODO: is it necessary? Probably WMS only?
212  layer->dataProvider()->setDpi( 25.4 * rendererContext.scaleFactor() );
213 
214 
215  // copy the whole raster pipe!
216  mPipe = new QgsRasterPipe( *layer->pipe() );
217  QgsRasterRenderer *rasterRenderer = mPipe->renderer();
218  if ( rasterRenderer )
219  layer->refreshRendererIfNeeded( rasterRenderer, rendererContext.extent() );
220 }
221 
223 {
224  delete mFeedback;
225 
226  delete mRasterViewPort;
227  delete mPipe;
228 }
229 
231 {
232  if ( !mRasterViewPort )
233  return true; // outside of layer extent - nothing to do
234 
235  //R->draw( mPainter, mRasterViewPort, &mMapToPixel );
236 
237  QTime time;
238  time.start();
239  //
240  //
241  // The goal here is to make as many decisions as possible early on (outside of the rendering loop)
242  // so that we can maximise performance of the rendering process. So now we check which drawing
243  // procedure to use :
244  //
245 
246  QgsRasterProjector *projector = mPipe->projector();
247 
248  // TODO add a method to interface to get provider and get provider
249  // params in QgsRasterProjector
250  if ( projector )
251  {
252  projector->setCrs( mRasterViewPort->mSrcCRS, mRasterViewPort->mDestCRS, mRasterViewPort->mSrcDatumTransform, mRasterViewPort->mDestDatumTransform );
253  }
254 
255  // Drawer to pipe?
256  QgsRasterIterator iterator( mPipe->last() );
257  QgsRasterDrawer drawer( &iterator );
258  drawer.draw( mPainter, mRasterViewPort, mMapToPixel, mFeedback );
259 
260  QgsDebugMsgLevel( QString( "total raster draw time (ms): %1" ).arg( time.elapsed(), 5 ), 4 );
261 
262  return true;
263 }
264 
266 {
267  return mFeedback;
268 }
269 
int width() const
Accessor that returns the width of the (unclipped) raster.
virtual QgsFeedback * feedback() const override
Access to feedback object of the layer renderer (may be null)
A rectangle specified with double values.
Definition: qgsrectangle.h:38
void setMapRotation(double degrees, double cx, double cy)
Set map rotation in degrees (clockwise)
void setMinimal()
Set a rectangle so that min corner is at max and max corner is at min.
Base class for processing modules.
Definition: qgsrasterpipe.h:45
Iterator for sequentially processing raster cells.
QgsRasterRenderer * renderer() const
#define QgsDebugMsg(str)
Definition: qgslogger.h:37
This class provides qgis with the ability to render raster datasets onto the mapcanvas.
double y
Definition: qgspointxy.h:47
QgsRasterPipe * pipe()
Get raster pipe.
A class to represent a 2D point.
Definition: qgspointxy.h:42
QgsRasterProjector * projector() const
QgsRasterInterface * last() const
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, TransformDirection direction=ForwardTransform, const bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system, which the transform will transform coordinates t...
QgsRectangle intersect(const QgsRectangle *rect) const
Return the intersection with the given rectangle.
void setRenderPartialOutput(bool enable)
Set whether our painter is drawing to a temporary image used just by this layer.
int height() const
Accessor that returns the height of the (unclipped) raster.
Implementation of threaded rendering for raster layers.
virtual bool render() override
Do the rendering (based on data stored in the class)
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
virtual QgsRectangle extent() const
Returns the extent of the layer.
double mapRotation() const
Return current map rotation in degrees.
QgsCoordinateReferenceSystem mDestCRS
Target coordinate system.
QString what() const
Definition: qgsexception.h:48
void setCrs(const QgsCoordinateReferenceSystem &srcCRS, const QgsCoordinateReferenceSystem &destCRS, int srcDatumTransform=-1, int destDatumTransform=-1)
set source and destination CRS
Base class for feedback objects to be used for cancelation of something running in a worker thread...
Definition: qgsfeedback.h:43
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:35
The drawing pipe for raster layers.
QgsPointXY transform(const QgsPointXY &p) const
Transform the point from map (world) coordinates to device coordinates.
QgsRasterDataProvider * dataProvider() override
int mapWidth() const
Return current map width in pixels The information is only known if setRotation was used...
QString id() const
Returns the layer&#39;s unique ID, which is used to access this layer from QgsProject.
int mapHeight() const
Return current map height in pixels.
void setPreviewOnly(bool preview)
set flag whether the block request is for preview purposes only
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:38
bool isEmpty() const
Returns true if the rectangle is empty.
const QgsRectangle & extent() const
QgsRasterLayerRenderer(QgsRasterLayer *layer, QgsRenderContext &rendererContext)
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
QgsCoordinateReferenceSystem crs() const
Returns the layer&#39;s spatial reference system.
QgsCoordinateTransform coordinateTransform() const
Returns the current coordinate transform for the context, or an invalid transform is no coordinate tr...
double mapUnitsPerPixel() const
Return current map units per pixel.
void setX(double x)
Sets the x value of the point.
Definition: qgspointxy.h:102
double x
Definition: qgspointxy.h:46
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:111
QgsCoordinateReferenceSystem mSrcCRS
Source coordinate system.
double xMaximum() const
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:96
QgsRasterProjector implements approximate projection support for it calculates grid of points in sour...
static void logMessage(const QString &message, const QString &tag=QString(), MessageLevel level=QgsMessageLog::WARNING)
add a message to the instance (and create it if necessary)
Contains information about the context of a rendering operation.
QPainter * painter()
Returns the destination QPainter for the render operation.
const QgsMapToPixel & mapToPixel() const
Whether to make extra effort to update map image with partially rendered layers (better for interacti...
This class represents a coordinate reference system (CRS).
double xMinimum() const
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:101
Base class for utility classes that encapsulate information necessary for rendering of map layers...
double yMaximum() const
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:106
void refreshRendererIfNeeded(QgsRasterRenderer *rasterRenderer, const QgsRectangle &extent)
Refresh renderer with new extent, if needed.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:64
This class provides details of the viewable area that a raster will be rendered into.
bool testFlag(Flag flag) const
Check whether a particular flag is enabled.
double scaleFactor() const
Returns the scaling factor for the render to convert painter units to physical sizes.
Feedback object tailored for raster block reading.
QgsPointXY toMapCoordinatesF(double x, double y) const
Transform device coordinates to map (world) coordinates.
QgsPointXY toMapCoordinates(int x, int y) const
Raster renderer pipe that applies colors to a raster.
void setDpi(int dpi)
Sets the output device resolution.
void set(const QgsPointXY &p1, const QgsPointXY &p2)
Sets the rectangle from two QgsPoints.