Subversion Repositories public iLand

Rev

Rev 984 | Rev 1010 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1
 
671 werner 2
/********************************************************************************************
3
**    iLand - an individual based forest landscape and disturbance model
4
**    http://iland.boku.ac.at
5
**    Copyright (C) 2009-  Werner Rammer, Rupert Seidl
6
**
7
**    This program is free software: you can redistribute it and/or modify
8
**    it under the terms of the GNU General Public License as published by
9
**    the Free Software Foundation, either version 3 of the License, or
10
**    (at your option) any later version.
11
**
12
**    This program is distributed in the hope that it will be useful,
13
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
14
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
**    GNU General Public License for more details.
16
**
17
**    You should have received a copy of the GNU General Public License
18
**    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
********************************************************************************************/
20
 
15 Werner 21
#ifndef GRID_H
22
#define GRID_H
23
 
22 Werner 24
#include <QtCore>
15 Werner 25
 
26
 
27
#include <stdexcept>
145 Werner 28
#include <limits>
150 iland 29
#include <cstring>
15 Werner 30
 
373 werner 31
#include "global.h"
32
 
247 werner 33
/** Grid class (template).
697 werner 34
@ingroup tools
74 Werner 35
Orientation
656 werner 36
The grid is oriented as typically coordinates on the northern hemisphere: higher y-values -> north, higher x-values-> east.
490 werner 37
The projection is reversed for drawing on screen (Viewport).
74 Werner 38
          N
490 werner 39
  (0/2) (1/2) (2/2)
656 werner 40
W (0/1) (1/1) (2/1)  E
74 Werner 41
  (0/0) (1/0) (2/0)
42
          S
43
*/
15 Werner 44
template <class T>
45
class Grid {
46
public:
47
 
48
    Grid();
49
    Grid(int cellsize, int sizex, int sizey) { mData=0; setup(cellsize, sizex, sizey); }
914 werner 50
    /// create from a metric rect
58 Werner 51
    Grid(const QRectF rect_metric, const float cellsize) { mData=0; setup(rect_metric,cellsize); }
33 Werner 52
    // copy ctor
53
    Grid(const Grid<T>& toCopy);
105 Werner 54
    ~Grid() { clear(); }
55
    void clear() { if (mData) delete[] mData; mData=0; }
15 Werner 56
 
18 Werner 57
    bool setup(const float cellsize, const int sizex, const int sizey);
22 Werner 58
    bool setup(const QRectF& rect, const double cellsize);
896 werner 59
    bool setup(const Grid<T>& source) { clear();  mRect = source.mRect; return setup(source.mRect, source.mCellsize); }
75 Werner 60
    void initialize(const T& value) {for( T *p = begin();p!=end(); ++p) *p=value; }
150 iland 61
    void wipe(); ///< write 0-bytes with memcpy to the whole area
154 werner 62
    void wipe(const T value); ///< overwrite the whole area with "value" size of T must be the size of "int" ERRORNOUS!!!
764 werner 63
    /// copies the content of the source grid to this grid.
64
    /// no operation, if the grids are not of the same size.
65
    void copy(const Grid<T> source) { if (source.count()==count()) memcpy(mData, source.mData, count()*sizeof(T)); }
15 Werner 66
 
797 werner 67
    // get the number of cells in x and y direction
145 Werner 68
    int sizeX() const { return mSizeX; }
69
    int sizeY() const { return mSizeY; }
797 werner 70
    // get the size of the grid in metric coordinates (x and y direction)
145 Werner 71
    float metricSizeX() const { return mSizeX*mCellsize; }
72
    float metricSizeY() const { return mSizeY*mCellsize; }
797 werner 73
    /// get the metric rectangle of the grid
49 Werner 74
    QRectF metricRect() const { return mRect; }
797 werner 75
    /// get the rectangle of the grid in terms of indices
76
    QRect rectangle() const { return QRect(QPoint(0,0), QPoint(sizeX(), sizeY())); }
77
    /// get the length of one pixel of the grid
145 Werner 78
    float cellsize() const { return mCellsize; }
373 werner 79
    int count() const { return mCount; } ///< returns the number of elements of the grid
80
    bool isEmpty() const { return mData==NULL; } ///< returns false if the grid was not setup
32 Werner 81
    // operations
15 Werner 82
    // query
33 Werner 83
    /// access (const) with index variables. use int.
84
    inline const T& operator()(const int ix, const int iy) const { return constValueAtIndex(ix, iy); }
85
    /// access (const) using metric variables. use float.
86
    inline const T& operator()(const float x, const float y) const { return constValueAt(x, y); }
48 Werner 87
    inline const T& operator[] (const QPointF &p) const { return constValueAt(p); }
33 Werner 88
 
705 werner 89
    inline T& valueAtIndex(const QPoint& pos) {return valueAtIndex(pos.x(), pos.y());}  ///< value at position defined by a QPoint defining the two indices (x,y)
90
    T& valueAtIndex(const int ix, const int iy) { return mData[iy*mSizeX + ix];  } ///< const value at position defined by indices (x,y)
285 werner 91
    T& valueAtIndex(const int index) {return mData[index]; } ///< get a ref ot value at (one-dimensional) index 'index'.
33 Werner 92
 
705 werner 93
    /// value at position defined by a (integer) QPoint
94
    inline const T& constValueAtIndex(const QPoint& pos) const {return constValueAtIndex(pos.x(), pos.y()); }
95
    /// value at position defined by a pair of integer coordinates
96
    inline const T& constValueAtIndex(const int ix, const int iy) const { return mData[iy*mSizeX + ix];  }
97
    /// value at position defined by the index within the grid
549 werner 98
    const T& constValueAtIndex(const int index) const {return mData[index]; } ///< get a ref ot value at (one-dimensional) index 'index'.
33 Werner 99
 
100
    T& valueAt(const QPointF& posf); ///< value at position defined by metric coordinates (QPointF)
101
    const T& constValueAt(const QPointF& posf) const; ///< value at position defined by metric coordinates (QPointF)
102
 
103
    T& valueAt(const float x, const float y); ///< value at position defined by metric coordinates (x,y)
104
    const T& constValueAt(const float x, const float y) const; ///< value at position defined by metric coordinates (x,y)
105
 
105 Werner 106
    bool coordValid(const float x, const float y) const { return x>=mRect.left() && x<mRect.right()  && y>=mRect.top() && y<mRect.bottom(); }
49 Werner 107
    bool coordValid(const QPointF &pos) const { return coordValid(pos.x(), pos.y()); }
75 Werner 108
 
55 Werner 109
    QPoint indexAt(const QPointF& pos) const { return QPoint(int((pos.x()-mRect.left()) / mCellsize),  int((pos.y()-mRect.top())/mCellsize)); } ///< get index of value at position pos (metric)
538 werner 110
    /// get index (x/y) of the (linear) index 'index' (0..count-1)
111
    QPoint indexOf(const int index) const {return QPoint(index % mSizeX,  index / mSizeX); }
373 werner 112
    bool isIndexValid(const QPoint& pos) const { return (pos.x()>=0 && pos.x()<mSizeX && pos.y()>=0 && pos.y()<mSizeY); } ///< return true, if position is within the grid
113
    bool isIndexValid(const int x, const int y) const {return (x>=0 && x<mSizeX && y>=0 && y<mSizeY); } ///< return true, if index is within the grid
75 Werner 114
    /// force @param pos to contain valid indices with respect to this grid.
55 Werner 115
    void validate(QPoint &pos) const{ pos.setX( qMax(qMin(pos.x(), mSizeX-1), 0) );  pos.setY( qMax(qMin(pos.y(), mSizeY-1), 0) );} ///< ensure that "pos" is a valid key. if out of range, pos is set to minimum/maximum values.
105 Werner 116
    /// get the (metric) centerpoint of cell with index @p pos
549 werner 117
    QPointF cellCenterPoint(const QPoint &pos) const { return QPointF( (pos.x()+0.5)*mCellsize+mRect.left(), (pos.y()+0.5)*mCellsize + mRect.top());} ///< get metric coordinates of the cells center
881 werner 118
    /// get the metric cell center point of the cell given by index 'index'
119
    QPointF cellCenterPoint(const int &index) const { QPoint pos=indexOf(index); return QPointF( (pos.x()+0.5)*mCellsize+mRect.left(), (pos.y()+0.5)*mCellsize + mRect.top());}
105 Werner 120
    /// get the metric rectangle of the cell with index @pos
439 werner 121
    QRectF cellRect(const QPoint &pos) const { QRectF r( QPointF(mRect.left() + mCellsize*pos.x(), mRect.top() + pos.y()*mCellsize),
55 Werner 122
                                                   QSizeF(mCellsize, mCellsize)); return r; } ///< return coordinates of rect given by @param pos.
105 Werner 123
 
27 Werner 124
    inline  T* begin() const { return mData; } ///< get "iterator" pointer
37 Werner 125
    inline  T* end() const { return mEnd; } ///< get iterator end-pointer
717 werner 126
    inline QPoint indexOf(const T* element) const; ///< retrieve index (x/y) of the pointer element. returns -1/-1 if element is not valid.
27 Werner 127
    // special queries
33 Werner 128
    T max() const; ///< retrieve the maximum value of a grid
129
    T sum() const; ///< retrieve the sum of the grid
130
    T avg() const; ///< retrieve the average value of a grid
391 werner 131
    // modifying operations
132
    void add(const T& summand);
133
    void multiply(const T& factor);
33 Werner 134
    /// creates a grid with lower resolution and averaged cell values.
135
    /// @param factor factor by which grid size is reduced (e.g. 3 -> 3x3=9 pixels are averaged to 1 result pixel)
136
    /// @param offsetx, offsety: start averaging with an offset from 0/0 (e.g.: x=1, y=2, factor=3: -> 1/2-3/4 -> 0/0)
137
    /// @return Grid with size sizeX()/factor x sizeY()/factor
138
    Grid<T> averaged(const int factor, const int offsetx=0, const int offsety=0) const;
139
    /// normalized returns a normalized grid, in a way that the sum()  = @param targetvalue.
140
    /// if the grid is empty or the sum is 0, no modifications are performed.
141
    Grid<T> normalized(const T targetvalue) const;
373 werner 142
    T* ptr(int x, int y) { return &(mData[y*mSizeX + x]); } ///< get a pointer to the element denoted by "x" and "y"
143
    inline double distance(const QPoint &p1, const QPoint &p2); ///< distance (metric) between p1 and p2
144
    const QPoint randomPosition() const; ///< returns a (valid) random position within the grid
15 Werner 145
private:
77 Werner 146
 
15 Werner 147
    T* mData;
37 Werner 148
    T* mEnd; ///< pointer to 1 element behind the last
49 Werner 149
    QRectF mRect;
36 Werner 150
    float mCellsize; ///< size of a cell in meter
151
    int mSizeX; ///< count of cells in x-direction
152
    int mSizeY; ///< count of cells in y-direction
153
    int mCount; ///< total number of cells in the grid
15 Werner 154
};
155
 
156
typedef Grid<float> FloatGrid;
157
 
1008 werner 158
enum GridViewType { GridViewRainbow=0, GridViewRainbowReverse=1, GridViewGray=2, GridViewGrayReverse=3, GridViewHeat=4,
880 werner 159
                    GridViewBrewerDiv=10, GridViewBrewerQual=11, GridViewTerrain=12, GridViewCustom=14  };
643 werner 160
 
438 werner 161
/** @class GridRunner is a helper class to iterate over a rectangular fraction of a grid
162
*/
163
template <class T>
164
class GridRunner {
165
public:
650 werner 166
    // constructors with a QRectF (metric coordinates)
617 werner 167
    GridRunner(Grid<T> &target_grid, const QRectF &rectangle) {setup(&target_grid, rectangle);}
168
    GridRunner(const Grid<T> &target_grid, const QRectF &rectangle) {setup(&target_grid, rectangle);}
169
    GridRunner(Grid<T> *target_grid, const QRectF &rectangle) {setup(target_grid, rectangle);}
650 werner 170
    // constructors with a QRect (indices within the grid)
171
    GridRunner(Grid<T> &target_grid, const QRect &rectangle) {setup(&target_grid, rectangle);}
172
    GridRunner(const Grid<T> &target_grid, const QRect &rectangle) {setup(&target_grid, rectangle);}
173
    GridRunner(Grid<T> *target_grid, const QRect &rectangle) {setup(target_grid, rectangle);}
914 werner 174
    GridRunner(Grid<T> *target_grid) {setup(target_grid, target_grid->rectangle()); }
438 werner 175
    T* next(); ///< to to next element, return NULL if finished
662 werner 176
    T* current() const { return mCurrent; }
902 werner 177
    /// return the (index) - coordinates of the current position in the grid
178
    QPoint currentIndex() const { return mGrid->indexOf(mCurrent); }
179
    /// return the coordinates of the cell center point of the current position in the grid.
180
    QPointF currentCoord() const {return mGrid->cellCenterPoint(mGrid->indexOf(mCurrent));}
650 werner 181
    void reset() { mCurrent = mFirst-1; mCurrentCol = -1; }
182
    // helpers
183
    /// fill array with pointers to neighbors (north, east, west, south)
184
    /// or Null-pointers if out of range.
185
    /// the target array (rArray) is not checked and must be valid!
186
    void neighbors4(T** rArray);
187
    void neighbors8(T** rArray);
438 werner 188
private:
617 werner 189
    void setup(const Grid<T> *target_grid, const QRectF &rectangle);
650 werner 190
    void setup(const Grid<T> *target_grid, const QRect &rectangle);
902 werner 191
    const Grid<T> *mGrid;
650 werner 192
    T* mFirst; // points to the first element of the grid
193
    T* mLast; // points to the last element of the grid
438 werner 194
    T* mCurrent;
195
    size_t mLineLength;
196
    size_t mCols;
984 werner 197
    int mCurrentCol;
438 werner 198
};
199
 
646 werner 200
/** @class Vector3D is a simple 3d vector.
201
  QVector3D (from Qt) is in QtGui so we needed a replacement.
202
*/
203
class Vector3D
204
{
205
 public:
206
    Vector3D(): mX(0.), mY(0.), mZ(0.) {}
207
    Vector3D(const double x, const double y, const double z): mX(x), mY(y), mZ(z) {}
208
    double x() const { return mX; } ///< get x-coordinate
209
    double y() const { return mY; } ///< get y-coordinate
210
    double z() const { return mZ; } ///< get z-coordinate
211
    // set variables
212
    void setX(const double x) { mX=x; } ///< set value of the x-coordinate
213
    void setY(const double y) { mY=y; } ///< set value of the y-coordinate
214
    void setZ(const double z) { mZ=z; } ///< set value of the z-coordinate
215
private:
216
    double mX;
217
    double mY;
218
    double mZ;
219
};
438 werner 220
 
33 Werner 221
// copy constructor
222
template <class T>
223
Grid<T>::Grid(const Grid<T>& toCopy)
224
{
40 Werner 225
    mData = 0;
50 Werner 226
    mRect = toCopy.mRect;
33 Werner 227
    setup(toCopy.cellsize(), toCopy.sizeX(), toCopy.sizeY());
228
    const T* end = toCopy.end();
229
    T* ptr = begin();
230
    for (T* i= toCopy.begin(); i!=end; ++i, ++ptr)
231
       *ptr = *i;
232
}
22 Werner 233
 
33 Werner 234
// normalize function
32 Werner 235
template <class T>
33 Werner 236
Grid<T> Grid<T>::normalized(const T targetvalue) const
32 Werner 237
{
33 Werner 238
    Grid<T> target(*this);
239
    T total = sum();
240
    T multiplier;
241
    if (total)
242
        multiplier = targetvalue / total;
243
    else
244
        return target;
245
    for (T* p=target.begin();p!=target.end();++p)
246
        *p *= multiplier;
40 Werner 247
    return target;
33 Werner 248
}
249
 
250
 
251
template <class T>
252
Grid<T> Grid<T>::averaged(const int factor, const int offsetx, const int offsety) const
253
{
32 Werner 254
    Grid<T> target;
255
    target.setup(cellsize()*factor, sizeX()/factor, sizeY()/factor);
256
    int x,y;
257
    T sum=0;
258
    target.initialize(sum);
259
    // sum over array of 2x2, 3x3, 4x4, ...
260
    for (x=offsetx;x<mSizeX;x++)
261
        for (y=offsety;y<mSizeY;y++) {
262
            target.valueAtIndex((x-offsetx)/factor, (y-offsety)/factor) += constValueAtIndex(x,y);
263
        }
264
    // divide
265
    double fsquare = factor*factor;
266
    for (T* p=target.begin();p!=target.end();++p)
267
        *p /= fsquare;
268
    return target;
269
}
22 Werner 270
 
36 Werner 271
 
27 Werner 272
template <class T>
33 Werner 273
T&  Grid<T>::valueAt(const float x, const float y)
274
{
275
    return valueAtIndex( indexAt(QPointF(x,y)) );
276
}
36 Werner 277
 
33 Werner 278
template <class T>
279
const T&  Grid<T>::constValueAt(const float x, const float y) const
280
{
281
    return constValueAtIndex( indexAt(QPointF(x,y)) );
282
}
36 Werner 283
 
33 Werner 284
template <class T>
22 Werner 285
T&  Grid<T>::valueAt(const QPointF& posf)
286
{
287
    return valueAtIndex( indexAt(posf) );
288
}
36 Werner 289
 
33 Werner 290
template <class T>
291
const T&  Grid<T>::constValueAt(const QPointF& posf) const
292
{
293
    return constValueAtIndex( indexAt(posf) );
294
}
22 Werner 295
 
296
template <class T>
15 Werner 297
Grid<T>::Grid()
298
{
37 Werner 299
    mData = 0; mCellsize=0.f;
300
    mEnd = 0;
912 werner 301
    mSizeX=0; mSizeY=0; mCount=0;
15 Werner 302
}
303
 
304
template <class T>
18 Werner 305
bool Grid<T>::setup(const float cellsize, const int sizex, const int sizey)
15 Werner 306
{
912 werner 307
    mSizeX=sizex; mSizeY=sizey;
951 werner 308
    if (mRect.isNull()) // only set rect if not set before (e.g. by call to setup(QRectF, double))
50 Werner 309
        mRect.setCoords(0., 0., cellsize*sizex, cellsize*sizey);
912 werner 310
 
311
    if (mData) {
312
        // test if we can re-use the allocated memory.
951 werner 313
        if (mSizeX*mSizeY > mCount || mCellsize != cellsize) {
912 werner 314
            // we cannot re-use the memory - create new data
315
            delete[] mData; mData=NULL;
316
        }
317
    }
318
    mCellsize=cellsize;
15 Werner 319
    mCount = mSizeX*mSizeY;
951 werner 320
    if (mCount==0)
321
        return false;
322
    if (mData==NULL)
37 Werner 323
        mData = new T[mCount];
912 werner 324
    mEnd = &(mData[mCount]);
325
    return true;
15 Werner 326
}
327
 
328
template <class T>
22 Werner 329
bool Grid<T>::setup(const QRectF& rect, const double cellsize)
15 Werner 330
{
49 Werner 331
    mRect = rect;
22 Werner 332
    int dx = int(rect.width()/cellsize);
49 Werner 333
    if (mRect.left()+cellsize*dx<rect.right())
22 Werner 334
        dx++;
335
    int dy = int(rect.height()/cellsize);
49 Werner 336
    if (mRect.top()+cellsize*dy<rect.bottom())
22 Werner 337
        dy++;
338
    return setup(cellsize, dx, dy);
15 Werner 339
}
340
 
261 werner 341
/** retrieve from the index from an element reversely from a pointer to that element.
342
    The internal memory layout is (for dimx=6, dimy=3):
343
 
344
6  7  8  9  10 11
345
12 13 14 15 16 17
346
Note: north and south are reversed, thus the item with index 0 is located in the south-western edge of the grid! */
487 werner 347
template <class T> inline
717 werner 348
QPoint Grid<T>::indexOf(const T* element) const
25 Werner 349
{
487 werner 350
//    QPoint result(-1,-1);
25 Werner 351
    if (element==NULL || element<mData || element>=end())
487 werner 352
        return QPoint(-1, -1);
25 Werner 353
    int idx = element - mData;
487 werner 354
    return QPoint(idx % mSizeX,  idx / mSizeX);
355
//    result.setX( idx % mSizeX);
356
//    result.setY( idx / mSizeX);
357
//    return result;
25 Werner 358
}
22 Werner 359
 
27 Werner 360
template <class T>
361
T  Grid<T>::max() const
362
{
143 Werner 363
    T maxv = -std::numeric_limits<T>::max();
27 Werner 364
    T* p;
365
    T* pend = end();
366
    for (p=begin(); p!=pend;++p)
367
       maxv = std::max(maxv, *p);
368
    return maxv;
369
}
370
 
33 Werner 371
template <class T>
372
T  Grid<T>::sum() const
373
{
374
    T* pend = end();
375
    T total = 0;
376
    for (T *p=begin(); p!=pend;++p)
377
       total += *p;
378
    return total;
379
}
380
 
381
template <class T>
382
T  Grid<T>::avg() const
383
{
384
    if (count())
385
        return sum() / T(count());
386
    else return 0;
387
}
388
 
150 iland 389
template <class T>
391 werner 390
void Grid<T>::add(const T& summand)
391
{
392
    T* pend = end();
393
    for (T *p=begin(); p!=pend;*p+=summand,++p)
394
       ;
395
}
396
 
397
template <class T>
398
void Grid<T>::multiply(const T& factor)
399
{
400
    T* pend = end();
401
    for (T *p=begin(); p!=pend;*p*=factor,++p)
402
       ;
403
}
404
 
405
 
406
 
407
template <class T>
150 iland 408
void  Grid<T>::wipe()
409
{
410
    memset(mData, 0, mCount*sizeof(T));
411
}
412
template <class T>
413
void  Grid<T>::wipe(const T value)
414
{
154 werner 415
    /* this does not work properly !!! */
153 werner 416
    if (sizeof(T)==sizeof(int)) {
417
        float temp = value;
418
        float *pf = &temp;
419
 
420
        memset(mData, *((int*)pf), mCount*sizeof(T));
421
    } else
150 iland 422
        initialize(value);
423
}
424
 
373 werner 425
template <class T>
426
double Grid<T>::distance(const QPoint &p1, const QPoint &p2)
427
{
428
    QPointF fp1=cellCenterPoint(p1);
429
    QPointF fp2=cellCenterPoint(p2);
430
    double distance = sqrt( (fp1.x()-fp2.x())*(fp1.x()-fp2.x()) + (fp1.y()-fp2.y())*(fp1.y()-fp2.y()));
431
    return distance;
432
}
433
 
434
template <class T>
435
const QPoint Grid<T>::randomPosition() const
436
{
437
    return QPoint(irandom(0,mSizeX-1), irandom(0, mSizeY-1));
438
}
438 werner 439
 
373 werner 440
////////////////////////////////////////////////////////////
438 werner 441
// grid runner
442
////////////////////////////////////////////////////////////
443
template <class T>
650 werner 444
void GridRunner<T>::setup(const Grid<T> *target_grid, const QRect &rectangle)
438 werner 445
{
650 werner 446
    QPoint upper_left = rectangle.topLeft();
651 werner 447
    // due to the strange behavior of QRect::bottom() and right():
650 werner 448
    QPoint lower_right = rectangle.bottomRight();
617 werner 449
    mCurrent = const_cast<Grid<T> *>(target_grid)->ptr(upper_left.x(), upper_left.y());
650 werner 450
    mFirst = mCurrent;
585 werner 451
    mCurrent--; // point to first element -1
617 werner 452
    mLast = const_cast<Grid<T> *>(target_grid)->ptr(lower_right.x()-1, lower_right.y()-1);
438 werner 453
    mCols = lower_right.x() - upper_left.x(); //
617 werner 454
    mLineLength =  target_grid->sizeX() - mCols;
585 werner 455
    mCurrentCol = -1;
902 werner 456
    mGrid = target_grid;
585 werner 457
//    qDebug() << "GridRunner: rectangle:" << rectangle
458
//             << "upper_left:" << target_grid.cellCenterPoint(target_grid.indexOf(mCurrent))
459
//             << "lower_right:" << target_grid.cellCenterPoint(target_grid.indexOf(mLast));
438 werner 460
}
461
 
462
template <class T>
650 werner 463
void GridRunner<T>::setup(const Grid<T> *target_grid, const QRectF &rectangle_metric)
464
{
465
    QRect rect(target_grid->indexAt(rectangle_metric.topLeft()),
466
               target_grid->indexAt(rectangle_metric.bottomRight()) );
467
    setup (target_grid, rect);
468
}
469
 
470
template <class T>
438 werner 471
T* GridRunner<T>::next()
472
{
473
    if (mCurrent>mLast)
474
        return NULL;
475
    mCurrent++;
476
    mCurrentCol++;
585 werner 477
 
438 werner 478
    if (mCurrentCol >= mCols) {
479
        mCurrent += mLineLength; // skip to next line
480
        mCurrentCol = 0;
481
    }
585 werner 482
    if (mCurrent>mLast)
483
        return NULL;
484
    else
485
        return mCurrent;
438 werner 486
}
487
 
650 werner 488
template <class T>
656 werner 489
/// get pointers the the 4-neighborhood
490
/// north, east, south, west
803 werner 491
/// 0-pointers are returned for edge pixels.
650 werner 492
void GridRunner<T>::neighbors4(T** rArray)
493
{
494
    // north:
651 werner 495
    rArray[0] = mCurrent + mCols + mLineLength > mLast?0: mCurrent + mCols + mLineLength;
650 werner 496
    // south:
651 werner 497
    rArray[3] = mCurrent - (mCols + mLineLength) < mFirst?0: mCurrent -  (mCols + mLineLength);
650 werner 498
    // east / west
656 werner 499
    rArray[1] = mCurrentCol<mCols? mCurrent + 1 : 0;
500
    rArray[2] = mCurrentCol>0? mCurrent-1 : 0;
650 werner 501
}
502
 
503
/// get pointers to the 8-neighbor-hood
504
/// north/east/west/south/NE/NW/SE/SW
803 werner 505
/// 0-pointers are returned for edge pixels.
650 werner 506
template <class T>
507
void GridRunner<T>::neighbors8(T** rArray)
508
{
509
    neighbors4(rArray);
510
    // north-east
656 werner 511
    rArray[4] = rArray[0] && rArray[1]? rArray[0]+1: 0;
650 werner 512
    // north-west
656 werner 513
    rArray[5] = rArray[0] && rArray[2]? rArray[0]-1: 0;
650 werner 514
    // south-east
656 werner 515
    rArray[6] = rArray[3] && rArray[1]? rArray[3]+1: 0;
650 werner 516
    // south-west
656 werner 517
    rArray[7] = rArray[3] && rArray[2]? rArray[3]-1: 0;
650 werner 518
 
519
}
520
 
438 werner 521
////////////////////////////////////////////////////////////
36 Werner 522
// global functions
373 werner 523
////////////////////////////////////////////////////////////
36 Werner 524
 
525
/// dumps a FloatGrid to a String.
46 Werner 526
/// rows will be y-lines, columns x-values. (see grid.cpp)
599 werner 527
QString gridToString(const FloatGrid &grid, const QChar sep=QChar(';'), const int newline_after=-1);
36 Werner 528
 
529
/// creates and return a QImage from Grid-Data.
530
/// @param black_white true: max_value = white, min_value = black, false: color-mode: uses a HSV-color model from blue (min_value) to red (max_value), default: color mode (false)
531
/// @param min_value, max_value min/max bounds for color calcuations. values outside bounds are limited to these values. defaults: min=0, max=1
532
/// @param reverse if true, color ramps are inversed (to: min_value = white (black and white mode) or red (color mode). default = false.
533
/// @return a QImage with the Grids size of pixels. Pixel coordinates relate to the index values of the grid.
534
QImage gridToImage(const FloatGrid &grid,
535
                   bool black_white=false,
536
                   double min_value=0., double max_value=1.,
537
                   bool reverse=false);
538
 
556 werner 539
 
285 werner 540
/** load into 'rGrid' the content of the image pointed at by 'fileName'.
541
    Pixels are converted to grey-scale and then transformend to a value ranging from 0..1 (black..white).
542
  */
543
bool loadGridFromImage(const QString &fileName, FloatGrid &rGrid);
544
 
46 Werner 545
/// template version for non-float grids (see also version for FloatGrid)
599 werner 546
/// @param sep string separator
547
/// @param newline_after if <>-1 a newline is added after every 'newline_after' data values
36 Werner 548
template <class T>
599 werner 549
        QString gridToString(const Grid<T> &grid, const QChar sep=QChar(';'), const int newline_after=-1)
36 Werner 550
{
551
    QString res;
552
    QTextStream ts(&res);
553
 
599 werner 554
    int newl_counter = newline_after;
708 werner 555
    for (int y=grid.sizeY()-1;y>=0;--y){
46 Werner 556
        for (int x=0;x<grid.sizeX();x++){
599 werner 557
            ts << grid.constValueAtIndex(x,y) << sep;
558
            if (--newl_counter==0) {
559
                ts << "\r\n";
560
                newl_counter = newline_after;
561
            }
36 Werner 562
        }
563
        ts << "\r\n";
564
    }
565
 
566
    return res;
567
}
46 Werner 568
 
599 werner 569
/// template version for non-float grids (see also version for FloatGrid)
570
/// @param valueFunction pointer to a function with the signature: QString func(const T&) : this should return a QString
571
/// @param sep string separator
572
/// @param newline_after if <>-1 a newline is added after every 'newline_after' data values
573
template <class T>
574
        QString gridToString(const Grid<T> &grid, QString (*valueFunction)(const T& value), const QChar sep=QChar(';'), const int newline_after=-1 )
708 werner 575
        {
576
            QString res;
577
            QTextStream ts(&res);
599 werner 578
 
708 werner 579
            int newl_counter = newline_after;
580
            for (int y=grid.sizeY()-1;y>=0;--y){
581
                for (int x=0;x<grid.sizeX();x++){
582
                    ts << (*valueFunction)(grid.constValueAtIndex(x,y)) << sep;
599 werner 583
 
708 werner 584
                    if (--newl_counter==0) {
585
                        ts << "\r\n";
586
                        newl_counter = newline_after;
587
                    }
588
                }
599 werner 589
                ts << "\r\n";
590
            }
708 werner 591
 
592
            return res;
599 werner 593
        }
646 werner 594
void modelToWorld(const Vector3D &From, Vector3D &To);
599 werner 595
 
596
template <class T>
597
    QString gridToESRIRaster(const Grid<T> &grid, QString (*valueFunction)(const T& value) )
598
{
646 werner 599
        Vector3D model(grid.metricRect().left(), grid.metricRect().top(), 0.);
600
        Vector3D world;
599 werner 601
        modelToWorld(model, world);
607 werner 602
        QString result = QString("ncols %1\r\nnrows %2\r\nxllcorner %3\r\nyllcorner %4\r\ncellsize %5\r\nNODATA_value %6\r\n")
599 werner 603
                                .arg(grid.sizeX())
604
                                .arg(grid.sizeY())
600 werner 605
                                .arg(world.x(),0,'f').arg(world.y(),0,'f')
599 werner 606
                                .arg(grid.cellsize()).arg(-9999);
694 werner 607
        QString line =  gridToString(grid, valueFunction, QChar(' ')); // for special grids
608
        return result + line;
609
}
599 werner 610
 
611
    template <class T>
612
        QString gridToESRIRaster(const Grid<T> &grid )
613
{
646 werner 614
            Vector3D model(grid.metricRect().left(), grid.metricRect().top(), 0.);
615
            Vector3D world;
599 werner 616
            modelToWorld(model, world);
683 werner 617
            QString result = QString("ncols %1\r\nnrows %2\r\nxllcorner %3\r\nyllcorner %4\r\ncellsize %5\r\nNODATA_value %6\r\n")
599 werner 618
                    .arg(grid.sizeX())
619
                    .arg(grid.sizeY())
680 werner 620
                    .arg(world.x(),0,'f').arg(world.y(),0,'f')
599 werner 621
                    .arg(grid.cellsize()).arg(-9999);
694 werner 622
            QString line = gridToString(grid, QChar(' ')); // for normal grids (e.g. float)
623
            return result + line;
599 werner 624
}
625
 
15 Werner 626
#endif // GRID_H