001    //$HeadURL: svn+ssh://rbezema@svn.wald.intevation.org/deegree/base/branches/2.2_testing/src/org/deegree/model/coverage/grid/ShortGridCoverage.java $
002    /*----------------    FILE HEADER  ------------------------------------------
003    
004     This file is part of deegree.
005     Copyright (C) 2001-2008 by:
006     EXSE, Department of Geography, University of Bonn
007     http://www.giub.uni-bonn.de/deegree/
008     lat/lon GmbH
009     http://www.lat-lon.de
010    
011     This library is free software; you can redistribute it and/or
012     modify it under the terms of the GNU Lesser General Public
013     License as published by the Free Software Foundation; either
014     version 2.1 of the License, or (at your option) any later version.
015    
016     This library is distributed in the hope that it will be useful,
017     but WITHOUT ANY WARRANTY; without even the implied warranty of
018     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
019     Lesser General Public License for more details.
020    
021     You should have received a copy of the GNU Lesser General Public
022     License along with this library; if not, write to the Free Software
023     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
024    
025     Contact:
026    
027     Andreas Poth
028     lat/lon GmbH
029     Aennchenstr. 19
030     53115 Bonn
031     Germany
032     E-Mail: poth@lat-lon.de
033    
034     Klaus Greve
035     Department of Geography
036     University of Bonn
037     Meckenheimer Allee 166
038     53115 Bonn
039     Germany
040     E-Mail: klaus.greve@uni-bonn.de
041    
042     
043     ---------------------------------------------------------------------------*/
044    package org.deegree.model.coverage.grid;
045    
046    import java.awt.Rectangle;
047    import java.awt.color.ColorSpace;
048    import java.awt.image.BandedSampleModel;
049    import java.awt.image.BufferedImage;
050    import java.awt.image.ComponentColorModel;
051    import java.awt.image.DataBuffer;
052    import java.awt.image.DataBufferShort;
053    import java.awt.image.Raster;
054    import java.awt.image.SampleModel;
055    import java.awt.image.WritableRaster;
056    import java.awt.image.renderable.RenderableImage;
057    import java.util.Hashtable;
058    
059    import org.deegree.model.spatialschema.Envelope;
060    import org.deegree.model.spatialschema.GeometryFactory;
061    import org.deegree.ogcwebservices.wcs.describecoverage.CoverageOffering;
062    import org.deegree.processing.raster.converter.RawData2Image;
063    import org.opengis.pt.PT_Envelope;
064    
065    /**
066     * GridCoverage implementation for holding grids stored in a raw byte matrix (byte[][]) or in a set
067     * of <tt>ByteGridCoverage</tt>s
068     * 
069     * @version $Revision: 9343 $
070     * @author <a href="mailto:poth@lat-lon.de">Andreas Poth</a>
071     * @author last edited by: $Author: apoth $
072     * 
073     * @version $Revision: 9343 $, $Date: 2007-12-27 14:30:32 +0100 (Do, 27 Dez 2007) $
074     */
075    public class ShortGridCoverage extends AbstractGridCoverage {
076    
077        private static final long serialVersionUID = -2073045348804541362L;
078    
079        private short[][][] data = null;
080    
081        /**
082         * @param coverageOffering
083         * @param envelope
084         * @param data
085         */
086        public ShortGridCoverage( CoverageOffering coverageOffering, Envelope envelope, short[][][] data ) {
087            this( coverageOffering, envelope, false, data );
088        }
089    
090        /**
091         * @param coverageOffering
092         * @param envelope
093         * @param isEditable
094         * @param data
095         */
096        public ShortGridCoverage( CoverageOffering coverageOffering, Envelope envelope, boolean isEditable, short[][][] data ) {
097            super( coverageOffering, envelope, isEditable );
098            this.data = data;
099        }
100    
101        /**
102         * @param coverageOffering
103         * @param envelope
104         * @param sources
105         */
106        public ShortGridCoverage( CoverageOffering coverageOffering, Envelope envelope, ShortGridCoverage[] sources ) {
107            super( coverageOffering, envelope, sources );
108        }
109    
110        /**
111         * The number of sample dimensions in the coverage. For grid coverages, a sample dimension is a
112         * band.
113         * 
114         * @return The number of sample dimensions in the coverage.
115         * @UML mandatory numSampleDimensions
116         */
117        public int getNumSampleDimensions() {
118            if ( data != null ) {
119                return data.length;
120            }
121            return sources[0].getNumSampleDimensions();
122        }
123    
124        /**
125         * Returns 2D view of this coverage as a renderable image. This optional operation allows
126         * interoperability with <A HREF="http://java.sun.com/products/java-media/2D/">Java2D</A>. If
127         * this coverage is a {@link "org.opengis.coverage.grid.GridCoverage"} backed by a
128         * {@link java.awt.image.RenderedImage}, the underlying image can be obtained with:
129         * 
130         * <code>getRenderableImage(0,1).{@linkplain RenderableImage#createDefaultRendering()
131         * createDefaultRendering()}</code>
132         * 
133         * @param xAxis
134         *            Dimension to use for the <var>x</var> axis.
135         * @param yAxis
136         *            Dimension to use for the <var>y</var> axis.
137         * @return A 2D view of this coverage as a renderable image.
138         * @throws UnsupportedOperationException
139         *             if this optional operation is not supported.
140         * @throws IndexOutOfBoundsException
141         *             if <code>xAxis</code> or <code>yAxis</code> is out of bounds.
142         */
143        public RenderableImage getRenderableImage( int xAxis, int yAxis )
144                                throws UnsupportedOperationException, IndexOutOfBoundsException {
145            if ( data != null ) {
146    
147                return null;
148            }
149            // TODO if multi images -> sources.length > 0
150            return null;
151        }
152    
153        /**
154         * this is a deegree convenience method which returns the source image of an
155         * <tt>ImageGridCoverage</tt>. In procipal the same can be done with the
156         * getRenderableImage(int xAxis, int yAxis) method. but creating a <tt>RenderableImage</tt>
157         * image is very slow. I xAxis or yAxis <= 0 then the size of the returned image will be
158         * calculated from the source images of the coverage.
159         * 
160         * @param xAxis
161         *            Dimension to use for the <var>x</var> axis.
162         * @param yAxis
163         *            Dimension to use for the <var>y</var> axis.
164         * @return the source image of an <tt>ImageGridCoverage</tt>.
165         */
166        public BufferedImage getAsImage( int xAxis, int yAxis ) {
167    
168            if ( xAxis <= 0 || yAxis <= 0 ) {
169                // get default size if passed target size is <= 0
170                Rectangle rect = calculateOriginalSize();
171                xAxis = rect.width;
172                yAxis = rect.height;
173            }
174            BufferedImage bi = null;
175            if ( data != null ) {
176    
177                bi = createBufferedImage( data[0][0].length, data[0].length );
178                // total number of fields for one band; it is assumed that each
179                // band has the same number of fiels
180                int numOfFields = data[0].length * data[0][0].length;
181                short[][] bb = new short[data.length][];
182                for ( int z = 0; z < data.length; z++ ) {
183                    bb[z] = new short[numOfFields];
184                }
185                int c = 0;
186                for ( int i = 0; i < data[0].length; i++ ) {
187                    for ( int j = 0; j < data[0][i].length; j++ ) {
188                        for ( int z = 0; z < data.length; z++ ) {
189                            bb[z][c] = data[z][i][j];
190                        }
191                        c++;
192                    }
193                }
194                DataBuffer db = new DataBufferShort( bb, numOfFields );
195                SampleModel sm = new BandedSampleModel( DataBuffer.TYPE_USHORT, data[0][0].length, data[0].length,
196                                                        data.length );
197                Raster raster = Raster.createWritableRaster( sm, db, null );
198                bi.setData( raster );
199            } else {
200                bi = createBufferedImage( xAxis, yAxis );
201                int targetPs = bi.getColorModel().getPixelSize();
202                float[][] data = null;
203                if ( targetPs == 16 ) {
204                    // do not use image api if target bitDepth = 16
205                    data = new float[bi.getHeight()][bi.getWidth()];
206                }
207                // it's a complex ImageGridCoverage made up of different
208                // source coverages
209                for ( int i = 0; i < sources.length; i++ ) {
210                    PT_Envelope env = sources[i].getEnvelope();
211                    Envelope sourceEnv = GeometryFactory.createEnvelope( env.minCP.ord[0], env.minCP.ord[1],
212                                                                         env.maxCP.ord[0], env.maxCP.ord[1], null );
213                    env = this.getEnvelope();
214                    Envelope targetEnv = GeometryFactory.createEnvelope( env.minCP.ord[0], env.minCP.ord[1],
215                                                                         env.maxCP.ord[0], env.maxCP.ord[1], null );
216    
217                    BufferedImage sourceImg = ( (AbstractGridCoverage) sources[i] ).getAsImage( -1, -1 );
218                    bi = paintImage( bi, data, targetEnv, sourceImg, sourceEnv );
219                }
220                if ( targetPs == 16 ) {
221                    bi = RawData2Image.rawData2Image( data, false, scaleFactor, offset );
222                }
223            }
224    
225            return bi;
226        }
227    
228        /**
229         * 
230         * @param xAxis
231         * @param yAxis
232         * @return
233         */
234        private BufferedImage createBufferedImage( int xAxis, int yAxis ) {
235            BufferedImage bi = null;
236            int sampleDim = getNumSampleDimensions();
237            switch ( sampleDim ) {
238            case 1: {
239                ColorSpace cs = ColorSpace.getInstance( ColorSpace.CS_GRAY );
240                ComponentColorModel ccm = new ComponentColorModel( cs, null, false, false, BufferedImage.OPAQUE,
241                                                                   DataBuffer.TYPE_USHORT );
242                WritableRaster wr = ccm.createCompatibleWritableRaster( xAxis, yAxis );
243    
244                bi = new BufferedImage( ccm, wr, false, new Hashtable() );
245            }
246            }
247            return bi;
248        }
249    
250        /**
251         * calculates the original size of a gridcoverage based on its resolution and the envelope(s) of
252         * its source(s).
253         * 
254         * @return
255         */
256        private Rectangle calculateOriginalSize() {
257    
258            if ( data != null ) {
259                return new Rectangle( data[0][0].length, data[0].length );
260            }
261            BufferedImage bi = ( (ShortGridCoverage) sources[0] ).getAsImage( -1, -1 );
262            PT_Envelope env = sources[0].getEnvelope();
263            double dx = ( env.maxCP.ord[0] - env.minCP.ord[0] ) / bi.getWidth();
264            double dy = ( env.maxCP.ord[1] - env.minCP.ord[1] ) / bi.getHeight();
265    
266            env = this.getEnvelope();
267            int w = (int) Math.round( ( env.maxCP.ord[0] - env.minCP.ord[0] ) / dx );
268            int h = (int) Math.round( ( env.maxCP.ord[1] - env.minCP.ord[1] ) / dy );
269            return new Rectangle( w, h );
270        }
271    }