29#include <QDomDocument>
35#include <QRegularExpression>
38const int QgsPalettedRasterRenderer::MAX_FLOAT_CLASSES = 65536;
43 , mClassData( classes )
51 if ( mSourceColorRamp )
70 const int bandNumber = elem.attribute( QStringLiteral(
"band" ), QStringLiteral(
"-1" ) ).toInt();
73 const QDomElement paletteElem = elem.firstChildElement( QStringLiteral(
"colorPalette" ) );
74 if ( !paletteElem.isNull() )
76 const QDomNodeList paletteEntries = paletteElem.elementsByTagName( QStringLiteral(
"paletteEntry" ) );
78 QDomElement entryElem;
81 for (
int i = 0; i < paletteEntries.size(); ++i )
85 entryElem = paletteEntries.at( i ).toElement();
86 value = entryElem.attribute( QStringLiteral(
"value" ), QStringLiteral(
"0" ) ).toDouble();
87 color = QColor( entryElem.attribute( QStringLiteral(
"color" ), QStringLiteral(
"#000000" ) ) );
88 color.setAlpha( entryElem.attribute( QStringLiteral(
"alpha" ), QStringLiteral(
"255" ) ).toInt() );
89 label = entryElem.attribute( QStringLiteral(
"label" ) );
90 QgsDebugMsgLevel( QStringLiteral(
"Value: %1, label: %2, color: %3" ).arg( value ).arg(
label, entryElem.attribute( QStringLiteral(
"color" ) ) ), 4 );
99 QDomElement sourceColorRampElem = elem.firstChildElement( QStringLiteral(
"colorramp" ) );
100 if ( !sourceColorRampElem.isNull() && sourceColorRampElem.attribute( QStringLiteral(
"name" ) ) == QLatin1String(
"[source]" ) )
115 const auto constMClassData = mClassData;
116 for (
const Class &
c : constMClassData )
118 if (
c.value == idx )
127 ClassData::iterator cIt = mClassData.begin();
128 for ( ; cIt != mClassData.end(); ++cIt )
130 if ( cIt->value == idx )
140 std::unique_ptr< QgsRasterBlock > outputBlock(
new QgsRasterBlock() );
141 if ( !
mInput || mClassData.isEmpty() )
143 return outputBlock.release();
146 const std::shared_ptr< QgsRasterBlock > inputBlock(
mInput->
block( mBand,
extent, width, height, feedback ) );
148 if ( !inputBlock || inputBlock->isEmpty() )
150 QgsDebugMsg( QStringLiteral(
"No raster data!" ) );
151 return outputBlock.release();
159 std::shared_ptr< QgsRasterBlock > alphaBlock;
164 if ( !alphaBlock || alphaBlock->isEmpty() )
166 return outputBlock.release();
171 alphaBlock = inputBlock;
176 return outputBlock.release();
183 Q_ASSERT( outputBlock );
184 unsigned int *outputData = (
unsigned int * )( outputBlock->bits() );
187 bool isNoData =
false;
188 for (
qgssize i = 0; i < rasterSize; ++i )
190 const double value = inputBlock->valueAndNoData( i, isNoData );
193 outputData[i] = myDefaultColor;
196 if ( !mColors.contains( value ) )
198 outputData[i] = myDefaultColor;
202 if ( !hasTransparency )
204 outputData[i] = mColors.value( value );
215 const double alpha = alphaBlock->value( i );
218 outputBlock->setColor( i, myDefaultColor );
223 currentOpacity *= alpha / 255.0;
227 const QRgb
c = mColors.value( value );
228 outputData[i] = qRgba( currentOpacity * qRed(
c ), currentOpacity * qGreen(
c ), currentOpacity * qBlue(
c ), currentOpacity * qAlpha(
c ) );
232 return outputBlock.release();
237 if ( parentElem.isNull() )
242 QDomElement rasterRendererElem = doc.createElement( QStringLiteral(
"rasterrenderer" ) );
245 rasterRendererElem.setAttribute( QStringLiteral(
"band" ), mBand );
246 QDomElement colorPaletteElem = doc.createElement( QStringLiteral(
"colorPalette" ) );
247 ClassData::const_iterator it = mClassData.constBegin();
248 for ( ; it != mClassData.constEnd(); ++it )
250 const QColor color = it->color;
251 QDomElement colorElem = doc.createElement( QStringLiteral(
"paletteEntry" ) );
252 colorElem.setAttribute( QStringLiteral(
"value" ), it->value );
253 colorElem.setAttribute( QStringLiteral(
"color" ), color.name() );
254 colorElem.setAttribute( QStringLiteral(
"alpha" ), color.alpha() );
255 if ( !it->label.isEmpty() )
257 colorElem.setAttribute( QStringLiteral(
"label" ), it->label );
259 colorPaletteElem.appendChild( colorElem );
261 rasterRendererElem.appendChild( colorPaletteElem );
264 if ( mSourceColorRamp )
267 rasterRendererElem.appendChild( colorRampElem );
270 parentElem.appendChild( rasterRendererElem );
279 const QDomNodeList elements = element.elementsByTagName( QStringLiteral(
"sld:RasterSymbolizer" ) );
280 if ( elements.size() == 0 )
284 QDomElement rasterSymbolizerElem = elements.at( 0 ).toElement();
287 QDomElement channelSelectionElem = doc.createElement( QStringLiteral(
"sld:ChannelSelection" ) );
288 rasterSymbolizerElem.appendChild( channelSelectionElem );
291 QDomElement channelElem = doc.createElement( QStringLiteral(
"sld:GrayChannel" ) );
292 channelSelectionElem.appendChild( channelElem );
295 QDomElement sourceChannelNameElem = doc.createElement( QStringLiteral(
"sld:SourceChannelName" ) );
296 sourceChannelNameElem.appendChild( doc.createTextNode( QString::number(
band() ) ) );
297 channelElem.appendChild( sourceChannelNameElem );
300 QDomElement colorMapElem = doc.createElement( QStringLiteral(
"sld:ColorMap" ) );
301 colorMapElem.setAttribute( QStringLiteral(
"type" ), QStringLiteral(
"values" ) );
302 if ( this->
classes().size() >= 255 )
303 colorMapElem.setAttribute( QStringLiteral(
"extended" ), QStringLiteral(
"true" ) );
304 rasterSymbolizerElem.appendChild( colorMapElem );
308 const QList<QgsPalettedRasterRenderer::Class>
classes = this->
classes();
309 QList<QgsPalettedRasterRenderer::Class>::const_iterator classDataIt =
classes.constBegin();
310 for ( ; classDataIt !=
classes.constEnd(); ++classDataIt )
312 QDomElement colorMapEntryElem = doc.createElement( QStringLiteral(
"sld:ColorMapEntry" ) );
313 colorMapElem.appendChild( colorMapEntryElem );
316 colorMapEntryElem.setAttribute( QStringLiteral(
"color" ), classDataIt->color.name() );
317 colorMapEntryElem.setAttribute( QStringLiteral(
"quantity" ), QString::number( classDataIt->value ) );
318 colorMapEntryElem.setAttribute( QStringLiteral(
"label" ), classDataIt->label );
319 if ( classDataIt->color.alphaF() != 1.0 )
321 colorMapEntryElem.setAttribute( QStringLiteral(
"opacity" ), QString::number( classDataIt->color.alphaF() ) );
328 if ( mSourceColorRamp )
340 QList< QPair< QString, QColor > > symbolItems;
343 const QString lab = classData.label.isEmpty() ? QString::number( classData.value ) : classData.label;
344 symbolItems << qMakePair( lab, classData.color );
352 QList<QgsLayerTreeModelLegendNode *> res;
355 if ( !name.isEmpty() )
361 res.reserve( res.size() + items.size() );
362 for (
const QPair< QString, QColor > &item : items )
383 mSourceColorRamp.reset( ramp );
388 return mSourceColorRamp.get();
393 QList<QgsColorRampShader::ColorRampItem>::const_iterator colorIt = table.constBegin();
395 for ( ; colorIt != table.constEnd(); ++colorIt )
406 const QRegularExpression linePartRx( QStringLiteral(
"[\\s,:]+" ) );
408#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
409 const QStringList parts =
string.split(
'\n', QString::SkipEmptyParts );
411 const QStringList parts =
string.split(
'\n', Qt::SkipEmptyParts );
413 for (
const QString &part : parts )
415#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
416 const QStringList lineParts = part.split( linePartRx, QString::SkipEmptyParts );
418 const QStringList lineParts = part.split( linePartRx, Qt::SkipEmptyParts );
421 switch ( lineParts.count() )
425 const int value = lineParts.at( 0 ).toInt( &ok );
435 const int value = lineParts.at( 0 ).toInt( &ok );
439 const QColor
c( lineParts.at( 1 ) );
447 if ( lineParts.count() < 4 )
450 const int value = lineParts.at( 0 ).toInt( &ok );
455 const double r = lineParts.at( 1 ).toDouble( &rOk );
457 const double g = lineParts.at( 2 ).toDouble( &gOk );
459 const double b = lineParts.at( 3 ).toDouble( &bOk );
462 if ( rOk && gOk && bOk )
464 c = QColor( r, g, b );
467 if ( lineParts.count() >= 5 )
469 const double alpha = lineParts.at( 4 ).toDouble( &ok );
475 if ( lineParts.count() > 5 )
477 label = lineParts.mid( 5 ).join(
' ' );
491 QFile inputFile( path );
493 if ( inputFile.open( QIODevice::ReadOnly ) )
495 QTextStream in( &inputFile );
496 input = in.readAll();
507 std::sort( cd.begin(), cd.end(), [](
const Class & a,
const Class & b ) ->
bool
509 return a.value < b.value;
512 const auto constCd = cd;
513 for (
const Class &
c : constCd )
515 out << QStringLiteral(
"%1 %2 %3 %4 %5 %6" ).arg(
c.value ).arg(
c.color.red() )
516 .arg(
c.color.green() ).arg(
c.color.blue() ).arg(
c.color.alpha() ).arg(
c.label );
518 return out.join(
'\n' );
528 if ( bandNumber > 0 && bandNumber <= raster->
bandCount() )
530 qlonglong numClasses = 0;
544 std::set<double> values;
552 const int nbBlocksWidth =
static_cast< int >( std::ceil( 1.0 * raster->
xSize() / maxWidth ) );
553 const int nbBlocksHeight =
static_cast< int >( std::ceil( 1.0 * raster->
ySize() / maxHeight ) );
554 const int nbBlocks = nbBlocksWidth * nbBlocksHeight;
560 std::unique_ptr< QgsRasterBlock > rasterBlock;
562 bool isNoData =
false;
563 while ( iter.
readNextRasterPart( bandNumber, iterCols, iterRows, rasterBlock, iterLeft, iterTop, &blockExtent ) )
566 feedback->
setProgress( 100 * ( ( iterTop / maxHeight * nbBlocksWidth ) + iterLeft / maxWidth ) / nbBlocks );
571 for (
int row = 0; row < iterRows; row++ )
576 for (
int column = 0; column < iterCols; column++ )
581 const double currentValue = rasterBlock->valueAndNoData( row, column, isNoData );
582 if ( numClasses >= MAX_FLOAT_CLASSES )
584 QgsMessageLog::logMessage( QStringLiteral(
"Number of classes exceeded maximum (%1)." ).arg( MAX_FLOAT_CLASSES ), QStringLiteral(
"Raster" ) );
587 if ( !isNoData && values.find( currentValue ) == values.end() )
589 values.insert( currentValue );
590 data.push_back(
Class( currentValue, QColor(), QLocale().toString( currentValue ) ) );
597 std::sort( data.begin(), data.end(), [](
const Class & a,
const Class & b ) ->
bool
599 return a.value < b.value;
612 const int bins = std::ceil( max - min ) + 1;
630 data <<
Class( currentValue, QColor(), QLocale().toString( currentValue ) );
633 currentValue += interval;
644 if ( ramp && numClasses > 0 )
652 randomRamp->setTotalColorCount( data.count() );
655 if ( numClasses > 1 )
658 QgsPalettedRasterRenderer::ClassData::iterator cIt = data.begin();
659 for ( ; cIt != data.end(); ++cIt )
664 feedback->
setProgress( std::max<int>( 1, 100 * ( i + 1 ) / numClasses ) );
666 cIt->color = ramp->
color( i /
static_cast<double>( numClasses ) );
674void QgsPalettedRasterRenderer::updateArrays()
677 ClassData::const_iterator it = mClassData.constBegin();
678 for ( ; it != mClassData.constEnd(); ++it )
680 mColors[it->value] = qPremultiply( it->color.rgba() );
@ InternalLayerOpacityHandling
The renderer internally handles the raster layer's opacity, so the default layer level opacity handli...
@ Float32
Thirty two bit floating point (float)
@ ARGB32_Premultiplied
Color, alpha, red, green, blue, 4 bytes the same as QImage::Format_ARGB32_Premultiplied.
@ Float64
Sixty four bit floating point (double)
Abstract base class for color ramps.
virtual QColor color(double value) const =0
Returns the color corresponding to a specified value.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Layer tree node points to a map layer.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
Renderer for paletted raster images.
int band() const
Returns the raster band used for rendering the raster.
QgsRasterBlock * block(int bandNo, const QgsRectangle &extent, int width, int height, QgsRasterBlockFeedback *feedback=nullptr) override
Read block of data using given extent and size.
QList< QgsLayerTreeModelLegendNode * > createLegendNodes(QgsLayerTreeLayer *nodeLayer) override
Creates a set of legend nodes representing the renderer.
QgsColorRamp * sourceColorRamp() const
Gets the source color ramp.
static QgsPalettedRasterRenderer::ClassData classDataFromString(const QString &string)
Converts a string containing a color table or class data to to paletted renderer class data.
QString label(double idx) const
Returns optional category label.
void setSourceColorRamp(QgsColorRamp *ramp)
Set the source color ramp.
QList< int > usesBands() const override
Returns a list of band numbers used by the renderer.
void writeXml(QDomDocument &doc, QDomElement &parentElem) const override
Write base class members to xml.
QList< QgsPalettedRasterRenderer::Class > ClassData
Map of value to class properties.
bool accept(QgsStyleEntityVisitorInterface *visitor) const override
Accepts the specified symbology visitor, causing it to visit all symbols associated with the renderer...
Qgis::RasterRendererFlags flags() const override
Returns flags which dictate renderer behavior.
static QgsPalettedRasterRenderer::ClassData classDataFromFile(const QString &path)
Opens a color table file and returns corresponding paletted renderer class data.
static QgsRasterRenderer * create(const QDomElement &elem, QgsRasterInterface *input)
static QgsPalettedRasterRenderer::ClassData colorTableToClassData(const QList< QgsColorRampShader::ColorRampItem > &table)
Converts a raster color table to paletted renderer class data.
ClassData classes() const
Returns a map of value to classes (colors) used by the renderer.
QList< QPair< QString, QColor > > legendSymbologyItems() const override
Returns symbology items if provided by renderer.
QgsPalettedRasterRenderer * clone() const override
Clone itself, create deep copy.
void setLabel(double idx, const QString &label)
Set category label.
static QgsPalettedRasterRenderer::ClassData classDataFromRaster(QgsRasterInterface *raster, int bandNumber, QgsColorRamp *ramp=nullptr, QgsRasterBlockFeedback *feedback=nullptr)
Generates class data from a raster, for the specified bandNumber.
static QString classDataToString(const QgsPalettedRasterRenderer::ClassData &classes)
Converts classes to a string representation, using the .clr/gdal color table file format.
void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props=QVariantMap()) const override
Used from subclasses to create SLD Rule elements following SLD v1.0 specs.
QgsPalettedRasterRenderer(QgsRasterInterface *input, int bandNumber, const ClassData &classes)
Constructor for QgsPalettedRasterRenderer.
Totally random color ramp.
The RasterBandStats struct is a container for statistics about a single raster band.
double minimumValue
The minimum cell value in the raster band.
double maximumValue
The maximum cell value in the raster band.
Feedback object tailored for raster block reading.
The QgsRasterHistogram is a container for histogram of a single raster band.
double minimum
The minimum histogram value.
double maximum
The maximum histogram value.
QgsRasterHistogram::HistogramVector histogramVector
Stores the histogram for a given layer.
bool valid
Histogram is valid.
int binCount
Number of bins (intervals,buckets) in histogram.
Base class for processing filters like renderers, reprojector, resampler etc.
virtual QgsRasterBlock * block(int bandNo, const QgsRectangle &extent, int width, int height, QgsRasterBlockFeedback *feedback=nullptr)=0
Read block of data using given extent and size.
virtual Qgis::DataType dataType(int bandNo) const =0
Returns data type for the band specified by number.
virtual int xSize() const
Gets raster size.
virtual QgsRasterBandStats bandStatistics(int bandNo, int stats=QgsRasterBandStats::All, const QgsRectangle &extent=QgsRectangle(), int sampleSize=0, QgsRasterBlockFeedback *feedback=nullptr)
Returns the band statistics.
QString displayBandName(int bandNumber) const
Generates a friendly, descriptive name for the specified bandNumber.
QgsRasterInterface * mInput
virtual int ySize() const
virtual QgsRectangle extent() const
Gets the extent of the interface.
virtual QgsRasterInterface * input() const
Current input.
virtual QgsRasterHistogram histogram(int bandNo, int binCount=0, double minimum=std::numeric_limits< double >::quiet_NaN(), double maximum=std::numeric_limits< double >::quiet_NaN(), const QgsRectangle &extent=QgsRectangle(), int sampleSize=0, bool includeOutOfRange=false, QgsRasterBlockFeedback *feedback=nullptr)
Returns a band histogram.
Iterator for sequentially processing raster cells.
static const int DEFAULT_MAXIMUM_TILE_WIDTH
Default maximum tile width.
bool readNextRasterPart(int bandNumber, int &nCols, int &nRows, QgsRasterBlock **block, int &topLeftCol, int &topLeftRow)
Fetches next part of raster data, caller takes ownership of the block and caller should delete the bl...
static const int DEFAULT_MAXIMUM_TILE_HEIGHT
Default maximum tile height.
void startRasterRead(int bandNumber, qgssize nCols, qgssize nRows, const QgsRectangle &extent, QgsRasterBlockFeedback *feedback=nullptr)
Start reading of raster band.
Raster renderer pipe that applies colors to a raster.
double mOpacity
Global alpha value (0-1)
int mAlphaBand
Read alpha value from band.
QRgb renderColorForNodataPixel() const
Returns the color for the renderer to use to represent nodata pixels.
void _writeXml(QDomDocument &doc, QDomElement &rasterRendererElem) const
Write upper class info into rasterrenderer element (called by writeXml method of subclasses)
int bandCount() const override
Gets number of bands.
QgsRasterTransparency * mRasterTransparency
Raster transparency per color or value. Overwrites global alpha value.
bool usesTransparency() const
void copyCommonProperties(const QgsRasterRenderer *other, bool copyMinMaxOrigin=true)
Copies common properties like opacity / transparency data from other renderer.
virtual void toSld(QDomDocument &doc, QDomElement &element, const QVariantMap &props=QVariantMap()) const
Used from subclasses to create SLD Rule elements following SLD v1.0 specs.
void readXml(const QDomElement &rendererElem) override
Sets base class members from xml. Usually called from create() methods of subclasses.
Implementation of legend node interface for displaying raster legend entries.
int alphaValue(double value, int globalTransparency=255) const
Returns the transparency value for a single value pixel.
A rectangle specified with double values.
Implementation of legend node interface for displaying arbitrary label with icon.
A color ramp entity for QgsStyle databases.
An interface for classes which can visit style entity (e.g.
virtual bool visit(const QgsStyleEntityVisitorInterface::StyleLeaf &entity)
Called when the visitor will visit a style entity.
static QgsColorRamp * loadColorRamp(QDomElement &element)
Creates a color ramp from the settings encoded in an XML element.
static QDomElement saveColorRamp(const QString &name, QgsColorRamp *ramp, QDomDocument &doc)
Encodes a color ramp's settings to an XML element.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
unsigned long long qgssize
Qgssize is used instead of size_t, because size_t is stdlib type, unknown by SIP, and it would be har...
#define QgsDebugMsgLevel(str, level)
Properties of a single value class.
Contains information relating to the style entity currently being visited.