Statistics
| Revision:

gvsig-raster / org.gvsig.raster / branches / org.gvsig.raster_dataaccess_refactoring / org.gvsig.raster.lib / org.gvsig.raster.lib.api / src / main / java / org / gvsig / fmap / dal / coverage / grid / filter / BaseRasterFilter.java @ 2328

History | View | Annotate | Download (13.7 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.fmap.dal.coverage.grid.filter;
23

    
24
import java.util.Hashtable;
25
import java.util.TreeMap;
26

    
27
import org.gvsig.fmap.dal.coverage.RasterLocator;
28
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
29
import org.gvsig.fmap.dal.coverage.dataset.BufferParam;
30
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
31
import org.gvsig.fmap.dal.coverage.datastruct.Params;
32
import org.gvsig.fmap.dal.coverage.exception.BufferCreationException;
33
import org.gvsig.fmap.dal.coverage.exception.FilterAddException;
34
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
35
import org.gvsig.fmap.dal.coverage.grid.RasterFilter;
36
import org.gvsig.fmap.dal.coverage.process.TaskEventManager;
37
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
38
import org.gvsig.fmap.dal.coverage.store.props.Transparency;
39
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
40
import org.gvsig.tools.locator.LocatorException;
41

    
42
/**
43
 * Base class for all filters
44
 *
45
 * @author Nacho Brodin (nachobrodin@gmail.com)
46
 */
47
public abstract class BaseRasterFilter implements RasterFilter, Cloneable {
48
        public static final String PERSISTENT_NAME        = "BaseRasterFilter";
49
    public static final String PERSISTENT_DESCRIPTION = "BaseRasterFilter Persistent";
50
        protected Buffer           raster                 = null;
51
        protected Buffer           rasterResult           = null;
52
        protected int              height                 = 0;
53
        protected int              width                  = 0;
54
        protected Hashtable<String, Object> 
55
                                   params                 = new Hashtable<String, Object>();
56
        protected TreeMap<String, Object>   
57
                                   environment            = new TreeMap<String, Object>();
58
        protected Extent           extent                 = null;
59
        private int                percent                = 0;
60
        private String             fName                  = "";
61
        /**
62
         * Variable que control la aplicaci?n o no del filtro. Si est? a false aunque est? en
63
         * la pila el filtro no se ejecutar?.
64
         */
65
        protected boolean           exec                  = true;
66
        protected RasterUtils       util                  = null;
67
        protected TaskEventManager  taskEventManager      = null;
68
        protected String            managername           = null;
69
        protected Transparency      transparency          = null;
70
        
71
        private boolean             hasInputTransparency       = false;
72
        protected int               nBandsToProcess       = 0;
73
        protected ColorInterpretation 
74
                                    colorInterpretation   = null;
75
        private boolean             argbOutput            = false;
76

    
77
        /**
78
         * Constructor
79
         */
80
        public BaseRasterFilter() {
81
                if(RasterLocator.getManager() != null)
82
                        util = RasterLocator.getManager().getRasterUtils();
83
        }
84

    
85
        /**
86
         * Aplica el filtro sobre el raster pasado pixel a pixel
87
         * @throws ProcessInterruptedException
88
         * @throws FilterAddException 
89
         */
90
        public void execute() throws ProcessInterruptedException, FilterAddException {
91
                taskEventManager = RasterLocator.getManager().createRasterTask(this);
92
                pre();
93
                if (raster != null && raster.getDataType() != this.getInRasterDataType())
94
                        exec = false;
95
                percent = 0;
96
                if (exec)
97
                        for (int row = 0; row < height; row ++) {
98
                                for (int col = 0; col < width; col ++)
99
                                        try {
100
                                                process(col, row);
101
                                        }catch (ArrayIndexOutOfBoundsException e) {
102
                                        }
103

    
104
                                if (taskEventManager.getEvent() != null)
105
                                        taskEventManager.manageEvent(taskEventManager.getEvent());
106

    
107
                                percent = (row * 100) / height;
108
                        }
109
                percent = 100;
110
                post();
111
        }
112

    
113
        /**
114
         * A?ade un par?metro al filtro
115
         *
116
         * @param name Clave del par?metro
117
         * @param param Objeto pasado como par?metro
118
         */
119
        public void addParam(String name, Object param) {
120
                if (param != null)
121
                        params.put(name, param);
122
                else
123
                        params.remove(name);
124
        }
125

    
126
        /**
127
         * Elimina un par?metro del filtro
128
         * @param name Clave del par?metro a eliminar
129
         */
130
        public void removeParam(String name) {
131
                params.remove(name);
132
        }
133

    
134
        /**
135
         * Obtiene un par?metro a partir de la clave
136
         * @param name Par?metro
137
         * @return Par?metro
138
         */
139
        public Object getParam(String name) {
140
                return params.get(name);
141
        }
142

    
143
        public Hashtable<String, Object> getParams() {
144
                return params;
145
        }
146

    
147
        public void setParams(Hashtable<String, Object> params) {
148
                this.params = params;
149
        }
150

    
151
        public void setExtent(Extent extent) {
152
                this.extent = extent;
153
        }
154

    
155
        /**
156
         * Obtiene true si el filtro va a ser ejecutado o false si no va a serlo
157
         * @return
158
         */
159
        public boolean isExec() {
160
                return exec;
161
        }
162

    
163
        /**
164
         * Asigna el valor a la variable exec. Esta estar? a true si el filtro se ejecutar? la pr?xima
165
         * vez que se repinte o false si no se ejecuta.
166
         * @param exec
167
         */
168
        public void setExec(boolean exec) {
169
                this.exec = exec;
170
        }
171

    
172
        /**
173
         * Pone a cero el contador del porcentaje del proceso de filtrado
174
         * @return
175
         */
176
        public void resetPercent() {
177
                percent = 0;
178
        }
179

    
180
        /**
181
         * Obtiene el porcentaje recorrido del proceso de filtrado
182
         * @return
183
         */
184
        public int getPercent() {
185
                return percent;
186
        }
187
        
188
        /*public int[] getRenderBands() {
189
                return renderBands;
190
        }*/
191

    
192
        /**
193
         * Funci?n que contiene el c?digo a ejecutar despues de aplicar el filtro
194
         */
195
        abstract public void post();
196

    
197
        /**
198
         * Ejecuci?n del filtro para un pixel de la imagen
199
         */
200
        abstract public void process(int x, int y);
201

    
202
        /**
203
         * Obtiene el tipo de datos del raster de entrada
204
         */
205
        abstract public int getInRasterDataType();
206

    
207
        /**
208
         * Obtiene el tipo de datos del raster de salida
209
         */
210
        abstract public int getOutRasterDataType();
211

    
212
        /**
213
         * Gets the result of this filter
214
         */
215
        public Object getResult(String name) {
216
                if (name.equals(RESULT_BUFFER)) {
217
                        if (exec)
218
                                return (Object) this.rasterResult;
219
                        else
220
                                return (Object) this.raster;
221
                }
222

    
223
                if (name.equals(RESULT_TRANSPARENCY)) {
224
                        if(transparency == null)
225
                                return null;
226
                        ColorInterpretation ci = null;
227
                        if(rasterResult.getDataType() == Buffer.TYPE_BYTE) {
228
                                if(argbOutput || (rasterResult.getBandCount() == 4 && hasInputTransparency())) {
229
                                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
230
                                                        new String[]{ColorInterpretation.RED_BAND,
231
                                                                        ColorInterpretation.GREEN_BAND,
232
                                                                        ColorInterpretation.BLUE_BAND,
233
                                                                        ColorInterpretation.ALPHA_BAND});
234
                                        transparency.setColorInterpretation(ci);
235
                                        transparency.activeTransparency();
236
                                        return transparency;
237
                                } else if(rasterResult.getBandCount() == 3) {
238
                                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
239
                                                        new String[]{ColorInterpretation.RED_BAND,
240
                                                                        ColorInterpretation.GREEN_BAND,
241
                                                                        ColorInterpretation.BLUE_BAND});
242
                                        transparency.setColorInterpretation(ci);
243
                                        transparency.activeTransparency();
244
                                        return transparency;
245
                                } else if(rasterResult.getBandCount() == 1) {
246
                                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
247
                                                        new String[]{ColorInterpretation.GRAY_BAND});
248
                                        transparency.setColorInterpretation(ci);
249
                                        transparency.activeTransparency();
250
                                        return transparency;
251
                                }
252
                                /*else if(rasterResult.getBandCount() == 3 && renderBands != null && renderBands.length >=3) {
253
                                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(renderBands);
254
                                        transparency.setColorInterpretation(ci);
255
                                        transparency.activeTransparency();
256
                                        return transparency;
257
                                }*/
258
                        } 
259
                        String[] values = new String[rasterResult.getBandCount()];
260
                        for (int i = 0; i < values.length; i++) {
261
                                values[i] = ColorInterpretation.UNDEF_BAND;
262
                        }
263
                        ci = RasterLocator.getManager().getDataStructFactory().createColorInterpretation(values);
264
                        transparency.setColorInterpretation(ci);
265
                        transparency.activeTransparency();
266
                        return transparency;
267
                }
268
                return null;
269
        }
270
        
271
        abstract public String getGroup();
272
        abstract public Params getUIParams(String nameFilter);
273
        abstract public String[] getNames();
274

    
275
        public boolean isVisible() {
276
                return true;
277
        }
278

    
279
        public Object clone() throws CloneNotSupportedException {
280
                return super.clone();
281
        }
282

    
283
        public String getName() {
284
                return fName;
285
        }
286

    
287
        public void setName(String name) {
288
                fName = name;
289
        }
290

    
291
        public TreeMap<String, Object> getEnv() {
292
                return environment;
293
        }
294

    
295
        public void setEnv(TreeMap<String, Object> env) {
296
                this.environment = env;
297
        }
298

    
299
        public String getManagerName() {
300
                return managername;
301
        }
302

    
303
        /**
304
         * Releases buffer resources
305
         */
306
        public void dispose() {
307
                
308
        }
309
        
310
        protected Buffer getOutputBuffer() {
311
                return rasterResult;
312
        }
313
        
314
        protected Buffer getInputBuffer() {
315
                return raster;
316
        }
317
        
318
        protected void finalize() throws Throwable {
319
                rasterResult = null;
320
                raster = null;
321
                extent = null;
322
                fName = null;
323
                super.finalize();
324
        }
325

    
326
        /**
327
         * Code to execute before apply a filter
328
         */
329
        public void pre() throws FilterAddException {
330
                exec = true;
331
                raster = (Buffer) params.get("raster");
332
                //renderBands = (int[]) params.get("renderBands");
333
                transparency = (Transparency)environment.get("Transparency");
334
                height = raster.getHeight();
335
                width = raster.getWidth();
336
                
337
                //?til para imagenes de tipo byte que puedan traer transparencia
338
                if(        raster != null && 
339
                        transparency != null && 
340
                        raster.getDataType() == Buffer.TYPE_BYTE &&
341
                        transparency.existAlphaBand()) {
342
                        nBandsToProcess = raster.getBandCount() - 1;
343
                        hasInputTransparency = true;
344
                } else
345
                        nBandsToProcess = raster.getBandCount();
346
        }
347
        
348
        //*****************************************
349
        //Support methods
350
        //*****************************************
351
        
352
        protected void createARGBBufferResult() throws FilterAddException {
353
                BufferParam param = RasterLocator.getManager().getBufferFactory().createBufferParams(width, height, 4, Buffer.TYPE_BYTE, true);
354
                try {
355
                        rasterResult = RasterLocator.getManager().getBufferFactory().createBuffer(param);
356
                        if(raster != null)
357
                                rasterResult.setDataExtent(raster.getDataExtent());
358
                        argbOutput = true;
359
                } catch (LocatorException e) {
360
                        throw new FilterAddException("Error creating buffer", e);
361
                } catch (BufferCreationException e) {
362
                        throw new FilterAddException("Error creating buffer", e);
363
                }
364
        }
365
        
366
        protected void createBufferResult(int dataType, int bandCount) throws FilterAddException {
367
                BufferParam param = RasterLocator.getManager().getBufferFactory().createBufferParams(width, height, bandCount, dataType, true);
368
                try {
369
                        rasterResult = RasterLocator.getManager().getBufferFactory().createBuffer(param);
370
                        if(raster != null)
371
                                rasterResult.setDataExtent(raster.getDataExtent());
372
                } catch (LocatorException e) {
373
                        throw new FilterAddException("Error creating buffer", e);
374
                } catch (BufferCreationException e) {
375
                        throw new FilterAddException("Error creating buffer", e);
376
                }
377
        }
378
        
379
        /**
380
         * Checks the renderBands array for RGB inputs. If it is not good, 
381
         * it will be calculated. This function will have into account the 
382
         * transparency object to render the alpha band
383
         */
384
        /*protected void checkRGBRenderBands() {
385
                for (int i = 0; i < renderBands.length; i++) {
386
                        if(renderBands[i] >= raster.getBandCount())
387
                                renderBands[i] = -1;
388
                }
389
                
390
                //Necesita 3 bandas para renderizar, ya que la entrada debe ser un valor RGB
391
                int countBandsToDraw = 0;
392
                for (int i = 0; i < renderBands.length; i++) {
393
                        if(renderBands[i] >= 0 && renderBands[i] < 3)
394
                                countBandsToDraw ++;
395
                }
396
                //Si no tiene al menos 3 bandas de entrada calculamos el renderBands
397
                if(renderBands == null || countBandsToDraw < 3) {
398
                        switch (raster.getBandCount()) {
399
                        case 1:renderBands = new int[]{0, 0, 0}; break;
400
                        case 2:renderBands = new int[]{0, 1, 1}; break;
401
                        case 3:renderBands = new int[]{0, 1, 2}; break;
402
                        default:
403
                                if(transparency.existAlphaBand())
404
                                        renderBands = new int[]{0, 1, 2, 3}; 
405
                                else
406
                                        renderBands = new int[]{0, 1, 2};
407
                        }
408
                }
409
        }*/
410
        
411
        /**
412
         * Copies the alpha band from the input raster to the output.
413
         * In most filters, this band is not processed and it will copy
414
         * it directly in the output
415
         */
416
        protected void writeAlphaBand(int line, int col) {
417
                if(hasInputTransparency)  {
418
                        rasterResult.setElem(line, col, rasterResult.getBandCount() - 1, 
419
                                        raster.getElemByte(line, col, raster.getBandCount() - 1));
420
                }
421
        }
422
        
423
        protected boolean hasInputTransparency() {
424
                return hasInputTransparency;
425
        }
426
        
427
        protected int numberOfBandsToProcess() {
428
                return nBandsToProcess;
429
        }
430
        
431
        protected ColorInterpretation getColorInterpretation() {
432
                if(transparency != null)
433
                        return transparency.getColorInterpretation();
434
                
435
                if(raster.getBandCount() >= 4)
436
                        return RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
437
                                        new String[]{ColorInterpretation.RED_BAND,
438
                                                ColorInterpretation.GREEN_BAND,
439
                                                ColorInterpretation.BLUE_BAND,
440
                                                ColorInterpretation.ALPHA_BAND});
441
                else if(raster.getBandCount() == 3)
442
                        return RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
443
                                        new String[]{ColorInterpretation.RED_BAND,
444
                                                        ColorInterpretation.GREEN_BAND,
445
                                                        ColorInterpretation.BLUE_BAND});
446
                else return RasterLocator.getManager().getDataStructFactory().createColorInterpretation(
447
                                new String[]{ColorInterpretation.GRAY_BAND});
448
        }
449
}