Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / raster / util / process / ClippingProcess.java @ 20120

History | View | Annotate | Download (14.1 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
*
3
* Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
4
*
5
* This program is free software; you can redistribute it and/or
6
* modify it under the terms of the GNU General Public License
7
* as published by the Free Software Foundation; either version 2
8
* of the License, or (at your option) any later version.
9
*
10
* This program is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
* GNU General Public License for more details.
14
*
15
* You should have received a copy of the GNU General Public License
16
* along with this program; if not, write to the Free Software
17
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
*/
19
package org.gvsig.raster.util.process;
20

    
21
import java.awt.geom.AffineTransform;
22
import java.io.File;
23
import java.io.FileNotFoundException;
24
import java.io.IOException;
25

    
26
import org.apache.log4j.Logger;
27
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
28
import org.gvsig.raster.Configuration;
29
import org.gvsig.raster.RasterProcess;
30
import org.gvsig.raster.buffer.BufferFactory;
31
import org.gvsig.raster.buffer.BufferInterpolation;
32
import org.gvsig.raster.buffer.RasterBuffer;
33
import org.gvsig.raster.buffer.WriterBufferServer;
34
import org.gvsig.raster.dataset.GeoRasterWriter;
35
import org.gvsig.raster.dataset.IBuffer;
36
import org.gvsig.raster.dataset.IRasterDataSource;
37
import org.gvsig.raster.dataset.InvalidSetViewException;
38
import org.gvsig.raster.dataset.NotSupportedExtensionException;
39
import org.gvsig.raster.dataset.Params;
40
import org.gvsig.raster.dataset.RasterDataset;
41
import org.gvsig.raster.dataset.io.RasterDriverException;
42
import org.gvsig.raster.dataset.io.rmf.RmfBlocksManager;
43
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
44
import org.gvsig.raster.datastruct.ColorTable;
45
import org.gvsig.raster.datastruct.serializer.ColorTableRmfSerializer;
46
import org.gvsig.raster.datastruct.serializer.NoDataRmfSerializer;
47
import org.gvsig.raster.grid.GridPalette;
48
import org.gvsig.raster.grid.filter.RasterFilterList;
49
import org.gvsig.raster.grid.filter.bands.ColorTableFilter;
50
import org.gvsig.raster.util.RasterNotLoadException;
51
import org.gvsig.raster.util.RasterToolsUtil;
52
import org.gvsig.raster.util.RasterUtilities;
53

    
54
import com.iver.cit.gvsig.fmap.layers.FLayer;
55
/**
56
 * <code>ClippingProcess</code> es un proceso que usa un <code>Thread</code>
57
 * para aplicar un recorte a una capa y guardarlo en disco. Muestra una barra
58
 * de incremento informativa.
59
 *
60
 * @version 24/04/2007
61
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
62
 */
63
public class ClippingProcess extends RasterProcess {
64
        private String                        fileName            = "";
65
        private WriterBufferServer            writerBufferServer  = null;
66
        private FLyrRasterSE                  rasterSE            = null;
67
        private AffineTransform               affineTransform     = new AffineTransform();
68
        private boolean                       oneLayerPerBand     = false;
69
        private int[]                         drawableBands       = { 0, 1, 2 };
70
        private int[]                         dValues             = null;
71
        private GeoRasterWriter               grw                 = null;
72
        private int                           interpolationMethod = BufferInterpolation.INTERPOLATION_Undefined;
73
        private String                        viewName            = "";
74
        private Params                        params              = null;
75
        private DatasetColorInterpretation    colorInterp         = null;
76

    
77
        /**
78
         * Variables de la resoluci?n de salida
79
         */
80
        private int                           resolutionWidth     = 0;
81
        private int                           resolutionHeight    = 0;
82
        
83
        private IBuffer                       buffer              = null;
84

    
85
        /**
86
         * Par?metros obligatorios al proceso:
87
         * <UL>
88
         * <LI>filename: Nombre del fichero de salida</LI>
89
         * <LI>datawriter: Escritor de datos</LI>
90
         * <LI>viewname: Nombre de la vista sobre la que se carga la capa al acabar el proceso</LI>
91
         * <LI>pixelcoordinates: Coordenadas pixel del recorte</LI>
92
         * <LI>layer: Capa de entrada para el recorte</LI>
93
         * <LI>drawablebands: Bandas de entrada</LI>
94
         * <LI>onelayerperband: booleano que informa de si escribimos una banda por fichero de salida o todas en un fichero</LI>
95
         * <LI>interpolationmethod: M?todo de interpolaci?n.</LI>
96
         * <LI>affinetransform: Transformaci?n que informa al dataset de salida de su referencia geografica</LI>
97
         * <LI>resolution: Ancho y alto de la capa de salida</LI>
98
         * </UL> 
99
         */
100
        public void init() {
101
                fileName = getStringParam("filename");
102
                writerBufferServer = (WriterBufferServer) getParam("datawriter");
103
                viewName = getStringParam("viewname");
104
                dValues = getIntArrayParam("pixelcoordinates");
105
                rasterSE = getLayerParam("layer");
106
                drawableBands = getIntArrayParam("drawablebands");
107
                oneLayerPerBand = getBooleanParam("onelayerperband");
108
                interpolationMethod = getIntParam("interpolationmethod");
109
                affineTransform = (AffineTransform)getParam("affinetransform");
110
                colorInterp = (DatasetColorInterpretation)getParam("colorInterpretation");
111
                if(getIntArrayParam("resolution") != null) {
112
                        resolutionWidth = getIntArrayParam("resolution")[0];
113
                        resolutionHeight = getIntArrayParam("resolution")[1];
114
                }
115
                params = (Params) getParam("driverparams");
116
        }
117

    
118
        /**
119
         * Salva la tabla de color al fichero rmf.
120
         * @param fName
121
         * @throws IOException
122
         */
123
        private void saveToRmf(String fileName) {
124
                fileName = RasterUtilities.getNameWithoutExtension(fileName) + ".rmf";
125

    
126
                RasterDataset rds = null;
127
                int limitNumberOfRequests = 20;
128
                while (rds == null && limitNumberOfRequests > 0) {
129
                        try {
130
                                rds = rasterSE.getDataSource().getDataset(0)[0];
131
                        } catch (IndexOutOfBoundsException e) {
132
                                //En ocasiones, sobre todo con servicios remotos al pedir un datasource da una excepci?n de este tipo
133
                                //se supone que es porque hay un refresco en el mismo momento de la petici?n por lo que como es m?s lento de
134
                                //gestionar pilla a la capa sin datasources asociados ya que est? reasignandolo. Si volvemos a pedirlo debe
135
                                //haberlo cargado ya.
136
                                try {
137
                                        Thread.sleep(200);
138
                                } catch (InterruptedException e1) {
139
                                }
140
                        }
141
                        limitNumberOfRequests--;
142
                }
143
                
144
                if (rds == null) {
145
                        //RasterToolsUtil.messageBoxError("error_load_layer", this, new Exception("Error writing RMF. limitNumberOfRequests=" + limitNumberOfRequests));
146
                        return;
147
                }
148
                
149
                RmfBlocksManager manager = rds.getRmfBlocksManager();
150

    
151
                RasterFilterList rasterFilterList = rasterSE.getRenderFilterList();
152

    
153
                manager.setPath(fileName);
154

    
155
                if (!manager.checkRmf())
156
                        return;
157

    
158
                // A?adimos el serializador de NoData
159
                if (Configuration.getValue("nodata_transparency_enabled", Boolean.FALSE).booleanValue()) {
160
                        NoDataRmfSerializer ser = new NoDataRmfSerializer(Double.valueOf(rasterSE.getNoDataValue()));
161
                        manager.addClient(ser);
162
                }
163
                
164
                // A?adimos el serializador para tablas de color
165
                ColorTableFilter colorTableFilter = (ColorTableFilter) rasterFilterList.getByName(ColorTableFilter.names[0]);
166
                if (colorTableFilter != null) {
167
                        GridPalette gridPalette = new GridPalette((ColorTable) colorTableFilter.getColorTable().clone());
168
                        ColorTableRmfSerializer ser = new ColorTableRmfSerializer(gridPalette);
169
                        manager.addClient(ser);
170
                }
171

    
172
                try {
173
                        manager.write(true);
174
                } catch (FileNotFoundException e) {
175
                        RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
176
                } catch (IOException e) {
177
                        RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
178
                }
179

    
180
                manager.deleteAllClients();
181
        }
182

    
183
        /**
184
         * Tarea de recorte
185
         */
186
        public void process() throws InterruptedException {
187
                IRasterDataSource dsetCopy = null;
188
                try {
189
                        long t2;
190
                        long t1 = new java.util.Date().getTime();
191

    
192
                        insertLineLog(RasterToolsUtil.getText(this, "leyendo_raster"));
193

    
194
                        dsetCopy = rasterSE.getDataSource().newDataset();
195
                        BufferFactory bufferFactory = new BufferFactory(dsetCopy);
196
                        bufferFactory.setDrawableBands(drawableBands);
197
        
198
                        if(        interpolationMethod != BufferInterpolation.INTERPOLATION_Undefined &&
199
                                        interpolationMethod != BufferInterpolation.INTERPOLATION_NearestNeighbour) {
200
                                try {
201
                                        if (RasterBuffer.isBufferTooBig(new double[] { dValues[0], dValues[3], dValues[2], dValues[1] }, drawableBands.length))
202
                                                bufferFactory.setReadOnly(true);
203

    
204
                                        bufferFactory.setAreaOfInterest(dValues[0], dValues[3], dValues[2] - dValues[0], dValues[1] - dValues[3]);
205
                                } catch (InvalidSetViewException e) {
206
                                        Logger.getLogger(this.getClass().getName()).debug("No se ha podido asignar la vista al inicial el proceso de recorte.", e);
207
                                }
208
                                buffer = bufferFactory.getRasterBuf();
209

    
210
                                insertLineLog(RasterToolsUtil.getText(this, "interpolando"));
211

    
212
                                buffer = ((RasterBuffer) buffer).getAdjustedWindow(resolutionWidth, resolutionHeight, interpolationMethod);
213
                        } else {
214
                                try {
215
                                        if (RasterBuffer.isBufferTooBig(new double[] { 0, 0, resolutionWidth, resolutionHeight }, drawableBands.length))
216
                                                bufferFactory.setReadOnly(true);
217
                                        bufferFactory.setAreaOfInterest(dValues[0], dValues[3], Math.abs(dValues[2] - dValues[0]), Math.abs(dValues[1] - dValues[3]), resolutionWidth, resolutionHeight);
218
                                        buffer = bufferFactory.getRasterBuf();
219
                                } catch (InvalidSetViewException e) {
220
                                        Logger.getLogger(this.getClass().getName()).debug("No se ha podido asignar la vista al inicial el proceso de recorte.", e);
221
                                }
222
                        }
223
                        //TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
224
                        
225
                        insertLineLog(RasterToolsUtil.getText(this, "salvando_imagen"));
226

    
227
                        String finalFileName = "";
228
                        if (oneLayerPerBand) {
229
                                long[] milis = new long[drawableBands.length];
230
                                String[] fileNames = new String[drawableBands.length];
231
                                for (int i = 0; i < drawableBands.length; i++) {
232
                                        fileNames[i] = fileName + "_B" + drawableBands[i] + ".tif";
233
                                        writerBufferServer.setBuffer(buffer, i);
234
                                        Params p = null;
235
                                        if (params == null)
236
                                                p = GeoRasterWriter.getWriter(fileNames[i]).getParams();
237
                                        else
238
                                                p = params;
239
                                        grw = GeoRasterWriter.getWriter(writerBufferServer, fileNames[i], 1,
240
                                                        affineTransform, buffer.getWidth(), buffer.getHeight(),
241
                                                        buffer.getDataType(), p, null);
242
                                        grw.setColorBandsInterpretation(new String[]{DatasetColorInterpretation.GRAY_BAND});
243
                                        grw.setWkt(dsetCopy.getWktProjection());
244
                                        grw.dataWrite();
245
                                        grw.writeClose();
246
                                        saveToRmf(fileNames[i]);
247
                                        t2 = new java.util.Date().getTime();
248
                                        milis[i] = (t2 - t1);
249
                                        t1 = new java.util.Date().getTime();
250
                                }
251
                                if (incrementableTask != null) {
252
                                        incrementableTask.processFinalize();
253
                                        incrementableTask = null;
254
                                }
255
                                if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) {
256
                                        try {
257
                                                for (int i = 0; i < drawableBands.length; i++) {
258
                                                        FLayer lyr = RasterToolsUtil.loadLayer(viewName, fileNames[i], null);
259
                                                        if(lyr != null && lyr instanceof FLyrRasterSE)
260
                                                                ((FLyrRasterSE)lyr).setRois(rasterSE.getRois());
261
                                                }
262
                                        } catch (RasterNotLoadException e) {
263
                                                RasterToolsUtil.messageBoxError("error_load_layer", this, e);
264
                                        }
265
                                }
266
                                for (int i = 0; i < drawableBands.length; i++) {
267
                                        if (externalActions != null)
268
                                                externalActions.end(new Object[] { fileName, new Long(milis[i]) });
269
                                }
270
                        } else {
271
                                writerBufferServer.setBuffer(buffer, -1);
272
                                if (params == null) {
273
                                        finalFileName = fileName + ".tif";
274
                                        params = GeoRasterWriter.getWriter(finalFileName).getParams();
275
                                } else
276
                                        finalFileName = fileName;
277
                                grw = GeoRasterWriter.getWriter(writerBufferServer, finalFileName,
278
                                                buffer.getBandCount(), affineTransform, buffer.getWidth(),
279
                                                buffer.getHeight(), buffer.getDataType(), params, null);
280
                                if(colorInterp != null)
281
                                        grw.setColorBandsInterpretation(colorInterp.getValues());
282
                                grw.setWkt(dsetCopy.getWktProjection());
283
                                grw.dataWrite();
284
                                grw.writeClose();
285
                                saveToRmf(finalFileName);
286
                                t2 = new java.util.Date().getTime();
287
                                if (incrementableTask != null) {
288
                                        incrementableTask.processFinalize();
289
                                        incrementableTask = null;
290
                                }
291
                                //Damos tiempo a parar el Thread del incrementable para que no se cuelgue la ventana
292
                                //El tiempo es como m?nimo el de un bucle de del run de la tarea incrementable
293
                                Thread.sleep(600);
294
                                cutFinalize(finalFileName, (t2 - t1));
295
                        }
296

    
297
                } catch (NotSupportedExtensionException e) {
298
                        Logger.getLogger(this.getClass().getName()).debug("No se ha podido obtener el writer. Extensi?n no soportada", e);
299
                } catch (RasterDriverException e) {
300
                        Logger.getLogger(this.getClass().getName()).debug("No se ha podido obtener el writer.", e);
301
                } catch (IOException e) {
302
                        Logger.getLogger(this.getClass().getName()).debug("Error en la escritura en GeoRasterWriter.", e);
303
                } finally {
304
                        if (dsetCopy != null)
305
                                dsetCopy.close();
306
                        buffer = null;
307
                }
308
        }
309
        
310
        /**
311
         * Acciones que se realizan al finalizar de crear los recortes de imagen.
312
         * Este m?todo es llamado por el thread TailRasterProcess al finalizar.
313
         */
314
        private void cutFinalize(String fileName, long milis) {
315
                if (!new File(fileName).exists())
316
                        return;
317

    
318
                if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) {
319
                        try {
320
                                FLayer lyr = RasterToolsUtil.loadLayer(viewName, fileName, null);
321
                                if(lyr != null && lyr instanceof FLyrRasterSE)
322
                                        ((FLyrRasterSE)lyr).setRois(rasterSE.getRois());
323
                        } catch (RasterNotLoadException e) {
324
                                RasterToolsUtil.messageBoxError("error_load_layer", this, e);
325
                        }
326
                }
327

    
328
                if (externalActions != null)
329
                        externalActions.end(new Object[]{fileName, new Long(milis)});
330
        }
331

    
332
        /*
333
         * (non-Javadoc)
334
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
335
         */
336
        public int getPercent() {
337
                return (writerBufferServer != null) ? writerBufferServer.getPercent() : 0;
338
        }
339

    
340
        /*
341
         * (non-Javadoc)
342
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
343
         */
344
        public String getTitle() {
345
                return RasterToolsUtil.getText(this, "incremento_recorte");
346
        }
347
}