QGIS API Documentation  2.8.2-Wien
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
qgsvectorcolorrampv2.cpp
Go to the documentation of this file.
1 /***************************************************************************
2  qgsvectorcolorrampv2.cpp
3  ---------------------
4  begin : November 2009
5  copyright : (C) 2009 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 "qgsvectorcolorrampv2.h"
17 #include "qgscolorbrewerpalette.h"
18 #include "qgscptcityarchive.h"
19 
20 #include "qgssymbollayerv2utils.h"
21 #include "qgsapplication.h"
22 #include "qgslogger.h"
23 
24 #include <stdlib.h> // for random()
25 #include <algorithm>
26 
27 #include <QTime>
28 
30 
31 static QColor _interpolate( const QColor& c1, const QColor& c2, const double value )
32 {
33  if ( qIsNaN( value ) ) return c2;
34  int r = ( int )( c1.red() + value * ( c2.red() - c1.red() ) );
35  int g = ( int )( c1.green() + value * ( c2.green() - c1.green() ) );
36  int b = ( int )( c1.blue() + value * ( c2.blue() - c1.blue() ) );
37  int a = ( int )( c1.alpha() + value * ( c2.alpha() - c1.alpha() ) );
38 
39  return QColor::fromRgb( r, g, b, a );
40 }
41 
43 
45  bool discrete, QgsGradientStopsList stops )
46  : mColor1( color1 ), mColor2( color2 ), mDiscrete( discrete ), mStops( stops )
47 {
48 }
49 
51 {
52  // color1 and color2
55  if ( props.contains( "color1" ) )
56  color1 = QgsSymbolLayerV2Utils::decodeColor( props["color1"] );
57  if ( props.contains( "color2" ) )
58  color2 = QgsSymbolLayerV2Utils::decodeColor( props["color2"] );
59 
60  //stops
62  if ( props.contains( "stops" ) )
63  {
64  foreach ( QString stop, props["stops"].split( ':' ) )
65  {
66  int i = stop.indexOf( ';' );
67  if ( i == -1 )
68  continue;
69 
70  QColor c = QgsSymbolLayerV2Utils::decodeColor( stop.mid( i + 1 ) );
71  stops.append( QgsGradientStop( stop.left( i ).toDouble(), c ) );
72  }
73  }
74 
75  // discrete vs. continuous
76  bool discrete = false;
77  if ( props.contains( "discrete" ) )
78  {
79  if ( props["discrete"] == "1" )
80  discrete = true;
81  }
82 
83  // search for information keys starting with "info_"
85  for ( QgsStringMap::const_iterator it = props.constBegin();
86  it != props.constEnd(); ++it )
87  {
88  if ( it.key().startsWith( "info_" ) )
89  info[ it.key().mid( 5 )] = it.value();
90  }
91 
92  QgsVectorGradientColorRampV2* r = new QgsVectorGradientColorRampV2( color1, color2, discrete, stops );
93  r->setInfo( info );
94  return r;
95 }
96 
98 {
99  if ( index <= 0 )
100  {
101  return 0;
102  }
103  else if ( index >= mStops.size() + 1 )
104  {
105  return 1;
106  }
107  else
108  {
109  return mStops[index-1].offset;
110  }
111 }
112 
113 QColor QgsVectorGradientColorRampV2::color( double value ) const
114 {
115  if ( qgsDoubleNear( value, 0.0 ) || value < 0.0 )
116  {
117  return mColor1;
118  }
119  else if ( qgsDoubleNear( value, 1.0 ) || value > 1.0 )
120  {
121  return mColor2;
122  }
123  else if ( mStops.isEmpty() )
124  {
125  if ( mDiscrete )
126  return mColor1;
127 
128  return _interpolate( mColor1, mColor2, value );
129  }
130  else
131  {
132  double lower = 0, upper = 0;
133  QColor c1 = mColor1, c2;
134  for ( QgsGradientStopsList::const_iterator it = mStops.begin(); it != mStops.end(); ++it )
135  {
136  if ( it->offset > value )
137  {
138  if ( mDiscrete )
139  return c1;
140 
141  upper = it->offset;
142  c2 = it->color;
143 
144  return upper == lower ? c1 : _interpolate( c1, c2, ( value - lower ) / ( upper - lower ) );
145  }
146  lower = it->offset;
147  c1 = it->color;
148  }
149 
150  if ( mDiscrete )
151  return c1;
152 
153  upper = 1;
154  c2 = mColor2;
155  return upper == lower ? c1 : _interpolate( c1, c2, ( value - lower ) / ( upper - lower ) );
156  }
157 }
158 
160 {
162  mDiscrete, mStops );
163  r->setInfo( mInfo );
164  return r;
165 }
166 
168 {
169  QgsStringMap map;
170  map["color1"] = QgsSymbolLayerV2Utils::encodeColor( mColor1 );
171  map["color2"] = QgsSymbolLayerV2Utils::encodeColor( mColor2 );
172  if ( !mStops.isEmpty() )
173  {
174  QStringList lst;
175  for ( QgsGradientStopsList::const_iterator it = mStops.begin(); it != mStops.end(); ++it )
176  {
177  lst.append( QString( "%1;%2" ).arg( it->offset ).arg( QgsSymbolLayerV2Utils::encodeColor( it->color ) ) );
178  }
179  map["stops"] = lst.join( ":" );
180  }
181 
182  map["discrete"] = mDiscrete ? "1" : "0";
183 
184  for ( QgsStringMap::const_iterator it = mInfo.constBegin();
185  it != mInfo.constEnd(); ++it )
186  {
187  map["info_" + it.key()] = it.value();
188  }
189 
190  return map;
191 }
193 {
194  if ( discrete == mDiscrete )
195  return;
196 
197  // if going to/from Discrete, re-arrange stops
198  // this will only work when stops are equally-spaced
199  QgsGradientStopsList newStops;
200  if ( discrete )
201  {
202  // re-arrange stops offset
203  int numStops = mStops.count() + 2;
204  int i = 1;
205  for ( QgsGradientStopsList::const_iterator it = mStops.begin();
206  it != mStops.end(); ++it )
207  {
208  newStops.append( QgsGradientStop(( double ) i / numStops, it->color ) );
209  if ( i == numStops - 1 )
210  break;
211  i++;
212  }
213  // replicate last color
214  newStops.append( QgsGradientStop(( double ) i / numStops, mColor2 ) );
215  }
216  else
217  {
218  // re-arrange stops offset, remove duplicate last color
219  int numStops = mStops.count() + 2;
220  int i = 1;
221  for ( QgsGradientStopsList::const_iterator it = mStops.begin();
222  it != mStops.end(); ++it )
223  {
224  newStops.append( QgsGradientStop(( double ) i / ( numStops - 2 ), it->color ) );
225  if ( i == numStops - 3 )
226  break;
227  i++;
228  }
229  }
230  mStops = newStops;
231  mDiscrete = discrete;
232 }
233 
234 void QgsVectorGradientColorRampV2::addStopsToGradient( QGradient* gradient, double alpha )
235 {
236  //copy color ramp stops to a QGradient
237  QColor color1 = mColor1;
238  QColor color2 = mColor2;
239  if ( alpha < 1 )
240  {
241  color1.setAlpha( color1.alpha() * alpha );
242  color2.setAlpha( color2.alpha() * alpha );
243  }
244  gradient->setColorAt( 0, color1 );
245  gradient->setColorAt( 1, color2 );
246 
247  for ( QgsGradientStopsList::const_iterator it = mStops.begin();
248  it != mStops.end(); ++it )
249  {
250  QColor rampColor = it->color;
251  if ( alpha < 1 )
252  {
253  rampColor.setAlpha( rampColor.alpha() * alpha );
254  }
255  gradient->setColorAt( it->offset, rampColor );
256  }
257 }
258 
259 
261 
262 
264  int satMin, int satMax, int valMin, int valMax )
265  : mCount( count ), mHueMin( hueMin ), mHueMax( hueMax ),
266  mSatMin( satMin ), mSatMax( satMax ), mValMin( valMin ), mValMax( valMax )
267 {
268  updateColors();
269 }
270 
272 {
277 
278  if ( props.contains( "count" ) ) count = props["count"].toInt();
279  if ( props.contains( "hueMin" ) ) hueMin = props["hueMin"].toInt();
280  if ( props.contains( "hueMax" ) ) hueMax = props["hueMax"].toInt();
281  if ( props.contains( "satMin" ) ) satMin = props["satMin"].toInt();
282  if ( props.contains( "satMax" ) ) satMax = props["satMax"].toInt();
283  if ( props.contains( "valMin" ) ) valMin = props["valMin"].toInt();
284  if ( props.contains( "valMax" ) ) valMax = props["valMax"].toInt();
285 
286  return new QgsVectorRandomColorRampV2( count, hueMin, hueMax, satMin, satMax, valMin, valMax );
287 }
288 
290 {
291  if ( mColors.size() < 1 ) return 0;
292  return index / mColors.size() - 1;
293 }
294 
295 QColor QgsVectorRandomColorRampV2::color( double value ) const
296 {
297  int colorCnt = mColors.count();
298  int colorIdx = ( int )( value * colorCnt );
299 
300  if ( colorIdx >= 0 && colorIdx < colorCnt )
301  return mColors.at( colorIdx );
302 
303  return QColor();
304 }
305 
307 {
309 }
310 
312 {
313  QgsStringMap map;
314  map["count"] = QString::number( mCount );
315  map["hueMin"] = QString::number( mHueMin );
316  map["hueMax"] = QString::number( mHueMax );
317  map["satMin"] = QString::number( mSatMin );
318  map["satMax"] = QString::number( mSatMax );
319  map["valMin"] = QString::number( mValMin );
320  map["valMax"] = QString::number( mValMax );
321  return map;
322 }
323 
325  int hueMax, int hueMin, int satMax, int satMin, int valMax, int valMin )
326 {
327  int h, s, v;
328  QList<QColor> colors;
329 
330  //normalize values
331  int safeHueMax = qMax( hueMin, hueMax );
332  int safeHueMin = qMin( hueMin, hueMax );
333  int safeSatMax = qMax( satMin, satMax );
334  int safeSatMin = qMin( satMin, satMax );
335  int safeValMax = qMax( valMin, valMax );
336  int safeValMin = qMin( valMin, valMax );
337 
338  //start hue at random angle
339  double currentHueAngle = 360.0 * ( double )qrand() / RAND_MAX;
340 
341  for ( int i = 0; i < count; i++ )
342  {
343  //increment hue by golden ratio (approx 137.507 degrees)
344  //as this minimises hue nearness as count increases
345  //see http://basecase.org/env/on-rainbows for more details
346  currentHueAngle += 137.50776;
347  //scale hue to between hueMax and hueMin
348  h = qBound( 0, qRound(( fmod( currentHueAngle, 360.0 ) / 360.0 ) * ( safeHueMax - safeHueMin ) + safeHueMin ), 359 );
349  s = qBound( 0, ( qrand() % ( safeSatMax - safeSatMin + 1 ) ) + safeValMax, 255 );
350  v = qBound( 0, ( qrand() % ( safeValMax - safeValMin + 1 ) ) + safeValMin, 255 );
351  colors.append( QColor::fromHsv( h, s, v ) );
352  }
353  return colors;
354 }
355 
357 {
359 }
360 
362 
364  : mTotalColorCount( 0 )
365 {
366 }
367 
369 {
370 
371 }
372 
374 {
375  return INT_MAX;
376 }
377 
378 double QgsRandomColorsV2::value( int index ) const
379 {
380  Q_UNUSED( index );
381  return 0.0;
382 }
383 
384 QColor QgsRandomColorsV2::color( double value ) const
385 {
386  int minVal = 130;
387  int maxVal = 255;
388 
389  //if value is nan, then use last precalculated color
390  int colorIndex = ( !qIsNaN( value ) ? value : 1 ) * ( mTotalColorCount - 1 );
391  if ( mTotalColorCount >= 1 && mPrecalculatedColors.length() > colorIndex )
392  {
393  //use precalculated hue
394  return mPrecalculatedColors.at( colorIndex );
395  }
396 
397  //can't use precalculated hues, use a totally random hue
398  int h = 1 + ( int )( 360.0 * qrand() / ( RAND_MAX + 1.0 ) );
399  int s = ( qrand() % ( DEFAULT_RANDOM_SAT_MAX - DEFAULT_RANDOM_SAT_MIN + 1 ) ) + DEFAULT_RANDOM_SAT_MIN;
400  int v = ( qrand() % ( maxVal - minVal + 1 ) ) + minVal;
401  return QColor::fromHsv( h, s, v );
402 }
403 
404 void QgsRandomColorsV2::setTotalColorCount( const int colorCount )
405 {
406  //calculate colors in advance, so that we can ensure they are more visually distinct than pure random colors
407  mPrecalculatedColors.clear();
408  mTotalColorCount = colorCount;
409 
410  //This works ok for low color counts, but for > 10 or so colors there's still a good chance of
411  //similar colors being picked. TODO - investigate alternative "n-visually distinct color" routines
412 
413  //random offsets
414  double hueOffset = ( 360.0 * qrand() / ( RAND_MAX + 1.0 ) );
415 
416  //try to maximise difference between hues. this is not an ideal implementation, as constant steps
417  //through the hue wheel are not visually perceived as constant changes in hue
418  //(for instance, we are much more likely to get green hues than yellow hues)
419  double hueStep = 359.0 / colorCount;
420  double currentHue = hueOffset;
421 
422  //build up a list of colors
423  for ( int idx = 0; idx < colorCount; ++ idx )
424  {
425  int h = qRound( currentHue ) % 360;
426  int s = ( qrand() % ( DEFAULT_RANDOM_SAT_MAX - DEFAULT_RANDOM_SAT_MIN + 1 ) ) + DEFAULT_RANDOM_SAT_MIN;
427  int v = ( qrand() % ( DEFAULT_RANDOM_VAL_MAX - DEFAULT_RANDOM_VAL_MIN + 1 ) ) + DEFAULT_RANDOM_VAL_MIN;
428  mPrecalculatedColors << QColor::fromHsv( h, s, v );
429  currentHue += hueStep;
430  }
431 
432  //lastly, shuffle color list
433  std::random_shuffle( mPrecalculatedColors.begin(), mPrecalculatedColors.end() );
434 }
435 
436 QString QgsRandomColorsV2::type() const
437 {
438  return "randomcolors";
439 }
440 
442 {
443  return new QgsRandomColorsV2();
444 }
445 
447 {
448  return QgsStringMap();
449 }
450 
452 
454  : mSchemeName( schemeName ), mColors( colors )
455 {
456  loadPalette();
457 }
458 
460 {
463 
464  if ( props.contains( "schemeName" ) )
465  schemeName = props["schemeName"];
466  if ( props.contains( "colors" ) )
467  colors = props["colors"].toInt();
468 
469  return new QgsVectorColorBrewerColorRampV2( schemeName, colors );
470 }
471 
473 {
475 }
476 
478 {
480 }
481 
483 {
484  return QgsColorBrewerPalette::listSchemeVariants( schemeName );
485 }
486 
488 {
489  if ( mPalette.size() < 1 ) return 0;
490  return index / mPalette.size() - 1;
491 }
492 
493 QColor QgsVectorColorBrewerColorRampV2::color( double value ) const
494 {
495  if ( mPalette.isEmpty() || value < 0 || value > 1 )
496  return QColor( 255, 0, 0 ); // red color as a warning :)
497 
498  int paletteEntry = ( int )( value * mPalette.count() );
499  if ( paletteEntry >= mPalette.count() )
500  paletteEntry = mPalette.count() - 1;
501  return mPalette.at( paletteEntry );
502 }
503 
505 {
507 }
508 
510 {
511  QgsStringMap map;
512  map["schemeName"] = mSchemeName;
513  map["colors"] = QString::number( mColors );
514  return map;
515 }
516 
517 
519 
520 
521 QgsCptCityColorRampV2::QgsCptCityColorRampV2( QString schemeName, QString variantName,
522  bool doLoadFile )
524  mSchemeName( schemeName ), mVariantName( variantName ),
525  mVariantList( QStringList() ), mFileLoaded( false ), mMultiStops( false )
526 {
527  // TODO replace this with hard-coded data in the default case
528  // don't load file if variant is missing
529  if ( doLoadFile && ( variantName != QString() || mVariantList.isEmpty() ) )
530  loadFile();
531 }
532 
533 QgsCptCityColorRampV2::QgsCptCityColorRampV2( QString schemeName, QStringList variantList,
534  QString variantName, bool doLoadFile )
536  mSchemeName( schemeName ), mVariantName( variantName ),
537  mVariantList( variantList ), mFileLoaded( false ), mMultiStops( false )
538 {
540 
541  // TODO replace this with hard-coded data in the default case
542  // don't load file if variant is missing
543  if ( doLoadFile && ( variantName != QString() || mVariantList.isEmpty() ) )
544  loadFile();
545 }
546 
548 {
551 
552  if ( props.contains( "schemeName" ) )
553  schemeName = props["schemeName"];
554  if ( props.contains( "variantName" ) )
555  variantName = props["variantName"];
556 
557  return new QgsCptCityColorRampV2( schemeName, variantName );
558 }
559 
561 {
562  QgsCptCityColorRampV2* ramp = new QgsCptCityColorRampV2( "", "", false );
563  ramp->copy( this );
564  return ramp;
565 }
566 
568 {
569  if ( ! other )
570  return;
571  mColor1 = other->color1();
572  mColor2 = other->color2();
573  mDiscrete = other->isDiscrete();
574  mStops = other->stops();
575  mSchemeName = other->mSchemeName;
576  mVariantName = other->mVariantName;
577  mVariantList = other->mVariantList;
578  mFileLoaded = other->mFileLoaded;
579 }
580 
582 {
585  // add author and copyright information
586  // TODO also add COPYING.xml file/link?
588  info["cpt-city-gradient"] = "<cpt-city>/" + mSchemeName + mVariantName + ".svg";
589  QString copyingFilename = copyingFileName();
590  copyingFilename.remove( QgsCptCityArchive::defaultBaseDir() );
591  info["cpt-city-license"] = "<cpt-city>" + copyingFilename;
592  ramp->setInfo( info );
593  return ramp;
594 }
595 
596 
598 {
599  QgsStringMap map;
600  map["schemeName"] = mSchemeName;
601  map["variantName"] = mVariantName;
602  return map;
603 }
604 
605 
607 {
608  if ( mSchemeName == "" )
609  return QString();
610  else
611  {
612  return QgsCptCityArchive::defaultBaseDir() + QDir::separator() + mSchemeName + mVariantName + ".svg";
613  }
614 }
615 
617 {
618  return QgsCptCityArchive::findFileName( "COPYING.xml", QFileInfo( fileName() ).dir().path(),
620 }
621 
623 {
624  return QgsCptCityArchive::findFileName( "DESC.xml", QFileInfo( fileName() ).dir().path(),
626 }
627 
629 {
631 }
632 
634 {
635  if ( mFileLoaded )
636  {
637  QgsDebugMsg( "File already loaded for " + mSchemeName + mVariantName );
638  return true;
639  }
640 
641  // get filename
642  QString filename = fileName();
643  if ( filename.isNull() )
644  {
645  QgsDebugMsg( "Couldn't get fileName() for " + mSchemeName + mVariantName );
646  return false;
647  }
648 
649  QgsDebugMsg( QString( "filename= %1 loaded=%2" ).arg( filename ).arg( mFileLoaded ) );
650 
651  // get color ramp from svg file
652  QMap< double, QPair<QColor, QColor> > colorMap =
654 
655  // add colors to palette
656  mFileLoaded = false;
657  mStops.clear();
658  QMap<double, QPair<QColor, QColor> >::const_iterator it, prev;
659  // first detect if file is gradient is continuous or dicrete
660  // discrete: stop contains 2 colors and first color is identical to previous second
661  // multi: stop contains 2 colors and no relation with previous stop
662  mDiscrete = false;
663  mMultiStops = false;
664  it = prev = colorMap.constBegin();
665  while ( it != colorMap.constEnd() )
666  {
667  // look for stops that contain multiple values
668  if ( it != colorMap.constBegin() && ( it.value().first != it.value().second ) )
669  {
670  if ( it.value().first == prev.value().second )
671  {
672  mDiscrete = true;
673  break;
674  }
675  else
676  {
677  mMultiStops = true;
678  break;
679  }
680  }
681  prev = it;
682  ++it;
683  }
684 
685  // fill all stops
686  it = prev = colorMap.constBegin();
687  while ( it != colorMap.constEnd() )
688  {
689  if ( mDiscrete )
690  {
691  // mPalette << qMakePair( it.key(), it.value().second );
692  mStops.append( QgsGradientStop( it.key(), it.value().second ) );
693  }
694  else
695  {
696  // mPalette << qMakePair( it.key(), it.value().first );
697  mStops.append( QgsGradientStop( it.key(), it.value().first ) );
698  if (( mMultiStops ) &&
699  ( it.key() != 0.0 && it.key() != 1.0 ) )
700  {
701  mStops.append( QgsGradientStop( it.key(), it.value().second ) );
702  }
703  }
704  prev = it;
705  ++it;
706  }
707 
708  // remove first and last items (mColor1 and mColor2)
709  if ( ! mStops.isEmpty() && mStops.first().offset == 0.0 )
710  mColor1 = mStops.takeFirst().color;
711  if ( ! mStops.isEmpty() && mStops.last().offset == 1.0 )
712  mColor2 = mStops.takeLast().color;
713 
714  mFileLoaded = true;
715  return true;
716 }