Statistics
| Revision:

gvsig-raster / org.gvsig.raster.gdal / trunk / org.gvsig.raster.gdal / org.gvsig.raster.gdal.io / src / main / java / org / gvsig / raster / gdal / io / GdalNative.java @ 937

History | View | Annotate | Download (50 KB)

1
        /* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.raster.gdal.io;
23

    
24
import java.awt.geom.AffineTransform;
25
import java.awt.geom.NoninvertibleTransformException;
26
import java.awt.geom.Point2D;
27
import java.io.IOException;
28

    
29
import org.gvsig.fmap.dal.coverage.RasterLibrary;
30
import org.gvsig.fmap.dal.coverage.RasterLocator;
31
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
32
import org.gvsig.fmap.dal.coverage.datastruct.BandList;
33
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
34
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
35
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
36
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
37
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
38
import org.gvsig.fmap.dal.coverage.util.FileUtils;
39
import org.gvsig.jgdal.Gdal;
40
import org.gvsig.jgdal.GdalBuffer;
41
import org.gvsig.jgdal.GdalException;
42
import org.gvsig.jgdal.GdalRasterBand;
43
import org.gvsig.jgdal.GeoTransform;
44
import org.gvsig.raster.impl.datastruct.DefaultNoData;
45
import org.gvsig.raster.impl.datastruct.ExtentImpl;
46
import org.gvsig.raster.impl.process.RasterTask;
47
import org.gvsig.raster.impl.process.RasterTaskQueue;
48
import org.gvsig.raster.impl.store.properties.DataStoreColorInterpretation;
49
import org.gvsig.raster.impl.store.properties.DataStoreColorTable;
50
import org.gvsig.raster.impl.store.properties.DataStoreMetadata;
51
import org.gvsig.raster.impl.store.properties.DataStoreTransparency;
52
/**
53
 * Soporte 'nativo' para ficheros desde GDAL.
54
 * 
55
 * @author Luis W. Sevilla (sevilla_lui@gva.es)
56
 * @author Nacho Brodin (nachobrodin@gmail.com)
57
 */
58
public class GdalNative extends Gdal {
59
        private String                       fileName                = null;
60
        private String                       shortName               = "";
61
        public         GeoTransform                 trans                   = null;
62
        public int                           width                   = 0, height = 0;
63
        public double                        originX                 = 0D, originY = 0D;
64
        public String                        version                 = "";
65
        protected int                        rBandNr                 = 1, gBandNr = 2, bBandNr = 3, aBandNr = 4;
66
        private int[]                        dataType                = null;
67
        DataStoreMetadata                    metadata                = null;
68
        protected boolean                    georeferenced           = true;
69
        
70
        /**
71
         * Vectores que contiene los desplazamientos de un pixel cuando hay supersampling.
72
         * , es decir el n?mero de pixels de pantalla que tiene un pixel de imagen. Como todos
73
         * los pixeles no tienen el mismo ancho y alto ha de meterse en un array y no puede ser
74
         * una variable. Adem?s hay que tener en cuenta que el primer y ?ltimo pixel son de 
75
         * distinto tama?o que el resto.   
76
         */
77
        public int[]                              stepArrayX             = null;
78
        public int[]                              stepArrayY             = null;
79
        protected GdalRasterBand[]                gdalBands              = null;
80
        private double                            lastReadLine           = -1;
81
        private int                               currentFullWidth       = -1;
82
        private int                               currentFullHeight      = -1;
83
        private int                               currentViewWidth       = -1;
84
        private int                               currentViewHeight      = -1;
85
        private double                            currentViewX           = 0D;
86
        private double                            viewportScaleX         = 0D;
87
        private double                            viewportScaleY         = 0D;
88
        private double                            stepX                  = 0D;
89
        private double                            stepY                  = 0D;
90
        public boolean                            isSupersampling        = false;
91
        private boolean                           open                   = false;
92
        /**
93
         * Estado de transparencia del raster.
94
         */
95
        protected DataStoreTransparency           fileTransparency       = null;
96
        protected DataStoreColorTable             palette                = null;
97
        protected DataStoreColorInterpretation    colorInterpr           = null;
98
        protected AffineTransform                 ownTransformation      = null;
99
        protected AffineTransform                 externalTransformation = new AffineTransform();
100
        
101
        
102
        /**
103
         * Overview usada en el ?ltimo setView
104
         */
105
        int currentOverview = -1;
106
        
107
        
108
        public GdalNative(String fName) throws GdalException, IOException {
109
                super();
110
                init(fName);
111
        }
112
        
113
        private void init(String fName) throws GdalException, IOException {
114
                fileName = fName;
115
                open(fName, GA_ReadOnly);
116
                open = true;
117
                if (getPtro() == -1)
118
                        throw new GdalException("Error en la apertura del fichero. El fichero no tiene un formato v?lido.");
119
//                ext = RasterUtilities.getExtensionFromFileName(fName);
120
                width = getRasterXSize();
121
                height = getRasterYSize();
122

    
123
                int[] dt = new int[getRasterCount()];
124
                for (int i = 0; i < getRasterCount(); i++)
125
                        dt[i] = this.getRasterBand(i + 1).getRasterDataType();
126
                setDataType(dt);
127
                shortName = getDriverShortName();
128
                fileTransparency = new DataStoreTransparency();
129
                colorInterpr = new DataStoreColorInterpretation();
130
                metadata = new DataStoreMetadata(getMetadata(), colorInterpr);
131

    
132
                // Asignamos la interpretaci?n de color leida por gdal a cada banda. Esto
133
                // nos sirve para saber que banda de la imagen va asignada a cada banda de
134
                // visualizaci?n (ARGB)
135
                colorInterpr.initColorInterpretation(getRasterCount());
136
                metadata.initNoDataByBand(getRasterCount());
137
                for (int i = 0; i < getRasterCount(); i++) {
138
                        GdalRasterBand rb = getRasterBand(i + 1);
139
                        String colorInt = getColorInterpretationName(rb.getRasterColorInterpretation());
140
                        metadata.setNoDataEnabled(rb.existsNoDataValue());
141
                        if(rb.existsNoDataValue()) {
142
                                metadata.setNoDataValue(i, rb.getRasterNoDataValue());
143
                                metadata.setNoDataEnabled(rb.existsNoDataValue());
144
                        }
145
                        colorInterpr.setColorInterpValue(i, colorInt);
146
                        if (colorInt.equals("Alpha"))
147
                                fileTransparency.setTransparencyBand(i);
148

    
149
                        if (rb.getRasterColorTable() != null && palette == null) {
150
                                palette = new DataStoreColorTable();
151
                                palette.createPaletteFromGdalColorTable(rb.getRasterColorTable());
152
//                                fileTransparency.setTransparencyRangeList(palette.getTransparencyRange());
153
                        }
154
                }
155
                fileTransparency.setTransparencyByPixelFromMetadata(metadata);
156

    
157
                try {
158
                        trans = getGeoTransform();
159

    
160
                        boolean isCorrect = false;
161
                        for (int i = 0; i < trans.adfgeotransform.length; i++)
162
                                if (trans.adfgeotransform[i] != 0)
163
                                        isCorrect = true;
164
                        if (!isCorrect)
165
                                throw new GdalException("");
166

    
167
                        ownTransformation = new AffineTransform(trans.adfgeotransform[1], trans.adfgeotransform[4], trans.adfgeotransform[2], trans.adfgeotransform[5], trans.adfgeotransform[0], trans.adfgeotransform[3]);
168
                        externalTransformation = (AffineTransform) ownTransformation.clone();
169
                        currentFullWidth = width;
170
                        currentFullHeight = height;
171

    
172
                        this.georeferenced = true;
173
                } catch (GdalException exc) {
174
                        // Transformaci?n para ficheros sin georreferenciaci?n. Se invierte la Y
175
                        // ya que las WC decrecen de
176
                        // arriba a abajo y los pixeles crecen de arriba a abajo
177
                        ownTransformation = new AffineTransform(1, 0, 0, -1, 0, height);
178
                        externalTransformation = (AffineTransform) ownTransformation.clone();
179
                        currentFullWidth = width;
180
                        currentFullHeight = height;
181
                        this.georeferenced = false;
182
                }
183
        }
184
        
185
        /**
186
         * Returns true if this provider is open and false if don't
187
         * @return
188
         */
189
        public boolean isOpen() {
190
                return open;
191
        }
192
        
193
        /*
194
         * (non-Javadoc)
195
         * @see es.gva.cit.jgdal.Gdal#close()
196
         */
197
        public void close() throws GdalException {
198
                open = false;
199
                super.close();
200
        }
201
        
202
        /**
203
         * Obtiene el flag que informa de si el raster tiene valor no data o no.
204
         * Consultar? todas las bandas del mismo y si alguna tiene valor no data
205
         * devuelve true sino devolver? false.
206
         * @return true si tiene valor no data y false si no lo tiene
207
         * @throws GdalException
208
         */
209
        public boolean existsNoDataValue() throws GdalException {
210
                for (int i = 0; i < getRasterCount(); i++) {
211
                        GdalRasterBand rb = getRasterBand(i + 1);
212
                        if (rb.existsNoDataValue())
213
                                return true;
214
                }
215
                return false;
216
        }
217
        
218
        /**
219
         * Obtiene el flag que informa de si el raster tiene valor no data o no
220
         * en una banda concreta.
221
         * @return true si tiene valor no data en esa banda y false si no lo tiene
222
         * @param band Posici?n de la banda a consultar (0..n)
223
         * @throws GdalException
224
         */
225
        public boolean existsNoDataValue(int band) throws GdalException {
226
                GdalRasterBand rb = getRasterBand(band + 1);
227
                return rb.existsNoDataValue();
228
        }
229

    
230
        /**
231
         * Gets nodata value
232
         * @return
233
         */
234
        public NoData getNoDataValue() {
235
                Number value = null;
236
                int type = RasterLocator.getManager().getRasterUtils().getRasterBufTypeFromGdalType(getDataType()[0]);
237
                if (metadata != null && metadata.isNoDataEnabled() && metadata.getNoDataValue().length > 0) {
238
                        switch (type) {
239
                        case Buffer.TYPE_BYTE:
240
                                if (metadata == null || metadata.getNoDataValue().length == 0)
241
                                        value = new Byte(RasterLibrary.defaultByteNoDataValue);
242
                                else
243
                                        value = new Byte((byte)metadata.getNoDataValue()[0]);
244
                                break;
245
                        case Buffer.TYPE_SHORT:
246
                                if (metadata == null || metadata.getNoDataValue().length == 0)
247
                                        value = new Short(RasterLibrary.defaultShortNoDataValue);
248
                                else
249
                                        value = new Short((short)metadata.getNoDataValue()[0]);
250
                                break;
251
                        case Buffer.TYPE_INT:
252
                                if (metadata == null || metadata.getNoDataValue().length == 0)
253
                                        value = new Integer((int)RasterLibrary.defaultIntegerNoDataValue);
254
                                else
255
                                        value = new Integer((int)metadata.getNoDataValue()[0]);
256
                                break;
257
                        case Buffer.TYPE_FLOAT:
258
                                if (metadata == null || metadata.getNoDataValue().length == 0)
259
                                        value = new Float(RasterLibrary.defaultFloatNoDataValue);
260
                                else
261
                                        value = new Float(metadata.getNoDataValue()[0]);
262
                                break;
263
                        case Buffer.TYPE_DOUBLE:
264
                                if (metadata == null || metadata.getNoDataValue().length == 0)
265
                                        value = new Double(RasterLibrary.defaultFloatNoDataValue);
266
                                else
267
                                        value = new Double(metadata.getNoDataValue()[0]);
268
                                break;
269
                        }
270
                }
271

    
272
                return new DefaultNoData(value, value, fileName);
273
        }
274

    
275
        /**
276
         * Asigna el tipo de dato
277
         * @param dt entero que representa el tipo de dato
278
         */
279
        public void setDataType(int[] dt) { 
280
                dataType = dt; 
281
        }
282
        
283
        /**
284
         * Obtiene el tipo de dato
285
         * @return entero que representa el tipo de dato
286
         */
287
        public int[] getDataType() { 
288
                return dataType; 
289
        }
290
        
291
        /**
292
         * Gets the color interpretation
293
         * @return
294
         */
295
        public ColorInterpretation getColorInterpretation() { 
296
                return colorInterpr; 
297
        }
298
        
299
        /**
300
         * Gets the color table
301
         * @return
302
         */
303
        public ColorTable getColorTable() {
304
                return palette;
305
        }
306
        
307
        /**
308
         * Obtiene un punto 2D con las coordenadas del raster a partir de uno en coordenadas
309
         * del punto real.
310
         * Supone rasters no girados
311
         * @param pt        punto en coordenadas del punto real
312
         * @return        punto en coordenadas del raster
313
         */
314
        public Point2D worldToRasterWithoutRot(Point2D pt) {
315
                Point2D p = new Point2D.Double();
316
                AffineTransform at = new AffineTransform(        externalTransformation.getScaleX(), 0, 
317
                                                                                                        0, externalTransformation.getScaleY(), 
318
                                                                                                        externalTransformation.getTranslateX(), externalTransformation.getTranslateY());
319
                try {
320
                        at.inverseTransform(pt, p);
321
                } catch (NoninvertibleTransformException e) {
322
                        return pt;
323
                }
324
                return p;
325
        }
326
                
327
        /**
328
         * Obtiene un punto 2D con las coordenadas del raster a partir de uno en coordenadas
329
         * del punto real.
330
         * Supone rasters no girados
331
         * @param pt        punto en coordenadas del punto real
332
         * @return        punto en coordenadas del raster
333
         */
334
        public Point2D worldToRaster(Point2D pt) {
335
                Point2D p = new Point2D.Double();
336
                try {
337
                        externalTransformation.inverseTransform(pt, p);
338
                } catch (NoninvertibleTransformException e) {
339
                        return pt;
340
                }
341
                return p;
342
        }
343
        
344
        /**
345
         * Obtiene un punto del raster en coordenadas pixel a partir de un punto en coordenadas
346
         * reales. 
347
         * @param pt Punto en coordenadas reales
348
         * @return Punto en coordenadas pixel.
349
         */
350
        public Point2D rasterToWorld(Point2D pt) {
351
                Point2D p = new Point2D.Double();
352
                externalTransformation.transform(pt, p);
353
                return p;
354
        }
355
        
356
        /**
357
         * Calcula el overview a usar. Hay que tener en cuenta que tenemos que tener calculadas las variables
358
         * viewPortScale, currentFullWidth y currentFulHeight
359
         * @param coordenada pixel expresada en double que indica la posici?n superior izquierda
360
         * @throws GdalException
361
         */
362
        private void calcOverview(Point2D tl, Point2D br) throws GdalException {
363
                gdalBands[0] = getRasterBand(1);
364
                currentOverview = -1;
365
                if (gdalBands[0].getOverviewCount() > 0) {
366
                        GdalRasterBand ovb = null;
367
                        for (int i = gdalBands[0].getOverviewCount() - 1; i > 0; i--) {
368
                                ovb = gdalBands[0].getOverview(i);
369
                                if (ovb.getRasterBandXSize() > getRasterXSize() * viewportScaleX) {
370
                                        currentOverview = i;
371
                                        viewportScaleX *= ((double) width / (double) ovb.getRasterBandXSize());
372
                                        viewportScaleY *= ((double) height / (double) ovb.getRasterBandYSize());
373
                                        stepX = 1D / viewportScaleX;
374
                                        stepY = 1D / viewportScaleY;
375
                                        currentFullWidth = ovb.getRasterBandXSize();
376
                                        currentFullHeight = ovb.getRasterBandYSize();
377
                                        currentViewX = Math.min(tl.getX(), br.getX());
378
                                        lastReadLine = Math.min(tl.getY(), br.getY());
379
                                        break;
380
                                }
381
                        }
382
                }
383
        }
384
        
385
        public void setView(double dWorldTLX, double dWorldTLY,
386
                                                double dWorldBRX, double dWorldBRY,
387
                                                int nWidth, int nHeight) throws GdalException {
388
                currentFullWidth = width;
389
                currentFullHeight = height;
390
                Point2D tl = worldToRaster(new Point2D.Double(dWorldTLX, dWorldTLY));
391
                Point2D br = worldToRaster(new Point2D.Double(dWorldBRX, dWorldBRY));
392
                // Calcula cual es la primera l?nea a leer;
393
                currentViewWidth = nWidth;
394
                currentViewHeight = nHeight;
395
//                wcWidth = Math.abs(br.getX() - tl.getX());
396

    
397
                currentViewX = Math.min(tl.getX(), br.getX());
398

    
399
                viewportScaleX = (double) currentViewWidth / (br.getX() - tl.getX());
400
                viewportScaleY = (double) currentViewHeight / (br.getY() - tl.getY());
401
                stepX = 1D / viewportScaleX;
402
                stepY = 1D / viewportScaleY;
403

    
404
                lastReadLine = Math.min(tl.getY(), br.getY());
405
                
406
                //Para lectura del renderizado (ARGB). readWindow selecciona las bandas que necesita.
407

    
408
                // calcula el overview a usar
409
                gdalBands = new GdalRasterBand[4];
410
                calcOverview(tl, br);
411

    
412
                // Selecciona las bandas y los overviews necesarios
413
                /*gdalBands[0] = getRasterBand(rBandNr);
414
                gdalBands[1] = gdalBands[0]; 
415
                gdalBands[2] = gdalBands[1]; 
416

417
                if(getRasterCount() >= 2) {
418
                        gdalBands[1] = getRasterBand(gBandNr);
419
                        gdalBands[2] = gdalBands[1]; 
420
                }
421
                if(this.getRasterCount() >= 3) 
422
                        gdalBands[2] = getRasterBand(bBandNr);
423
                if(colorInterpr.isAlphaBand())
424
                        gdalBands[3] = getRasterBand(aBandNr);                        
425

426
                assignDataTypeFromGdalRasterBands(gdalBands);
427

428
                if (currentOverview > 0) {
429
                        gdalBands[0] = gdalBands[0].getOverview(currentOverview);
430
                        if(getRasterCount() >= 2) {
431
                                gdalBands[1] = gdalBands[1].getOverview(currentOverview);
432
                        }
433
                        if(this.getRasterCount() >= 3) 
434
                                gdalBands[2] = gdalBands[2].getOverview(currentOverview);
435
                        if(colorInterpr.isAlphaBand())
436
                                gdalBands[3] = gdalBands[3].getOverview(currentOverview);                        
437

438
                }*/
439
        }
440
        
441
        /**
442
         * Selecciona bandas y overview en el objeto GdalRasterBand[] para el n?mero de bandas solicitado.
443
         * @param nbands N?mero de bandas solicitado.
444
         * @throws GdalException
445
         */
446
        public void selectGdalBands(int nbands) throws GdalException {
447
                gdalBands = new GdalRasterBand[nbands];
448
                // Selecciona las bandas y los overviews necesarios
449
                gdalBands[0] = getRasterBand(1);
450
                for (int i = 0; i < nbands; i++)
451
                        gdalBands[i] = gdalBands[0];
452

    
453
                assignDataTypeFromGdalRasterBands(gdalBands);
454
//                setDataType(gdalBands[0].getRasterDataType());
455

    
456
                for (int i = 2; i <= nbands; i++) {
457
                        if (getRasterCount() >= i) {
458
                                gdalBands[i - 1] = getRasterBand(i);
459
                                for (int j = i; j < nbands; j++)
460
                                        gdalBands[j] = gdalBands[i - 1];
461
                        }
462
                }
463

    
464
                if (currentOverview > 0) {
465
                        gdalBands[0] = gdalBands[0].getOverview(currentOverview);
466
                        for (int i = 2; i <= nbands; i++) {
467
                                if (getRasterCount() >= i)
468
                                        gdalBands[i - 1] = gdalBands[i - 1].getOverview(currentOverview);
469
                        }
470
                }
471
        }
472
                
473
        int lastY = -1;
474
        
475
        /**
476
         * Lee una l?nea de bytes
477
         * @param line Buffer donde se cargan los datos
478
         * @param initOffset Desplazamiento inicial desde el margen inzquierdo. Esto es necesario para cuando
479
         * se supersamplea ya que cada pixel de imagen ocupa muchos pixeles de pantalla y puede empezar a dibujarse
480
         * por la izquierda a mitad de pixel
481
         * @param gdalBuffer Buffer con la l?nea de datos original
482
         */
483
        private void readLine(byte[][] line, double initOffset, GdalBuffer[] gdalBuffer) {
484
                double j = 0D;
485
                int i = 0;
486
                for (int iBand = 0; iBand < gdalBuffer.length; iBand++) {
487
                        for (i = 0, j = initOffset; i < currentViewWidth && j < gdalBuffer[0].getSize(); i++, j += stepX) {
488
                                line[iBand][i] = gdalBuffer[iBand].buffByte[(int) j];
489
                        }
490
                }
491
        }
492
        
493
        /**
494
         * Lee una l?nea de shorts
495
         * @param line Buffer donde se cargan los datos
496
         * @param initOffset Desplazamiento inicial desde el margen inzquierdo. Esto es necesario para cuando
497
         * se supersamplea ya que cada pixel de imagen ocupa muchos pixeles de pantalla y puede empezar a dibujarse
498
         * por la izquierda a mitad de pixel
499
         * @param gdalBuffer Buffer con la l?nea de datos original
500
         */
501
        private void readLine(short[][] line, double initOffset, GdalBuffer[] gdalBuffer) {
502
                double j = 0D;
503
                int i = 0;
504
                for (int iBand = 0; iBand < gdalBuffer.length; iBand++) {
505
                        for (i = 0, j = initOffset; i < currentViewWidth && j < gdalBuffer[0].getSize(); i++, j += stepX) {
506
                                line[iBand][i] = (short) (gdalBuffer[iBand].buffShort[(int) j] & 0xffff);
507
                        }
508
                }
509
        }
510

    
511
        /**
512
         * Lee una l?nea de ints
513
         * @param line Buffer donde se cargan los datos
514
         * @param initOffset Desplazamiento inicial desde el margen inzquierdo. Esto es necesario para cuando
515
         * se supersamplea ya que cada pixel de imagen ocupa muchos pixeles de pantalla y puede empezar a dibujarse
516
         * por la izquierda a mitad de pixel
517
         * @param gdalBuffer Buffer con la l?nea de datos original
518
         */
519
        private void readLine(int[][] line, double initOffset, GdalBuffer[] gdalBuffer) {
520
                double j = 0D;
521
                int i = 0;
522
                for (int iBand = 0; iBand < gdalBuffer.length; iBand++) {
523
                        for (i = 0, j = initOffset; i < currentViewWidth && j < gdalBuffer[0].getSize(); i++, j += stepX) {
524
                                line[iBand][i] = (gdalBuffer[iBand].buffInt[(int) j] & 0xffffffff);
525
                        }
526
                }
527
        }
528

    
529
        /**
530
         * Lee una l?nea de float
531
         * @param line Buffer donde se cargan los datos
532
         * @param initOffset Desplazamiento inicial desde el margen izquierdo. Esto es necesario para cuando
533
         * se supersamplea ya que cada pixel de imagen ocupa muchos pixeles de pantalla y puede empezar a dibujarse
534
         * por la izquierda a mitad de pixel
535
         * @param gdalBuffer Buffer con la l?nea de datos original
536
         */
537
        private void readLine(float[][] line, double initOffset, GdalBuffer[] gdalBuffer) {
538
                double j = 0D;
539
                int i = 0;
540
                for (int iBand = 0; iBand < gdalBuffer.length; iBand++) {
541
                        for (i = 0, j = initOffset; i < currentViewWidth && j < gdalBuffer[0].getSize(); i++, j += stepX) {
542
                                line[iBand][i] = gdalBuffer[iBand].buffFloat[(int) j];
543
                        }
544
                }
545
        }
546
        
547
        /**
548
         * Lee una l?nea de doubles
549
         * @param line Buffer donde se cargan los datos
550
         * @param initOffset Desplazamiento inicial desde el margen inzquierdo. Esto es necesario para cuando
551
         * se supersamplea ya que cada pixel de imagen ocupa muchos pixeles de pantalla y puede empezar a dibujarse
552
         * por la izquierda a mitad de pixel
553
         * @param gdalBuffer Buffer con la l?nea de datos original
554
         */
555
        private void readLine(double[][] line, double initOffset, GdalBuffer[] gdalBuffer) {
556
                double j = 0D;
557
                int i = 0;
558
                for (int iBand = 0; iBand < gdalBuffer.length; iBand++) {
559
                        for (i = 0, j = initOffset; i < currentViewWidth && j < gdalBuffer[0].getSize(); i++, j += stepX) {
560
                                line[iBand][i] = gdalBuffer[iBand].buffDouble[(int) j];
561
                        }
562
                }
563
        }
564

    
565
        /**
566
         * Lee una l?nea completa del raster y devuelve un array del tipo correcto. Esta funci?n es util
567
         * para una lectura rapida de todo el fichero sin necesidad de asignar vista. 
568
         * @param nLine N?mero de l?nea a leer
569
         * @param band Banda requerida
570
         * @return Object que es un array unidimendional del tipo de datos del raster
571
         * @throws GdalException
572
         */
573
        public Object readCompleteLine(int nLine, int band) throws GdalException {
574
                GdalRasterBand gdalBand = super.getRasterBand(band + 1);
575
                GdalBuffer gdalBuf = null;
576

    
577
                gdalBuf = gdalBand.readRaster(0, nLine, getRasterXSize(), 1, getRasterXSize(), 1, dataType[band]);
578

    
579
                if (dataType[band] == GDT_Byte)
580
                        return gdalBuf.buffByte;
581

    
582
                if (dataType[band] == GDT_Int16 || dataType[band] == GDT_UInt16)
583
                        return gdalBuf.buffShort;
584

    
585
                if (dataType[band] == GDT_Int32 || dataType[band] == GDT_UInt32)
586
                        return gdalBuf.buffInt;
587

    
588
                if (dataType[band] == GDT_Float32)
589
                        return gdalBuf.buffFloat;
590

    
591
                if (dataType[band] == GDT_Float64)
592
                        return gdalBuf.buffDouble;
593

    
594
                if (dataType[band] == GDT_CInt16 || dataType[band] == GDT_CInt32 ||
595
                                dataType[band] == GDT_CFloat32 || dataType[band] == GDT_CFloat64)
596
                        return null;
597
                
598
                return null;
599
        }
600
        
601
        /**
602
         * Lee una bloque completo del raster y devuelve un array tridimensional del tipo correcto. Esta funci?n es util
603
         * para una lectura rapida de todo el fichero sin necesidad de asignar vista. 
604
         * @param nLine N?mero de l?nea a leer
605
         * @param band Banda requerida
606
         * @return Object que es un array unidimendional del tipo de datos del raster
607
         * @throws GdalException
608
         */
609
        public Object readBlock(int pos, int blockHeight, double scale) throws GdalException, ProcessInterruptedException {
610
                bBandNr = super.getRasterCount();
611
                int widthBuffer = (int)(getRasterXSize() * scale);
612
                int heightBuffer = (int)(blockHeight * scale);
613

    
614
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
615
                                
616
                GdalRasterBand[] gdalBand = new GdalRasterBand[bBandNr];
617
                for (int iBand = 0; iBand < gdalBand.length; iBand++) 
618
                        gdalBand[iBand] = super.getRasterBand(iBand + 1);
619
                                
620
                GdalBuffer[] gdalBuf = new GdalBuffer[bBandNr];
621
                                
622
                if (dataType[0] == GDT_Byte) {
623
                        byte[][][] buf = new byte[bBandNr][heightBuffer][widthBuffer];
624
                        for (int iBand = 0; iBand < gdalBuf.length; iBand++) {
625
                                gdalBuf[iBand] = gdalBand[iBand].readRaster(0, pos, getRasterXSize(), blockHeight, widthBuffer, heightBuffer, dataType[0]);
626
                                for (int iRow = 0; iRow < heightBuffer; iRow++) {
627
                                        for (int iCol = 0; iCol < widthBuffer; iCol++) 
628
                                                buf[iBand][iRow][iCol] = gdalBuf[iBand].buffByte[iRow * widthBuffer + iCol];
629
                                        if(task.getEvent() != null)
630
                                                task.manageEvent(task.getEvent());
631
                                }
632
                        }        
633
                        return buf;
634
                } else if (dataType[0] == GDT_CInt16 || dataType[0] == GDT_Int16  || dataType[0] == GDT_UInt16) {
635
                        short[][][] buf = new short[bBandNr][heightBuffer][widthBuffer];
636
                        for (int iBand = 0; iBand < gdalBuf.length; iBand++) {
637
                                gdalBuf[iBand] = gdalBand[iBand].readRaster(0, pos, getRasterXSize(), blockHeight, widthBuffer, heightBuffer, dataType[0]);
638
                                for (int iRow = 0; iRow < heightBuffer; iRow++) {
639
                                        for (int iCol = 0; iCol < widthBuffer; iCol++) 
640
                                                buf[iBand][iRow][iCol] = gdalBuf[iBand].buffShort[iRow * widthBuffer + iCol];
641
                                        if(task.getEvent() != null)
642
                                                task.manageEvent(task.getEvent());
643
                                }
644
                        }        
645
                        return buf;
646
                } else if (dataType[0] == GDT_CInt32 || dataType[0] == GDT_Int32  || dataType[0] == GDT_UInt32) {
647
                        int[][][] buf = new int[bBandNr][heightBuffer][widthBuffer];
648
                        for (int iBand = 0; iBand < gdalBuf.length; iBand++) {
649
                                gdalBuf[iBand] = gdalBand[iBand].readRaster(0, pos, getRasterXSize(), blockHeight, widthBuffer, heightBuffer, dataType[0]);
650
                                for (int iRow = 0; iRow < heightBuffer; iRow++) { 
651
                                        for (int iCol = 0; iCol < widthBuffer; iCol++)
652
                                                buf[iBand][iRow][iCol] = gdalBuf[iBand].buffInt[iRow * widthBuffer + iCol];
653
                                        if(task.getEvent() != null)
654
                                                task.manageEvent(task.getEvent());
655
                                }
656
                        }        
657
                        return buf;
658
                } else if(dataType[0] == GDT_Float32 || dataType[0] == GDT_CFloat32) {
659
                        float[][][] buf = new float[bBandNr][heightBuffer][widthBuffer];
660
                        for (int iBand = 0; iBand < gdalBuf.length; iBand++) {
661
                                gdalBuf[iBand] = gdalBand[iBand].readRaster(0, pos, getRasterXSize(), blockHeight, widthBuffer, heightBuffer, dataType[0]);
662
                                for (int iRow = 0; iRow < heightBuffer; iRow++) {
663
                                        for (int iCol = 0; iCol < widthBuffer; iCol++)
664
                                                buf[iBand][iRow][iCol] = gdalBuf[iBand].buffFloat[iRow * widthBuffer + iCol];
665
                                        if(task.getEvent() != null)
666
                                                task.manageEvent(task.getEvent());
667
                                }
668
                        }        
669
                        return buf;
670
                } else if(dataType[0] == GDT_Float64 || dataType[0] == GDT_CFloat64) {
671
                        double[][][] buf = new double[bBandNr][heightBuffer][widthBuffer];
672
                        for (int iBand = 0; iBand < gdalBuf.length; iBand++) {
673
                                gdalBuf[iBand] = gdalBand[iBand].readRaster(0, pos, getRasterXSize(), blockHeight, widthBuffer, heightBuffer, dataType[0]);
674
                                for (int iRow = 0; iRow < heightBuffer; iRow++) {
675
                                        for (int iCol = 0; iCol < widthBuffer; iCol++) 
676
                                                buf[iBand][iRow][iCol] = gdalBuf[iBand].buffDouble[iRow * widthBuffer + iCol];
677
                                        if(task.getEvent() != null)
678
                                                task.manageEvent(task.getEvent());
679
                                }
680
                        }                
681
                        return buf;
682
                }
683
                                
684
                return null;
685
        }
686
        
687
        /**
688
         * Lectura de una l?nea de datos.
689
         * @param line
690
         * @throws GdalException
691
         */
692
        public void readLine(Object line) throws GdalException {
693
                int w = (int) (Math.ceil(((double)currentViewWidth)*stepX) + 1);
694
                int x = (int) (currentViewX);
695
                int y = (int) (lastReadLine);
696
                GdalBuffer r = null, g = null, b = null;
697
                GdalBuffer a = new GdalBuffer();
698

    
699
                while(y >= gdalBands[0].getRasterBandYSize())
700
                        y--;
701

    
702
                if (x+w > gdalBands[0].getRasterBandXSize()) 
703
                        w = gdalBands[0].getRasterBandXSize()-x;
704

    
705
                if(gdalBands[0].getRasterColorTable() != null) {
706
                        palette = new DataStoreColorTable();
707
                        palette.createPaletteFromGdalColorTable(gdalBands[0].getRasterColorTable());
708
                        r = gdalBands[0].readRaster(x, y, w, 1, w, 1, dataType[0]);
709
                } else {
710
                        a.buffByte = new byte[w];
711
                        r = gdalBands[0].readRaster(x, y, w, 1, w, 1, dataType[0]);
712
                        g = b = r;
713
                        if (getRasterCount() > 1 && gdalBands[1] != null)
714
                                g = gdalBands[1].readRaster(x, y, w, 1, w, 1, dataType[0]);
715
                        if (getRasterCount() > 2 && gdalBands[2] != null)
716
                                b = gdalBands[2].readRaster(x, y, w, 1, w, 1, dataType[0]);
717
                }
718

    
719
                lastReadLine += stepY;
720

    
721
                double initOffset =  Math.abs(currentViewX - ((int)currentViewX));
722
                GdalBuffer[] bands = {r, g, b};
723

    
724
                if (dataType[0] == GDT_Byte)
725
                        readLine((byte[][])line, initOffset, bands);
726
                else if (dataType[0] == GDT_CInt16 || dataType[0] == GDT_Int16  || dataType[0] == GDT_UInt16)
727
                        readLine((short[][])line, initOffset, bands);
728
                else if (dataType[0] == GDT_CInt32 || dataType[0] == GDT_Int32  || dataType[0] == GDT_UInt32)
729
                        readLine((int[][])line, initOffset, bands);
730
                else if(dataType[0] == GDT_Float32 || dataType[0] == GDT_CFloat32)
731
                        readLine((float[][])line, initOffset, bands);
732
                else if(dataType[0] == GDT_Float64 || dataType[0] == GDT_CFloat64)
733
                        readLine((double[][])line, initOffset, bands);
734

    
735
                return;
736
        }
737
                        
738
        /**
739
         * Cuando se hace una petici?n de carga de buffer la extensi?n pedida puede
740
         * estar ajustada a la extensi?n del raster o no estarlo. En caso de no
741
         * estarlo los pixeles del buffer que caen fuera de la extensi?n del raster
742
         * tendr?n valor de NoData. Esta funci?n calcula en que pixel del buffer hay
743
         * que empezar a escribir en caso de que este sea mayor que los datos a leer.
744
         * 
745
         * @param dWorldTLX Posici?n X superior izquierda en coord reales
746
         * @param dWorldTLY Posici?n Y superior izquierda en coord reales
747
         * @param dWorldBRX Posici?n X inferior derecha en coord reales
748
         * @param dWorldBRY Posici?n Y inferior derecha en coord reales
749
         * @param nWidth Ancho en pixeles del buffer
750
         * @param nHeight Alto en pixeles del buffer
751
         * @return desplazamiento dentro del buffer en X e Y
752
         */ 
753
        private int[] calcStepBuffer(Extent dataExtent, int nWidth, int nHeight, int[] stpBuffer) {
754
                Extent imageExtent = getExtentWithoutRot();
755
                Extent ajustDataExtent = RasterLocator.getManager().getRasterUtils().calculateAdjustedView(dataExtent, imageExtent);
756
                if(!RasterLocator.getManager().getRasterUtils().compareExtents(dataExtent, ajustDataExtent)){
757
                        Point2D p1 = worldToRasterWithoutRot(new Point2D.Double(ajustDataExtent.minX(), ajustDataExtent.maxY()));
758
                        Point2D p2 = worldToRasterWithoutRot(new Point2D.Double(ajustDataExtent.maxX(), ajustDataExtent.minY()));
759
                        Point2D p3 = worldToRasterWithoutRot(new Point2D.Double(dataExtent.minX(), dataExtent.maxY()));
760
                        //                    Point2D p4 = worldToRasterWithoutRot(new Point2D.Double(dataExtent.maxX(), dataExtent.minY()));
761
                        //Ese es el ancho y alto q tendr?a el buffer en caso de haberse ajustado
762
                        int w = (int)Math.abs(Math.ceil(p2.getX()) - Math.floor(p1.getX())); 
763
                        int h = (int)Math.abs(Math.floor(p1.getY()) - Math.ceil(p2.getY()));
764

    
765
                        stpBuffer[0] = (int)(p1.getX() + (-p3.getX()));
766
                        stpBuffer[1] = (int)(p1.getY() + (-p3.getY()));
767
                        stpBuffer[2] = stpBuffer[0] + w; 
768
                        stpBuffer[3] = stpBuffer[1] + h;
769
                        return new int[]{w, h};
770
                }
771
                return new int[]{nWidth, nHeight};
772
        }
773
        
774
        /**
775
         * Lee una ventana de datos sin resampleo a partir de coordenadas reales.
776
         * @param buf Buffer donde se almacenan los datos
777
         * @param bandList Lista de bandas que queremos leer y sobre que bandas del buffer de destino queremos escribirlas
778
         * @param dWorldTLX Posici?n X superior izquierda en coord reales
779
         * @param dWorldTLY Posici?n Y superior izquierda en coord reales
780
         * @param dWorldBRX Posici?n X inferior derecha en coord reales
781
         * @param dWorldBRY Posici?n Y inferior derecha en coord reales
782
         * @param nWidth Ancho en pixeles del buffer
783
         * @param nHeight Alto en pixeles del buffer
784
         * @throws GdalException
785
         */
786
        public void readWindow(Buffer buf, BandList bandList, double ulx, double uly,double lrx, double lry,
787
                        int nWidth, int nHeight, boolean adjustToExtent) throws GdalException, ProcessInterruptedException {
788
                Extent petExtent = new ExtentImpl(ulx, uly, lrx, lry);
789
                setView(ulx, uly, lrx, lry, nWidth, nHeight);
790
                Point2D tl = worldToRaster(new Point2D.Double(ulx, uly));
791
                Point2D br = worldToRaster(new Point2D.Double(lrx, lry));
792

    
793
                if(tl.getX() > br.getX())
794
                        tl.setLocation(tl.getX() - 1, tl.getY());
795
                else
796
                        br.setLocation(br.getX() - 1, br.getY());
797
                
798
                if(tl.getY() > br.getY())
799
                        tl.setLocation(tl.getX(), tl.getY() - 1);
800
                else
801
                        br.setLocation(br.getX(), br.getY() - 1);
802
                
803
                if(gdalBands.length == 0)
804
                        return;
805

    
806
                selectGdalBands(/*buf.getBandCount()*/getRasterCount());
807

    
808
                int x = (int) Math.round(Math.min(tl.getX(), br.getX()));
809
                int y = (int) Math.round(Math.min(tl.getY(), br.getY()));
810

    
811
                int[] stpBuffer = new int[]{0, 0 , buf.getWidth(), buf.getHeight()};
812
                //Si el buffer no se ajusta al extent entonces calculamos en que posici?n comienza a escribirse dentro del buffer
813
                //ya que lo que cae fuera ser?n valores NoData
814
                if(!adjustToExtent){
815
                        int[] wh = calcStepBuffer(petExtent, nWidth, nHeight, stpBuffer);
816
                        if(x < 0)
817
                                x  = 0;
818
                        if(y < 0)
819
                                y  = 0;
820
                        readData(buf, bandList, x, y, wh[0], wh[1], wh[0], wh[1], 0, 0, stpBuffer);
821
                        return;
822
                }
823

    
824
                readData(buf, bandList, x, y, nWidth, nHeight, nWidth, nHeight, 0, 0, stpBuffer);
825
        }
826
                        
827
        /**
828
         * Lee una ventana de datos con resampleo a partir de coordenadas reales. Este m?todo lee la
829
         * ventana de una vez cargando los datos de un golpe en el buffer. Las coordenadas se solicitan
830
         * en coordenadas del mundo real por lo que estas pueden caer en cualquier parte de un pixel.
831
         * Esto se hace m?s evidente cuando supersampleamos en la petici?n, es decir el buffer de de 
832
         * mayor tama?o que el n?mero de pixels solicitado.
833
         * 
834
         * Para resolver esto escribiremos con la funci?n readRaster los datos sobre un buffer mayor 
835
         * que el solicitado. Despu?s calcularemos el desplazamiento en pixels dentro de este buffer 
836
         * de mayor tama?o hasta llegar a la coordenada real donde comienza la petici?n real que ha
837
         * hecho el usuario. Esto es as? porque cuando supersampleamos no queremos los pixeles del 
838
         * raster de disco completos sino que en los bordes del buffer quedan cortados.  
839
         *  
840
         * @param buf Buffer donde se almacenan los datos
841
         * @param bandList Lista de bandas que queremos leer y sobre que bandas del buffer de destino queremos escribirlas
842
         * @param dWorldTLX Posici?n X superior izquierda en coord reales
843
         * @param dWorldTLY Posici?n Y superior izquierda en coord reales
844
         * @param dWorldBRX Posici?n X inferior derecha en coord reales
845
         * @param dWorldBRY Posici?n Y inferior derecha en coord reales
846
         * @param nWidth Ancho en pixeles de la petici?n
847
         * @param nHeight Alto en pixeles de la petici?n
848
         * @param bufWidth Ancho del buffer
849
         * @param bufHeight Alto del buffer
850
         * @throws GdalException
851
         */
852
        public void readWindow(Buffer buf, BandList bandList, double ulx, double uly, double lrx, double lry,
853
                                                                                double nWidth, double nHeight, int bufWidth, int bufHeight, boolean adjustToExtent) throws GdalException, ProcessInterruptedException {
854
                Extent petExtent = new ExtentImpl(ulx, uly, lrx, lry);
855
                setView(ulx, uly, lrx, lry, bufWidth, bufHeight);
856
                Point2D ul = worldToRaster(new Point2D.Double(ulx, uly));
857
                Point2D lr = worldToRaster(new Point2D.Double(lrx, lry));
858
                ul.setLocation(ul.getX() < 0 ? 1 : ul.getX(), ul.getY() < 0 ? 1 : ul.getY());
859
                lr.setLocation(lr.getX() < 0 ? 1 : lr.getX(), lr.getY() < 0 ? 1 : lr.getY());
860
                ul.setLocation(ul.getX() - 0.5, ul.getY() - 0.5);
861
                lr.setLocation(lr.getX() - 0.5, lr.getY() - 0.5);
862
                
863
                /*if(tl.getX() > br.getX())
864
                        tl.setLocation(tl.getX() - 1, tl.getY());
865
                else
866
                        br.setLocation(br.getX() - 1, br.getY());
867
                
868
                if(tl.getY() > br.getY())
869
                        tl.setLocation(tl.getX(), tl.getY() - 1);
870
                else
871
                        br.setLocation(br.getX(), br.getY() - 1);*/
872
                
873
                adjustPoints(ul, lr);
874
                
875
                if(gdalBands.length == 0)
876
                        return;
877
                
878
                selectGdalBands(/*buf.getBandCount()*/getRasterCount());
879
                                
880
                int x = (int) Math.min(ul.getX(), lr.getX());
881
                int y = (int) Math.min(ul.getY(), lr.getY());
882
                //int endX = (int) Math.ceil(Math.max(br.getX(), tl.getX()));
883
                //int endY = (int) Math.ceil(Math.max(br.getY(), tl.getY()));
884

    
885
                int stpX = 0;
886
                int stpY = 0;
887
                                
888
                /*if(bufWidth > Math.ceil(nWidth)){
889
                        stpX = (int)(((tl.getX() - x) * bufWidth) / nWidth);
890
                        bufWidth = (int)((Math.abs(endX - x) * bufWidth) / nWidth);
891
                }
892
                if(bufHeight > Math.ceil(nHeight)){
893
                        stpY = (int)(((tl.getY() - y) * bufHeight) / nHeight);
894
                        bufHeight = (int)((Math.abs(endY - y) * bufHeight) / nHeight);
895
                }
896

897
                nWidth = (int)Math.abs(endX - x);
898
                nHeight = (int)Math.abs(endY - y);*/
899

    
900
                nWidth = (nWidth * currentFullWidth) / width;
901
                nHeight = (nHeight * currentFullHeight) / height;
902
                x = (int)(((long)x * (long)currentFullWidth) / (long)width);
903
                y = (int) (((long)y * (long)currentFullHeight) / (long)height);
904

    
905
                int[] stpBuffer = new int[]{0, 0 , buf.getWidth(), buf.getHeight()};
906
                //Si el buffer no se ajusta al extent entonces calculamos en que posici?n comienza a escribirse dentro del buffer
907
                //ya que lo que cae fuera ser?n valores NoData
908
                if(!adjustToExtent){
909
                        int[] wh = calcStepBuffer(petExtent, bufWidth, bufHeight, stpBuffer);
910
                        if(x < 0)
911
                                x  = 0;
912
                        if(y < 0)
913
                                y  = 0;
914
                        stpBuffer[0] = (int)((stpBuffer[0] * bufWidth) / nWidth);
915
                        stpBuffer[1] = (int)((stpBuffer[1] * bufHeight) / nHeight);
916
                        stpBuffer[2] = (int)((stpBuffer[2] * bufWidth) / nWidth);
917
                        stpBuffer[3] = (int)((stpBuffer[3] * bufHeight) / nHeight);
918
                        bufWidth = (int)Math.abs(stpBuffer[2] - stpBuffer[0]);
919
                        bufHeight = (int)Math.abs(stpBuffer[3] - stpBuffer[1]);
920
                        readData(buf, bandList, x, y, wh[0], wh[1], bufWidth, bufHeight, 0, 0, stpBuffer);
921
                        return;
922
                }
923

    
924
                if ((x + nWidth) > gdalBands[0].getRasterBandXSize()) 
925
                        nWidth = gdalBands[0].getRasterBandXSize() - x;
926

    
927
                if ((y + nHeight) > gdalBands[0].getRasterBandYSize()) 
928
                        nHeight = gdalBands[0].getRasterBandYSize() - y;
929

    
930
                readData(buf, bandList, x, y, (int)nWidth, (int)nHeight, bufWidth, bufHeight, stpX, stpY, stpBuffer);
931
        }
932
        
933
        private void adjustPoints(Point2D ul, Point2D lr) {
934
                double a = (ul.getX() - (int)ul.getX());
935
                double b = (ul.getY() - (int)ul.getY());
936
                ul.setLocation(        (a > 0.95 || a < 0.05) ? Math.round(ul.getX()) : ul.getX(), 
937
                                                (b > 0.95 || b < 0.05) ? Math.round(ul.getY()) : ul.getY());
938
                lr.setLocation(        (a > 0.95 || a < 0.05) ? Math.round(lr.getX()) : lr.getX(), 
939
                                                (b > 0.95 || b < 0.05) ? Math.round(lr.getY()) : lr.getY());
940
        }
941

    
942
        /**
943
         * Lee una ventana de datos sin resampleo a partir de coordenadas en pixeles.
944
         * @param buf Buffer donde se almacenan los datos
945
         * @param bandList Lista de bandas que queremos leer y sobre que bandas del buffer de destino queremos escribirlas
946
         * @param x Posici?n X en pixeles
947
         * @param y Posici?n Y en pixeles
948
         * @param w Ancho en pixeles
949
         * @param h Alto en pixeles
950
         * @throws GdalException
951
         */
952
        public void readWindow(Buffer buf, BandList bandList, int x, int y, int w, int h) 
953
                throws GdalException, ProcessInterruptedException {
954
                gdalBands = new GdalRasterBand[getRasterCount()];
955
                isSupersampling = false;
956
                if(gdalBands.length == 0)
957
                        return;
958
                
959
                // Selecciona las bandas
960
                gdalBands[0] = getRasterBand(1);
961
                
962
                for(int iBand = 1; iBand < gdalBands.length; iBand++)
963
                        gdalBands[iBand] = getRasterBand(iBand + 1);
964
                
965
                assignDataTypeFromGdalRasterBands(gdalBands);
966
                
967
                int[] stepBuffer = new int[]{0, 0, w, h};
968
                readData(buf, bandList, x, y, w, h, w, h, 0, 0, stepBuffer);
969
                //int yMax = y + h;
970
                //readDataByLine(buf, bandList, x, y, w, yMax);
971
        }
972
        
973
        /**
974
         * Lee una ventana de datos con resampleo a partir de coordenadas en pixeles. Este m?todo lee la
975
         * ventana de una vez cargando los datos de un golpe en el buffer.
976
         * @param buf Buffer donde se almacenan los datos
977
         * @param bandList Lista de bandas que queremos leer y sobre que bandas del buffer de destino queremos escribirlas
978
         * @param x Posici?n X en pixeles
979
         * @param y Posici?n Y en pixeles
980
         * @param w Ancho en pixeles
981
         * @param h Alto en pixeles
982
         * @param bufWidth Ancho del buffer
983
         * @param bufHeight Alto del buffer
984
         * @throws GdalException
985
         */
986
        public void readWindow(Buffer buf, BandList bandList, int x, int y, int w, int h, int bufWidth, int bufHeight) throws GdalException, ProcessInterruptedException {
987
                gdalBands = new GdalRasterBand[getRasterCount()];
988
                
989
                if(gdalBands.length == 0)
990
                        return;
991
                
992
                // Selecciona las bandas
993
                gdalBands[0] = getRasterBand(1);
994
                
995
                for(int iBand = 1; iBand < gdalBands.length; iBand++)
996
                        gdalBands[iBand] = getRasterBand(iBand + 1);
997
                
998
                assignDataTypeFromGdalRasterBands(gdalBands);
999
                
1000
                int[] stpBuffer = new int[]{0, 0 , buf.getWidth(), buf.getHeight()};
1001
                readData(buf, bandList, x, y, w, h, bufWidth, bufHeight, 0, 0, stpBuffer);
1002
        }
1003
        
1004
        /**
1005
         * Asigna el tipo de datos de las bandas a partir de una lista de GdalRasterBands
1006
         * @param gdalBands
1007
         * @throws GdalException
1008
         */
1009
        private void assignDataTypeFromGdalRasterBands(GdalRasterBand[] gdalBands) throws GdalException {
1010
                int[] dt = new int[gdalBands.length];
1011
                for (int i = 0; i < gdalBands.length; i++) {
1012
                        if(gdalBands[i] != null)
1013
                                dt[i] = gdalBands[i].getRasterDataType();
1014
                }
1015
                setDataType(dt);
1016
        }
1017
                
1018
        /**
1019
         * Lee una ventana de datos sin resampleo a partir de coordenadas en pixeles. Esta funci?n es usuada por
1020
         * readWindow para coordenadas reales y readWindow en coordenadas pixel. 
1021
         * @param buf Buffer donde se almacenan los datos
1022
         * @param bandList Lista de bandas que queremos leer y sobre que bandas del buffer de destino queremos escribirlas
1023
         * @param x Posici?n X en pixeles
1024
         * @param y Posici?n Y en pixeles
1025
         * @param w Ancho en pixeles
1026
         * @param h Alto en pixeles
1027
         * @param bufWidth Ancho del buffer
1028
         * @param bufHeight Alto del buffer
1029
         * @param stepX Desplazamiento en pixeles en X a partir de la posici?n x. Este desplazamiento es util cuando hay un 
1030
         * supersampleo ya que puede ser que de los pixeles que est?n en el borde izquierdo de la petici?n solo queramos una
1031
         * parte de ellos. 
1032
         * @param stepY Desplazamiento en pixeles en Y a partir de la posici?n y. Este desplazamiento es util cuando hay un 
1033
         * supersampleo ya que puede ser que de los pixeles que est?n en el borde superior de la petici?n solo queramos una
1034
         * parte de ellos.
1035
         * @param stepBuffer El buffer puede empezar a escribirse a partir de un pixel determinado y acabar de escribir antes 
1036
         * de fin de buffer. Este par?metro indica el desplazamiento desde el inicio del buffer y la posici?n final.
1037
         * <UL>
1038
         * <LI>stepBuffer[0]:Desplazamiento en X desde el inicio</LI>
1039
         * <LI>stepBuffer[1]:Desplazamiento en Y desde el inicio</LI>
1040
         * <LI>stepBuffer[2]:Posici?n X final</LI>
1041
         * <LI>stepBuffer[3]:Posici?n Y final</LI>
1042
         * </UL>
1043
         * @throws GdalException
1044
         */
1045
        private void readData(Buffer buf, BandList bandList, int x, int y, int w, int h, 
1046
                        int bufWidth, int bufHeight, int stpX, int stpY, int[] stepBuffer) throws GdalException, ProcessInterruptedException {
1047
                
1048
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString()); 
1049
                FileUtils fUtil = RasterLocator.getManager().getFileUtils(); 
1050
                        
1051
                GdalBuffer gdalBuf = null;
1052
                for(int iBand = 0; iBand < gdalBands.length; iBand++) {
1053
                        int[] drawableBands = bandList.getBufferBandToDraw(fUtil.getFormatedRasterFileName(fileName), iBand);
1054
                        if(drawableBands == null || (drawableBands.length == 1 && drawableBands[0] == -1))
1055
                                continue;        
1056
                        int init = (int)((bufWidth * stpY) + stpX); //Pos inicial. Desplazamos stpX pixels hacia la derecha y bajamos stpY lineas
1057
                        int pos = init;
1058
                        gdalBuf = gdalBands[iBand].readRaster(x, y, w, h, bufWidth, bufHeight, dataType[iBand]);
1059
                        if(dataType[iBand] == Gdal.GDT_Byte) {
1060
                                for (int line = stepBuffer[1]; line < stepBuffer[3]/*buf.getHeight()*/; line++) {
1061
                                        pos = (int)((bufWidth * (line - stepBuffer[0])) + init);
1062
                                        for (int col = stepBuffer[0]; col < stepBuffer[2]/*buf.getWidth()*/; col ++) {
1063
                                                for (int i = 0; i < drawableBands.length; i++) 
1064
                                                        buf.setElem(line, col, drawableBands[i], gdalBuf.buffByte[pos]);
1065
                                                pos ++;
1066
                                        }
1067
                                        if(task.getEvent() != null)
1068
                                                task.manageEvent(task.getEvent());
1069
                                }
1070
                        }else if((dataType[iBand] == Gdal.GDT_UInt16) || (dataType[iBand] == Gdal.GDT_Int16) || (dataType[iBand] == Gdal.GDT_CInt16)) {
1071
                                for (int line = stepBuffer[1]; line < stepBuffer[3]; line++) {
1072
                                        pos = (int)((bufWidth * (line - stepBuffer[0])) + init);
1073
                                        for (int col = stepBuffer[0]; col < stepBuffer[2]; col ++) {
1074
                                                for (int i = 0; i < drawableBands.length; i++)
1075
                                                        buf.setElem(line, col, drawableBands[i], gdalBuf.buffShort[pos]);
1076
                                                pos ++;
1077
                                        }
1078
                                        if(task.getEvent() != null)
1079
                                                task.manageEvent(task.getEvent());
1080
                                }
1081
                        }else if((dataType[iBand] == Gdal.GDT_UInt32) || (dataType[iBand] == Gdal.GDT_Int32) || (dataType[iBand] == Gdal.GDT_CInt32)) {
1082
                                for (int line = stepBuffer[1]; line < stepBuffer[3]; line++) {
1083
                                        pos = (int)((bufWidth * (line - stepBuffer[0])) + init);
1084
                                        for (int col = stepBuffer[0]; col < stepBuffer[2]; col ++) {
1085
                                                for (int i = 0; i < drawableBands.length; i++)
1086
                                                        buf.setElem(line, col, drawableBands[i], gdalBuf.buffInt[pos]);
1087
                                                pos ++;
1088
                                        }
1089
                                        if(task.getEvent() != null)
1090
                                                task.manageEvent(task.getEvent());
1091
                                }
1092
                        }else if(dataType[iBand] == Gdal.GDT_Float32) {
1093
                                for (int line = stepBuffer[1]; line < stepBuffer[3]; line++) {
1094
                                        pos = (int)((bufWidth * (line - stepBuffer[0])) + init);
1095
                                        for (int col = stepBuffer[0]; col < stepBuffer[2]; col ++) {
1096
                                                for (int i = 0; i < drawableBands.length; i++)
1097
                                                        buf.setElem(line, col, drawableBands[i], gdalBuf.buffFloat[pos]);
1098
                                                pos ++;
1099
                                        }
1100
                                        if(task.getEvent() != null)
1101
                                                task.manageEvent(task.getEvent());
1102
                                }
1103
                        }else if(dataType[iBand] == Gdal.GDT_Float64) {
1104
                                for (int line = stepBuffer[1]; line < stepBuffer[3]; line++) {
1105
                                        pos = (int)((bufWidth * (line - stepBuffer[0])) + init);
1106
                                        for (int col = stepBuffer[0]; col < stepBuffer[2]; col ++) {
1107
                                                for (int i = 0; i < drawableBands.length; i++)
1108
                                                        buf.setElem(line, col, drawableBands[i], gdalBuf.buffDouble[pos]);
1109
                                                pos ++;
1110
                                        }
1111
                                        if(task.getEvent() != null)
1112
                                                task.manageEvent(task.getEvent());
1113
                                }
1114
                        }
1115
                }
1116
        }
1117
        
1118
        /**
1119
         * Lee una ventana de datos sin resampleo a partir de coordenadas en pixeles. Esta funci?n es usuada por
1120
         * readWindow para coordenadas reales y readWindow en coordenadas pixel. 
1121
         * @param buf Buffer donde se almacenan los datos
1122
         * @param bandList Lista de bandas que queremos leer y sobre que bandas del buffer de destino queremos escribirlas
1123
         * @param x Posici?n X en pixeles
1124
         * @param y Posici?n Y en pixeles
1125
         * @param w Ancho en pixeles
1126
         * @param yMax altura m?xima de y
1127
         * @throws GdalException
1128
         */
1129
        @SuppressWarnings("unused")
1130
        private void readDataByLine(Buffer buf, BandList bandList, int x, int y, int w, int yMax) throws GdalException, ProcessInterruptedException {
1131
                GdalBuffer gdalBuf = null;
1132
                int rasterBufLine;
1133
                RasterTask task = RasterTaskQueue.get(Thread.currentThread().toString());
1134
                FileUtils fUtil = RasterLocator.getManager().getFileUtils(); 
1135
                
1136
                for(int iBand = 0; iBand < gdalBands.length; iBand++) {
1137
                        int[] drawableBands = bandList.getBufferBandToDraw(fUtil.getFormatedRasterFileName(fileName), iBand);
1138
                        if(drawableBands == null || (drawableBands.length == 1 && drawableBands[0] == -1))
1139
                                continue;        
1140
                        if(dataType[iBand] == Gdal.GDT_Byte) {
1141
                                for (int line = y; line < yMax; line++) {
1142
                                        gdalBuf = gdalBands[iBand].readRaster(x, line, w, 1, w, 1, dataType[iBand]);
1143
                                        rasterBufLine = line - y;
1144
                                        for (int i = 0; i < drawableBands.length; i++) {
1145
                                                buf.setLineInBandByte(gdalBuf.buffByte, rasterBufLine, drawableBands[i]);
1146
                                        }
1147
                                        if(task.getEvent() != null)
1148
                                                task.manageEvent(task.getEvent());
1149
                                }
1150
                        }else if((dataType[iBand] == Gdal.GDT_UInt16) || (dataType[iBand] == Gdal.GDT_Int16) || (dataType[iBand] == Gdal.GDT_CInt16)) {
1151
                                for (int line = y; line < yMax; line++) {
1152
                                        gdalBuf = gdalBands[iBand].readRaster(x, line, w, 1, w, 1, dataType[iBand]);
1153
                                        rasterBufLine = line - y;
1154
                                        for (int i = 0; i < drawableBands.length; i++) {
1155
                                                buf.setLineInBandShort(gdalBuf.buffShort, rasterBufLine, drawableBands[i]);
1156
                                        }
1157
                                        if(task.getEvent() != null)
1158
                                                task.manageEvent(task.getEvent());
1159
                                }
1160
                        }else if((dataType[iBand] == Gdal.GDT_UInt32) || (dataType[iBand] == Gdal.GDT_Int32) || (dataType[iBand] == Gdal.GDT_CInt32)) {
1161
                                for (int line = y; line < yMax; line++) {
1162
                                        gdalBuf = gdalBands[iBand].readRaster(x, line, w, 1, w, 1, dataType[iBand]);
1163
                                        rasterBufLine = line - y;
1164
                                        for (int i = 0; i < drawableBands.length; i++) {
1165
                                                buf.setLineInBandInt(gdalBuf.buffInt, rasterBufLine, drawableBands[i]);
1166
                                        }
1167
                                        if(task.getEvent() != null)
1168
                                                task.manageEvent(task.getEvent());
1169
                                }
1170
                        }else if(dataType[iBand] == Gdal.GDT_Float32){
1171
                                for (int line = y; line < yMax; line++) {
1172
                                        gdalBuf = gdalBands[iBand].readRaster(x, line, w, 1, w, 1, dataType[iBand]);
1173
                                        rasterBufLine = line - y;
1174
                                        for (int i = 0; i < drawableBands.length; i++) {
1175
                                                buf.setLineInBandFloat(gdalBuf.buffFloat, rasterBufLine, drawableBands[i]);
1176
                                        }
1177
                                        if(task.getEvent() != null)
1178
                                                task.manageEvent(task.getEvent());
1179
                                }
1180
                        }else if(dataType[iBand] == Gdal.GDT_Float64){
1181
                                for (int line = y; line < yMax; line++) {
1182
                                        gdalBuf = gdalBands[iBand].readRaster(x, line, w, 1, w, 1, dataType[iBand]);
1183
                                        rasterBufLine = line - y;
1184
                                        for (int i = 0; i < drawableBands.length; i++) {
1185
                                                buf.setLineInBandDouble(gdalBuf.buffDouble, rasterBufLine, drawableBands[i]);
1186
                                        }
1187
                                        if(task.getEvent() != null)
1188
                                                task.manageEvent(task.getEvent());
1189
                                }
1190
                        }
1191
                }
1192
        }
1193
        
1194
        /**
1195
         * Obtiene el valor de un pixel determinado por las coordenadas x e y que se pasan
1196
         * por par?metro
1197
         * @param x Coordenada X del pixel
1198
         * @param y Coordenada Y del pixel
1199
         * @return Array de Object donde cada posici?n representa una banda y el valor ser? Integer
1200
         * en caso de ser byte, shot o int, Float en caso de ser float y Double en caso de ser double.
1201
         */
1202
        public Object[] getData(int x, int y) {
1203
                try {
1204
                        Object[] data = new Object[getRasterCount()];
1205
                        for(int i = 0; i < getRasterCount(); i++){
1206
                                GdalRasterBand rb = getRasterBand(i + 1);
1207
                                GdalBuffer r = rb.readRaster(x, y, 1, 1, 1, 1, dataType[i]);
1208
                                switch(dataType[i]){
1209
                                case 0:        break;                                                                        //Sin tipo
1210
                                case 1:        data[i] = new Integer(r.buffByte[0]);         //Buffer byte (8)
1211
                                                break;
1212
                                case 2:                                                                                        //Buffer short (16)
1213
                                case 3:        data[i] = new Integer(r.buffShort[0]);        //Buffer short (16)
1214
                                                break;
1215
                                case 4:                                                                                        //Buffer int (32)
1216
                                case 5: data[i] = new Integer(r.buffInt[0]);        //Buffer int (32)
1217
                                                break;
1218
                                case 6:        data[i] = new Float(r.buffFloat[0]);        //Buffer float (32)
1219
                                                break;
1220
                                case 7:        data[i] = new Double(r.buffDouble[0]);        //Buffer double (64)
1221
                                                break;
1222
                                }
1223
                        }
1224
                        return data;
1225
                } catch (GdalException e) {
1226
                        return null;
1227
                }
1228
        }
1229
        
1230
        public int getBlockSize(){
1231
                return this.getBlockSize();
1232
        }
1233

    
1234
        /**
1235
         * Devuelve la transformaci?n del fichero de georreferenciaci?n
1236
         * @return AffineTransform
1237
         */
1238
        public AffineTransform getOwnTransformation() {
1239
                return ownTransformation;
1240
        }
1241
                
1242
        /**
1243
         * Calcula el extent en coordenadas del mundo real sin rotaci?n. Solo coordenadas y tama?o de pixel
1244
         * @return Extent
1245
         */
1246
        public Extent getExtentWithoutRot() {
1247
                AffineTransform at = new AffineTransform(        externalTransformation.getScaleX(), 0, 
1248
                                                                                                        0, externalTransformation.getScaleY(), 
1249
                                                                                                        externalTransformation.getTranslateX(), externalTransformation.getTranslateY());
1250
                Point2D p1 = new Point2D.Double(0, 0);
1251
                Point2D p2 = new Point2D.Double(width, height);
1252
                at.transform(p1, p1);
1253
                at.transform(p2, p2);
1254
                return new ExtentImpl(p1, p2);
1255
        }
1256
        
1257
        /**
1258
         * Asigna una transformaci?n que es aplicada sobre la que ya tiene el propio fichero
1259
         * @param t
1260
         */
1261
        public void setExternalTransform(AffineTransform t){
1262
                externalTransformation = t;
1263
        }
1264

    
1265
        /**
1266
         * Obtiene el nombre del driver de Gdal
1267
         * @return Cadena que representa el nombre del driver de gdal
1268
         */
1269
        public String getGdalShortName() {
1270
                return shortName;
1271
        }
1272
                
1273
}
1274

    
1275

    
1276

    
1277