Statistics
| Revision:

svn-gvsig-desktop / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / clipping / ClippingProcess.java @ 18264

History | View | Annotate | Download (13.6 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.rastertools.clipping;
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.buffer.BufferFactory;
30
import org.gvsig.raster.buffer.BufferInterpolation;
31
import org.gvsig.raster.buffer.RasterBuffer;
32
import org.gvsig.raster.dataset.GeoRasterWriter;
33
import org.gvsig.raster.dataset.IBuffer;
34
import org.gvsig.raster.dataset.IRasterDataSource;
35
import org.gvsig.raster.dataset.InvalidSetViewException;
36
import org.gvsig.raster.dataset.NotSupportedExtensionException;
37
import org.gvsig.raster.dataset.Params;
38
import org.gvsig.raster.dataset.RasterDataset;
39
import org.gvsig.raster.dataset.io.RasterDriverException;
40
import org.gvsig.raster.dataset.io.rmf.RmfBlocksManager;
41
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
42
import org.gvsig.raster.datastruct.ColorTable;
43
import org.gvsig.raster.datastruct.serializer.ColorTableRmfSerializer;
44
import org.gvsig.raster.datastruct.serializer.NoDataRmfSerializer;
45
import org.gvsig.raster.grid.GridPalette;
46
import org.gvsig.raster.grid.filter.RasterFilterList;
47
import org.gvsig.raster.grid.filter.bands.ColorTableFilter;
48
import org.gvsig.raster.util.RasterNotLoadException;
49
import org.gvsig.raster.util.RasterToolsUtil;
50
import org.gvsig.raster.util.RasterUtilities;
51
import org.gvsig.rastertools.RasterProcess;
52
/**
53
 * <code>ClippingProcess</code> es un proceso que usa un <code>Thread</code>
54
 * para calcular el recorte de una capa.
55
 *
56
 * @version 24/04/2007
57
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
58
 */
59
public class ClippingProcess extends RasterProcess {
60
        private String                        fileName            = "";
61
        private WriterBufferServer            writerBufferServer  = null;
62
        private FLyrRasterSE                  rasterSE            = null;
63
        private AffineTransform               affineTransform     = new AffineTransform();
64
        private boolean                       oneLayerPerBand     = false;
65
        private int[]                         drawableBands       = { 0, 1, 2 };
66
        private int[]                         dValues             = null;
67
        private GeoRasterWriter               grw                 = null;
68
        private int                           interpolationMethod = BufferInterpolation.INTERPOLATION_Undefined;
69
        private String                        viewName            = "";
70
        private Params                        params              = null;
71
        private DatasetColorInterpretation    colorInterp         = null;
72

    
73
        /**
74
         * Variables de la resoluci?n de salida
75
         */
76
        private int                           resolutionWidth     = 0;
77
        private int                           resolutionHeight    = 0;
78
        
79
        private IBuffer                       buffer              = null;
80

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

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

    
122
                RasterDataset rds = null;
123
                int limitNumberOfRequests = 20;
124
                while (rds == null && limitNumberOfRequests > 0) {
125
                        try {
126
                                rds = rasterSE.getDataSource().getDataset(0)[0];
127
                        } catch (IndexOutOfBoundsException e) {
128
                                //En ocasiones, sobre todo con servicios remotos al pedir un datasource da una excepci?n de este tipo
129
                                //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
130
                                //gestionar pilla a la capa sin datasources asociados ya que est? reasignandolo. Si volvemos a pedirlo debe
131
                                //haberlo cargado ya.
132
                                try {
133
                                        Thread.sleep(200);
134
                                } catch (InterruptedException e1) {
135
                                }
136
                        }
137
                        limitNumberOfRequests--;
138
                }
139
                
140
                if (rds == null) {
141
                        //RasterToolsUtil.messageBoxError("error_load_layer", this, new Exception("Error writing RMF. limitNumberOfRequests=" + limitNumberOfRequests));
142
                        return;
143
                }
144
                
145
                RmfBlocksManager manager = rds.getRmfBlocksManager();
146

    
147
                RasterFilterList rasterFilterList = rasterSE.getRenderFilterList();
148

    
149
                manager.setPath(fileName);
150

    
151
                if (!manager.checkRmf())
152
                        return;
153

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

    
168
                try {
169
                        manager.write(true);
170
                } catch (FileNotFoundException e) {
171
                        RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
172
                } catch (IOException e) {
173
                        RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
174
                }
175

    
176
                manager.deleteAllClients();
177
        }
178

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

    
188
                        insertLineLog(RasterToolsUtil.getText(this, "leyendo_raster"));
189

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

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

    
206
                                insertLineLog(RasterToolsUtil.getText(this, "interpolando"));
207

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

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

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

    
311
                if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) {
312
                        try {
313
                                RasterToolsUtil.loadLayer(viewName, fileName, null);
314
                        } catch (RasterNotLoadException e) {
315
                                RasterToolsUtil.messageBoxError("error_load_layer", this, e);
316
                        }
317
                }
318

    
319
                if (externalActions != null)
320
                        externalActions.end(new Object[]{fileName, new Long(milis)});
321
        }
322

    
323
        /*
324
         * (non-Javadoc)
325
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
326
         */
327
        public int getPercent() {
328
                return (writerBufferServer != null) ? writerBufferServer.getPercent() : 0;
329
        }
330

    
331
        /*
332
         * (non-Javadoc)
333
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
334
         */
335
        public String getTitle() {
336
                return RasterToolsUtil.getText(this, "incremento_recorte");
337
        }
338
}