Example usage for java.awt.geom AffineTransform AffineTransform

List of usage examples for java.awt.geom AffineTransform AffineTransform

Introduction

In this page you can find the example usage for java.awt.geom AffineTransform AffineTransform.

Prototype

public AffineTransform(double[] flatmatrix) 

Source Link

Document

Constructs a new AffineTransform from an array of double precision values representing either the 4 non-translation entries or the 6 specifiable entries of the 3x3 transformation matrix.

Usage

From source file:org.geotools.gce.imagemosaic.RasterLayerResponse.java

/**
 * This method loads the granules which overlap the requested
 * {@link GeneralEnvelope} using the provided values for alpha and input
 * ROI.//from ww w .  j  a  v  a2 s  .  co  m
 * @return
 * @throws DataSourceException
 */
private RenderedImage prepareResponse() throws DataSourceException {

    try {

        //
        // prepare the params for executing a mosaic operation.
        //
        // It might important to set the mosaic type to blend otherwise
        // sometimes strange results jump in.

        // select the relevant overview, notice that at this time we have
        // relaxed a bit the requirement to have the same exact resolution
        // for all the overviews, but still we do not allow for reading the
        // various grid to world transform directly from the input files,
        // therefore we are assuming that each granuleDescriptor has a scale and
        // translate only grid to world that can be deduced from its base
        // level dimension and envelope. The grid to world transforms for
        // the other levels can be computed accordingly knowing the scale
        // factors.
        if (request.getRequestedBBox() != null && request.getRequestedRasterArea() != null
                && !request.isHeterogeneousGranules())
            imageChoice = ReadParamsController.setReadParams(request.getRequestedResolution(),
                    request.getOverviewPolicy(), request.getDecimationPolicy(), baseReadParameters,
                    request.rasterManager, request.rasterManager.overviewsController); // use general overviews controller
        else
            imageChoice = 0;
        assert imageChoice >= 0;
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine(new StringBuffer("Loading level ").append(imageChoice)
                    .append(" with subsampling factors ").append(baseReadParameters.getSourceXSubsampling())
                    .append(" ").append(baseReadParameters.getSourceYSubsampling()).toString());

        // ok we got something to return, let's load records from the index
        final BoundingBox cropBBOX = request.getCropBBox();
        if (cropBBOX != null)
            mosaicBBox = ReferencedEnvelope.reference(cropBBOX);
        else
            mosaicBBox = new ReferencedEnvelope(coverageEnvelope);

        //compute final world to grid
        // base grid to world for the center of pixels
        final AffineTransform g2w;
        final OverviewLevel baseLevel = rasterManager.overviewsController.resolutionsLevels.get(0);
        final OverviewLevel selectedLevel = rasterManager.overviewsController.resolutionsLevels
                .get(imageChoice);
        final double resX = baseLevel.resolutionX;
        final double resY = baseLevel.resolutionY;
        final double[] requestRes = request.getRequestedResolution();

        g2w = new AffineTransform((AffineTransform) baseGridToWorld);
        g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);

        if ((requestRes[0] < resX || requestRes[1] < resY)) {
            // Using the best available resolution
            oversampledRequest = true;
        } else {

            // SG going back to working on a per level basis to do the composition
            // g2w = new AffineTransform(request.getRequestedGridToWorld());
            g2w.concatenate(
                    AffineTransform.getScaleInstance(selectedLevel.scaleFactor, selectedLevel.scaleFactor));
            g2w.concatenate(AffineTransform.getScaleInstance(baseReadParameters.getSourceXSubsampling(),
                    baseReadParameters.getSourceYSubsampling()));
        }

        // move it to the corner
        finalGridToWorldCorner = new AffineTransform2D(g2w);
        finalWorldToGridCorner = finalGridToWorldCorner.inverse();// compute raster bounds
        final GeneralEnvelope tempRasterBounds = CRS.transform(finalWorldToGridCorner, mosaicBBox);
        rasterBounds = tempRasterBounds.toRectangle2D().getBounds();

        //          SG using the above may lead to problems since the reason is that  may be a little (1 px) bigger
        //          than what we need. The code below is a bit better since it uses a proper logic (see GridEnvelope
        //          Javadoc)
        //         rasterBounds = new GridEnvelope2D(new Envelope2D(tempRasterBounds), PixelInCell.CELL_CORNER);
        if (rasterBounds.width == 0)
            rasterBounds.width++;
        if (rasterBounds.height == 0)
            rasterBounds.height++;
        if (oversampledRequest)
            rasterBounds.grow(2, 2);

        // make sure we do not go beyond the raster dimensions for this layer
        final GeneralEnvelope levelRasterArea_ = CRS.transform(finalWorldToGridCorner,
                rasterManager.spatialDomainManager.coverageBBox);
        final GridEnvelope2D levelRasterArea = new GridEnvelope2D(new Envelope2D(levelRasterArea_),
                PixelInCell.CELL_CORNER);
        XRectangle2D.intersect(levelRasterArea, rasterBounds, rasterBounds);

        // create the index visitor and visit the feature
        final MosaicBuilder visitor = new MosaicBuilder(request);
        final List times = request.getRequestedTimes();
        final List elevations = request.getElevation();
        final Map<String, List> additionalDomains = request.getRequestedAdditionalDomains();
        final Filter filter = request.getFilter();
        final boolean hasTime = (times != null && times.size() > 0);
        final boolean hasElevation = (elevations != null && elevations.size() > 0);
        final boolean hasAdditionalDomains = additionalDomains.size() > 0;
        final boolean hasFilter = filter != null && !Filter.INCLUDE.equals(filter);

        // create query
        final SimpleFeatureType type = rasterManager.granuleCatalog.getType();
        Query query = null;
        Filter bbox = null;
        if (type != null) {
            query = new Query(rasterManager.granuleCatalog.getType().getTypeName());
            bbox = FeatureUtilities.DEFAULT_FILTER_FACTORY.bbox(
                    FeatureUtilities.DEFAULT_FILTER_FACTORY
                            .property(rasterManager.granuleCatalog.getType().getGeometryDescriptor().getName()),
                    mosaicBBox);
            query.setFilter(bbox);
        } else {
            throw new IllegalStateException("GranuleCatalog feature type was null!!!");
        }

        // prepare eventual filter for filtering granules
        // handle elevation indexing first since we then combine this with the max in case we are asking for current in time
        if (hasElevation) {

            final Filter elevationF = rasterManager.parent.elevationDomainManager
                    .createFilter(ImageMosaicReader.ELEVATION_DOMAIN, elevations);
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), elevationF));
        }

        // handle generic filter since we then combine this with the max in case we are asking for current in time
        if (hasFilter) {
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), filter));
        }

        // fuse time query with the bbox query
        if (hasTime) {
            final Filter timeFilter = this.rasterManager.parent.timeDomainManager
                    .createFilter(ImageMosaicReader.TIME_DOMAIN, times);
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), timeFilter));
        }

        if (hasAdditionalDomains) {
            final List<Filter> additionalFilter = new ArrayList<Filter>();
            for (Entry<String, List> entry : additionalDomains.entrySet()) {

                // build a filter for each dimension
                final String domainName = entry.getKey() + DomainDescriptor.DOMAIN_SUFFIX;
                additionalFilter.add(
                        rasterManager.parent.domainsManager.createFilter(domainName, (List) entry.getValue()));

            }
            // merge with existing ones
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(),
                    FeatureUtilities.DEFAULT_FILTER_FACTORY.and(additionalFilter)));
        }

        //
        // handle secondary query parameters
        //

        // max number of elements
        if (request.getMaximumNumberOfGranules() > 0) {
            query.setMaxFeatures(request.getMaximumNumberOfGranules());
        }

        // sort by clause
        final String sortByClause = request.getSortClause();
        if (sortByClause != null && sortByClause.length() > 0) {
            final String[] elements = sortByClause.split(",");
            if (elements != null && elements.length > 0) {
                final List<SortBy> clauses = new ArrayList<SortBy>(elements.length);
                for (String element : elements) {
                    // check
                    if (element == null || element.length() <= 0) {
                        continue;// next, please!
                    }
                    try {
                        // which clause?
                        // ASCENDING
                        element = element.trim();
                        if (element.endsWith(Utils.ASCENDING_ORDER_IDENTIFIER)) {
                            String attribute = element.substring(0, element.length() - 2);
                            clauses.add(
                                    new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),
                                            SortOrder.ASCENDING));
                        } else
                        // DESCENDING
                        if (element.contains(Utils.DESCENDING_ORDER_IDENTIFIER)) {
                            String attribute = element.substring(0, element.length() - 2);
                            clauses.add(
                                    new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),
                                            SortOrder.DESCENDING));
                        }
                        //                        if(element.startsWith(Utils.ASCENDING_ORDER_IDENTIFIER)){
                        //                           String attribute=element.substring(Utils.ASCENDING_ORDER_IDENTIFIER.length()+1);
                        //                           attribute=attribute.substring(0, attribute.length()-1);
                        //                           clauses.add(new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),SortOrder.ASCENDING));
                        //                        } else 
                        //                           // DESCENDING
                        //                           if(element.startsWith(Utils.DESCENDING_ORDER_IDENTIFIER)){
                        //                               String attribute=element.substring(Utils.DESCENDING_ORDER_IDENTIFIER.length()+1);
                        //                               attribute=attribute.substring(0, attribute.length()-1);
                        //                               clauses.add(new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),SortOrder.DESCENDING));
                        //                        } else {
                        else {
                            if (LOGGER.isLoggable(Level.FINE)) {
                                LOGGER.fine("Ignoring sort clause :" + element);
                            }
                        }
                    } catch (Exception e) {
                        if (LOGGER.isLoggable(Level.INFO)) {
                            LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
                        }
                    }
                }

                // assign to query if sorting is supported!
                final SortBy[] sb = clauses.toArray(new SortBy[] {});
                if (rasterManager.granuleCatalog.getQueryCapabilities().supportsSorting(sb)) {
                    query.setSortBy(sb);
                }
            }
        }

        // collect granules
        rasterManager.getGranules(query, visitor);

        // get those granules
        visitor.produce();

        //
        // Did we actually load anything?? Notice that it might happen that
        // either we have holes inside the definition area for the mosaic
        // or we had some problem with missing tiles, therefore it might
        // happen that for some bboxes we don't have anything to load.
        //
        RenderedImage returnValue = null;
        if (visitor.granulesNumber >= 1) {

            //
            // Create the mosaic image by doing a crop if necessary and also
            // managing the transparent color if applicable. Be aware that
            // management of the transparent color involves removing
            // transparency information from the input images.
            //          
            returnValue = buildMosaic(visitor);
            if (returnValue != null) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine("Loaded bbox " + mosaicBBox.toString() + " while crop bbox "
                            + request.getCropBBox().toString());
                return returnValue;
            }

        }

        // Redo the query without filter to check whether we got no granules due
        // to a filter. In that case we need to return null
        if (hasTime || hasElevation || hasFilter || hasAdditionalDomains) {
            query.setFilter(bbox);
            rasterManager.getGranules(query, visitor);
            // get those granules
            visitor.produce();
            if (visitor.granulesNumber >= 1) {
                // It means the previous lack of granule was due to a filter excluding all the results. Then we return null
                return null;
            }
        }

        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine("Creating constant image for area with no data");

        // if we get here that means that we do not have anything to load
        // but still we are inside the definition area for the mosaic,
        // therefore we create a fake coverage using the background values,
        // if provided (defaulting to 0), as well as the compute raster
        // bounds, envelope and grid to world.

        final Number[] values = ImageUtilities.getBackgroundValues(rasterManager.defaultSM, backgroundValues);
        // create a constant image with a proper layout
        RenderedImage finalImage = ConstantDescriptor.create(Float.valueOf(rasterBounds.width),
                Float.valueOf(rasterBounds.height), values, null);
        if (rasterBounds.x != 0 || rasterBounds.y != 0) {
            finalImage = TranslateDescriptor.create(finalImage, Float.valueOf(rasterBounds.x),
                    Float.valueOf(rasterBounds.y), Interpolation.getInstance(Interpolation.INTERP_NEAREST),
                    null);
        }
        if (rasterManager.defaultCM != null) {
            final ImageLayout2 il = new ImageLayout2();
            il.setColorModel(rasterManager.defaultCM);
            Dimension tileSize = request.getTileDimensions();
            if (tileSize == null) {
                tileSize = JAI.getDefaultTileSize();
            }
            il.setSampleModel(
                    rasterManager.defaultCM.createCompatibleSampleModel(tileSize.width, tileSize.height));
            il.setTileGridXOffset(0).setTileGridYOffset(0).setTileWidth((int) tileSize.getWidth())
                    .setTileHeight((int) tileSize.getHeight());
            return FormatDescriptor.create(finalImage, Integer.valueOf(il.getSampleModel(null).getDataType()),
                    new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il));
        }
        return finalImage;

    } catch (Exception e) {
        throw new DataSourceException("Unable to create this mosaic", e);
    }
}

From source file:org.apache.fop.render.intermediate.IFRenderer.java

/** {@inheritDoc} */
protected void startVParea(CTM ctm, Rectangle clippingRect) {
    if (log.isTraceEnabled()) {
        log.trace("startVParea() ctm=" + ctm + ", clippingRect=" + clippingRect);
    }/* w w  w  .  jav a  2s. c o m*/
    AffineTransform at = new AffineTransform(ctm.toArray());
    startViewport(at, clippingRect);
    if (log.isTraceEnabled()) {
        log.trace("startVPArea: " + at + " --> " + graphicContext.getTransform());
    }
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

/**
* Load a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* 
* @param imageReadParameters the {@link ImageReadParam} to use for reading.
* @param index the index to use for the {@link ImageReader}.
* @param cropBBox the bbox to use for cropping. 
* @param mosaicWorldToGrid the cropping grid to world transform.
* @param request the incoming request to satisfy.
* @param hints {@link Hints} to be used for creating this raster.
* @return a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* @throws IOException in case an error occurs.
*///from  www .java2  s  .c o m
public GranuleLoadingResult loadRaster(final ImageReadParam imageReadParameters, final int index,
        final ReferencedEnvelope cropBBox, final MathTransform2D mosaicWorldToGrid,
        final RasterLayerRequest request, final Hints hints) throws IOException {

    if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
        final String name = Thread.currentThread().getName();
        LOGGER.finer("Thread:" + name + " Loading raster data for granuleDescriptor " + this.toString());
    }
    ImageReadParam readParameters = null;
    int imageIndex;
    final boolean useFootprint = roiProvider != null
            && request.getFootprintBehavior() != FootprintBehavior.None;
    Geometry inclusionGeometry = useFootprint ? roiProvider.getFootprint() : null;
    final ReferencedEnvelope bbox = useFootprint
            ? new ReferencedEnvelope(granuleBBOX.intersection(inclusionGeometry.getEnvelopeInternal()),
                    granuleBBOX.getCoordinateReferenceSystem())
            : granuleBBOX;
    boolean doFiltering = false;
    if (filterMe && useFootprint) {
        doFiltering = Utils.areaIsDifferent(inclusionGeometry, baseGridToWorld, granuleBBOX);
    }

    // intersection of this tile bound with the current crop bbox
    final ReferencedEnvelope intersection = new ReferencedEnvelope(bbox.intersection(cropBBox),
            cropBBox.getCoordinateReferenceSystem());
    if (intersection.isEmpty()) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    // check if the requested bbox intersects or overlaps the requested area 
    if (useFootprint && inclusionGeometry != null && !JTS.toGeometry(cropBBox).intersects(inclusionGeometry)) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {
        //
        //get info about the raster we have to read
        //

        // get a stream
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null)
            return null;

        // get a reader and try to cache the relevant SPI
        if (cachedReaderSPI == null) {
            reader = ImageIOExt.getImageioReader(inStream);
            if (reader != null)
                cachedReaderSPI = reader.getOriginatingProvider();
        } else
            reader = cachedReaderSPI.createReaderInstance();
        if (reader == null) {
            if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
                LOGGER.warning(new StringBuilder("Unable to get s reader for granuleDescriptor ")
                        .append(this.toString()).append(" with request ").append(request.toString())
                        .append(" Resulting in no granule loaded: Empty result").toString());
            }
            return null;
        }
        // set input
        customizeReaderInitialization(reader, hints);
        reader.setInput(inStream);

        // Checking for heterogeneous granules
        if (request.isHeterogeneousGranules()) {
            // create read parameters
            readParameters = new ImageReadParam();

            //override the overviews controller for the base layer
            imageIndex = ReadParamsController.setReadParams(
                    request.spatialRequestHelper.getRequestedResolution(), request.getOverviewPolicy(),
                    request.getDecimationPolicy(), readParameters, request.rasterManager, overviewsController);
        } else {
            imageIndex = index;
            readParameters = imageReadParameters;
        }

        //get selected level and base level dimensions
        final GranuleOverviewLevelDescriptor selectedlevel = getLevel(imageIndex, reader);

        // now create the crop grid to world which can be used to decide
        // which source area we need to crop in the selected level taking
        // into account the scale factors imposed by the selection of this
        // level together with the base level grid to world transformation
        AffineTransform2D cropWorldToGrid = new AffineTransform2D(selectedlevel.gridToWorldTransformCorner);
        cropWorldToGrid = (AffineTransform2D) cropWorldToGrid.inverse();
        // computing the crop source area which lives into the
        // selected level raster space, NOTICE that at the end we need to
        // take into account the fact that we might also decimate therefore
        // we cannot just use the crop grid to world but we need to correct
        // it.
        final Rectangle sourceArea = CRS.transform(cropWorldToGrid, intersection).toRectangle2D().getBounds();
        //gutter
        if (selectedlevel.baseToLevelTransform.isIdentity()) {
            sourceArea.grow(2, 2);
        }
        XRectangle2D.intersect(sourceArea, selectedlevel.rasterDimensions, sourceArea);//make sure roundings don't bother us
        // is it empty??
        if (sourceArea.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.fine("Got empty area for granuleDescriptor " + this.toString() + " with request "
                        + request.toString() + " Resulting in no granule loaded: Empty result");

            }
            return null;

        } else if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
            LOGGER.finer("Loading level " + imageIndex + " with source region: " + sourceArea + " subsampling: "
                    + readParameters.getSourceXSubsampling() + "," + readParameters.getSourceYSubsampling()
                    + " for granule:" + granuleUrl);
        }

        // Setting subsampling 
        int newSubSamplingFactor = 0;
        final String pluginName = cachedReaderSPI.getPluginClassName();
        if (pluginName != null && pluginName.equals(ImageUtilities.DIRECT_KAKADU_PLUGIN)) {
            final int ssx = readParameters.getSourceXSubsampling();
            final int ssy = readParameters.getSourceYSubsampling();
            newSubSamplingFactor = ImageIOUtilities.getSubSamplingFactor2(ssx, ssy);
            if (newSubSamplingFactor != 0) {
                if (newSubSamplingFactor > maxDecimationFactor && maxDecimationFactor != -1) {
                    newSubSamplingFactor = maxDecimationFactor;
                }
                readParameters.setSourceSubsampling(newSubSamplingFactor, newSubSamplingFactor, 0, 0);
            }
        }

        // set the source region
        readParameters.setSourceRegion(sourceArea);
        RenderedImage raster;
        try {
            // read
            raster = request.getReadType().read(readParameters, imageIndex, granuleUrl,
                    selectedlevel.rasterDimensions, reader, hints, false);

        } catch (Throwable e) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.log(java.util.logging.Level.FINE,
                        "Unable to load raster for granuleDescriptor " + this.toString() + " with request "
                                + request.toString() + " Resulting in no granule loaded: Empty result",
                        e);
            }
            return null;
        }

        // use fixed source area
        sourceArea.setRect(readParameters.getSourceRegion());

        //
        // setting new coefficients to define a new affineTransformation
        // to be applied to the grid to world transformation
        // -----------------------------------------------------------------------------------
        //
        // With respect to the original envelope, the obtained planarImage
        // needs to be rescaled. The scaling factors are computed as the
        // ratio between the cropped source region sizes and the read
        // image sizes.
        //
        // place it in the mosaic using the coords created above;
        double decimationScaleX = ((1.0 * sourceArea.width) / raster.getWidth());
        double decimationScaleY = ((1.0 * sourceArea.height) / raster.getHeight());
        final AffineTransform decimationScaleTranform = XAffineTransform.getScaleInstance(decimationScaleX,
                decimationScaleY);

        // keep into account translation  to work into the selected level raster space
        final AffineTransform afterDecimationTranslateTranform = XAffineTransform
                .getTranslateInstance(sourceArea.x, sourceArea.y);

        // now we need to go back to the base level raster space
        final AffineTransform backToBaseLevelScaleTransform = selectedlevel.baseToLevelTransform;

        // now create the overall transform
        final AffineTransform finalRaster2Model = new AffineTransform(baseGridToWorld);
        finalRaster2Model.concatenate(CoverageUtilities.CENTER_TO_CORNER);

        if (!XAffineTransform.isIdentity(backToBaseLevelScaleTransform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(backToBaseLevelScaleTransform);
        if (!XAffineTransform.isIdentity(afterDecimationTranslateTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(afterDecimationTranslateTranform);
        if (!XAffineTransform.isIdentity(decimationScaleTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(decimationScaleTranform);

        // adjust roi
        if (useFootprint) {

            ROIGeometry transformed;
            try {
                transformed = roiProvider.getTransformedROI(finalRaster2Model.createInverse());
                if (transformed.getAsGeometry().isEmpty()) {
                    // inset might have killed the geometry fully
                    return null;
                }

                PlanarImage pi = PlanarImage.wrapRenderedImage(raster);
                if (!transformed.intersects(pi.getBounds())) {
                    return null;
                }
                pi.setProperty("ROI", transformed);
                raster = pi;

            } catch (NoninvertibleTransformException e) {
                if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                    LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                            + " due to a problem when managing the ROI");
                return null;
            }

        }
        // keep into account translation factors to place this tile
        finalRaster2Model.preConcatenate((AffineTransform) mosaicWorldToGrid);
        final Interpolation interpolation = request.getInterpolation();

        //paranoiac check to avoid that JAI freaks out when computing its internal layouT on images that are too small
        Rectangle2D finalLayout = ImageUtilities.layoutHelper(raster, (float) finalRaster2Model.getScaleX(),
                (float) finalRaster2Model.getScaleY(), (float) finalRaster2Model.getTranslateX(),
                (float) finalRaster2Model.getTranslateY(), interpolation);
        if (finalLayout.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                        + " due to jai scale bug creating a null source area");
            return null;
        }

        // apply the affine transform  conserving indexed color model
        final RenderingHints localHints = new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL,
                interpolation instanceof InterpolationNearest ? Boolean.FALSE : Boolean.TRUE);
        if (XAffineTransform.isIdentity(finalRaster2Model, Utils.AFFINE_IDENTITY_EPS)) {
            return new GranuleLoadingResult(raster, null, granuleUrl, doFiltering, pamDataset);
        } else {
            //
            // In case we are asked to use certain tile dimensions we tile
            // also at this stage in case the read type is Direct since
            // buffered images comes up untiled and this can affect the
            // performances of the subsequent affine operation.
            //
            final Dimension tileDimensions = request.getTileDimensions();
            if (tileDimensions != null && request.getReadType().equals(ReadType.DIRECT_READ)) {
                final ImageLayout layout = new ImageLayout();
                layout.setTileHeight(tileDimensions.width).setTileWidth(tileDimensions.height);
                localHints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout));
            } else {
                if (hints != null && hints.containsKey(JAI.KEY_IMAGE_LAYOUT)) {
                    final Object layout = hints.get(JAI.KEY_IMAGE_LAYOUT);
                    if (layout != null && layout instanceof ImageLayout) {
                        localHints
                                .add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, ((ImageLayout) layout).clone()));
                    }
                }
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_CACHE)) {
                final Object cache = hints.get(JAI.KEY_TILE_CACHE);
                if (cache != null && cache instanceof TileCache)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, (TileCache) cache));
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_SCHEDULER)) {
                final Object scheduler = hints.get(JAI.KEY_TILE_SCHEDULER);
                if (scheduler != null && scheduler instanceof TileScheduler)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_SCHEDULER, (TileScheduler) scheduler));
            }
            boolean addBorderExtender = true;
            if (hints != null && hints.containsKey(JAI.KEY_BORDER_EXTENDER)) {
                final Object extender = hints.get(JAI.KEY_BORDER_EXTENDER);
                if (extender != null && extender instanceof BorderExtender) {
                    localHints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, (BorderExtender) extender));
                    addBorderExtender = false;
                }
            }
            // BORDER extender
            if (addBorderExtender) {
                localHints.add(ImageUtilities.BORDER_EXTENDER_HINTS);
            }

            ImageWorker iw = new ImageWorker(raster);
            iw.setRenderingHints(localHints);
            iw.affine(finalRaster2Model, interpolation, request.getBackgroundValues());
            return new GranuleLoadingResult(iw.getRenderedImage(), null, granuleUrl, doFiltering, pamDataset);
        }

    } catch (IllegalStateException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (org.opengis.referencing.operation.NoninvertibleTransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (TransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;

    } finally {
        try {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && inStream != null) {
                inStream.close();
            }
        } finally {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && reader != null) {
                reader.dispose();
            }
        }
    }
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * Labels the specified non-self-loop edge with the specified label.
 * Uses the font specified by this instance's 
 * <code>EdgeFontFunction</code>.  (If the font is unspecified, the existing
 * font for the graphics context is used.)  Positions the 
 * label between the endpoints according to the coefficient returned
 * by this instance's edge label closeness function.
 *///from  w w  w . j a  v a2s .co m
protected void labelEdge(Graphics2D g2d, Edge e, String label, int x1, int x2, int y1, int y2) {
    int distX = x2 - x1;
    int distY = y2 - y1;
    double totalLength = Math.sqrt(distX * distX + distY * distY);

    double closeness = edgeLabelClosenessFunction.getNumber(e).doubleValue();

    int posX = (int) (x1 + (closeness) * distX);
    int posY = (int) (y1 + (closeness) * distY);

    int xDisplacement = (int) (LABEL_OFFSET * (distY / totalLength));
    int yDisplacement = (int) (LABEL_OFFSET * (-distX / totalLength));

    Component component = prepareRenderer(graphLabelRenderer, label, isPicked(e), e);

    Dimension d = component.getPreferredSize();

    Shape edgeShape = edgeShapeFunction.getShape(e);

    double parallelOffset = 1;

    parallelOffset += parallelEdgeIndexFunction.getIndex(e);

    if (edgeShape instanceof Ellipse2D) {
        parallelOffset += edgeShape.getBounds().getHeight();
        parallelOffset = -parallelOffset;
    }

    parallelOffset *= d.height;

    AffineTransform old = g2d.getTransform();
    AffineTransform xform = new AffineTransform(old);
    xform.translate(posX + xDisplacement, posY + yDisplacement);
    double dx = x2 - x1;
    double dy = y2 - y1;
    if (graphLabelRenderer.isRotateEdgeLabels()) {
        double theta = Math.atan2(dy, dx);
        if (dx < 0) {
            theta += Math.PI;
        }
        xform.rotate(theta);
    }
    if (dx < 0) {
        parallelOffset = -parallelOffset;
    }

    xform.translate(-d.width / 2, -(d.height / 2 - parallelOffset));
    g2d.setTransform(xform);
    rendererPane.paintComponent(g2d, component, screenDevice, 0, 0, d.width, d.height, true);
    g2d.setTransform(old);
}

From source file:SWTGraphics2D.java

/**
 * Converts an SWT transform into the equivalent AWT transform.
 *
 * @param swtTransform  the SWT transform.
 *
 * @return The AWT transform.//w ww  .j a v a  2 s. c  o m
 */
private AffineTransform toAwtTransform(Transform swtTransform) {
    float[] elements = new float[6];
    swtTransform.getElements(elements);
    AffineTransform awtTransform = new AffineTransform(elements);
    return awtTransform;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java

private AffineTransform normalizeMatrix() {
    final double[] mx = new double[6];
    AffineTransform result = AffineTransform.getTranslateInstance(0, 0);
    result.getMatrix(mx);//w  w w. j  a v  a  2s  . co  m
    mx[3] = -1;
    mx[5] = height;
    result = new AffineTransform(mx);
    result.concatenate(transform);
    return result;
}

From source file:it.geosolutions.geobatch.destination.vulnerability.VulnerabilityComputation.java

/**
 * Method used for merging the input Rasters into a 2 images, one for human targets and the other for not human targets
 * /*  w w  w  .ja v a  2  s  .  com*/
 * @param humanTargets
 * @param notHumanTargets
 * @param bandPerTargetH
 * @param bandPerTargetNH
 * @throws IOException
 * @throws java.awt.geom.NoninvertibleTransformException
 * @throws TransformException
 * @throws MismatchedDimensionException
 */
public RenderedImage[] rasterCalculation(Map<Integer, TargetInfo> bandPerTargetH,
        Map<Integer, TargetInfo> bandPerTargetNH) throws IOException,
        java.awt.geom.NoninvertibleTransformException, MismatchedDimensionException, TransformException {
    // Initialization of the images
    RenderedImage humanTargets = null;
    RenderedImage notHumanTargets = null;
    String basePath = System.getProperty(RASTER_PATH_PROP, "");
    if (!basePath.equals("")) {
        basePath = basePath + File.separator + codicePartner;
    }
    // Read of the resources
    Map vulnerabilityConf = (Map) readResourceFromXML("/vulnerability.xml");
    // Vulnerability engine used for extracting the Targets
    VulnerabilityStatsEngine vsengine = new VulnerabilityStatsEngine(basePath, vulnerabilityConf, dataStore,
            DISTANCE_TYPE_NAME, pixelArea);
    // Target Map
    Map<String, TargetInfo> targetInfo = vsengine.getTargetInfo();

    /*
     * Creation of 2 images: one for the HUMAN TARGETS and the other for NOT HUMAN TARGETS
     */
    // List of Human Targets
    List<RenderedImage> humanList = new ArrayList<RenderedImage>();

    // List of Not Human Targets
    List<RenderedImage> notHumanList = new ArrayList<RenderedImage>();

    // Counters indicating which band is associated to the TargetInfo and
    // Image
    int humanBandCounter = 0;
    int notHumanBandCounter = 0;

    // Iterator on all the targets
    Iterator<String> rasterIter = targetInfo.keySet().iterator();

    // Initializations of the parameters for merging the input rasters
    Envelope2D globalBBOXHuman = null;
    Envelope2D globalBBOXNotHuman = null;
    List<AffineTransform> tfHuman = new ArrayList<AffineTransform>();
    List<AffineTransform> tfNotHuman = new ArrayList<AffineTransform>();
    AffineTransform g2WHuman = null;
    AffineTransform g2WNotHuman = null;
    // Cycle on all the rasters
    while (rasterIter.hasNext()) {
        // save the ID of this target
        String targetID = rasterIter.next();

        // Load the target manager, init its status and check if the actual
        // distance is a valid distance for it
        TargetInfo info = targetInfo.get(targetID);

        // Getting of the transformation parameters
        GridGeometry2D gg2D = info.getGG2D();
        Envelope2D envelope = gg2D.getEnvelope2D();
        AffineTransform w2g = (AffineTransform) gg2D.getCRSToGrid2D(PixelOrientation.UPPER_LEFT);
        // getting information about current Target
        TargetManager manager = info.getManager();

        // Image associated to the current target
        RenderedImage newImage = info.getRaster();
        // Image data type
        int imgDataType = newImage.getSampleModel().getDataType();
        // Check if the image really exists
        if (newImage != null) {
            // If the target is human
            if (manager.isHumanTarget()) {
                // Other check for ensuring the target is correct
                if (imgDataType != DataBuffer.TYPE_FLOAT) {
                    System.out.println("Wrong data type");
                }

                // perform union
                if (globalBBOXHuman == null) {
                    globalBBOXHuman = new Envelope2D(envelope);
                } else {
                    globalBBOXHuman.include(envelope);
                }
                // Selection of the first g2w transform as the global one
                if (g2WHuman == null) {
                    g2WHuman = (AffineTransform) gg2D.getGridToCRS2D(PixelOrientation.UPPER_LEFT);
                }

                // Creation of the transformation from destination Raster space to source Raster space
                AffineTransform temp = new AffineTransform(w2g);
                temp.concatenate(g2WHuman);
                tfHuman.add(temp);

                // Addition of the TargetInfo of this target
                bandPerTargetH.put(humanBandCounter, info);
                // Update of the bandCounter
                humanBandCounter++;
                // Addition of the image to the associated list
                humanList.add(newImage);

            } else {
                // Other check for ensuring the target is correct
                if (imgDataType != DataBuffer.TYPE_BYTE) {
                    System.out.println("Wrong data type");
                }

                // perform union
                if (globalBBOXNotHuman == null) {
                    globalBBOXNotHuman = envelope;
                } else {
                    globalBBOXNotHuman.include(envelope);
                }
                // Selection of the first g2w transform as the global one
                if (g2WNotHuman == null) {
                    g2WNotHuman = (AffineTransform) gg2D.getGridToCRS2D(PixelOrientation.UPPER_LEFT);
                }
                // Creation of the transformation from destination Raster space to source Raster space
                AffineTransform temp = new AffineTransform(w2g);
                temp.concatenate(g2WNotHuman);
                tfNotHuman.add(temp);

                // Addition of the TargetInfo of this target
                bandPerTargetNH.put(notHumanBandCounter, info);
                // Update of the bandCounter
                notHumanBandCounter++;
                // Addition of the image to the associated list
                notHumanList.add(newImage);
            }
        }
    }

    // computing final raster space for the two targets
    GridGeometry2D humanGG2D = new GridGeometry2D(PixelInCell.CELL_CORNER, new AffineTransform2D(g2WHuman),
            globalBBOXHuman, null);
    globalBBOXHuman = humanGG2D.getEnvelope2D(); // take into account integer pixel roundings

    GridGeometry2D noHumanGG2D = new GridGeometry2D(PixelInCell.CELL_CORNER, new AffineTransform2D(g2WNotHuman),
            globalBBOXNotHuman, null);
    globalBBOXNotHuman = noHumanGG2D.getEnvelope2D(); // take into account integer pixel roundings

    // BandMerge of the images
    RenderedImage[] imagesHuman = new RenderedImage[humanList.size()];
    RenderedImage[] imagesNotHuman = new RenderedImage[notHumanList.size()];
    // Setting of the final layout
    ImageLayout layoutH = new ImageLayout2();
    GridEnvelope2D gridRange2D = humanGG2D.getGridRange2D();
    layoutH.setMinX(gridRange2D.x);
    layoutH.setMinY(gridRange2D.y);
    layoutH.setWidth(gridRange2D.width);
    layoutH.setHeight(gridRange2D.height);
    // Definition of the TileCache
    RenderingHints hintsH = new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache());
    // Setting of the layout as hint
    hintsH.put(JAI.KEY_IMAGE_LAYOUT, layoutH);
    // Merging of the input human targets
    humanTargets = BandMergeDescriptor.create(null, 0, hintsH, tfHuman, humanList.toArray(imagesHuman));
    // Setting of the final layout
    ImageLayout layoutNH = new ImageLayout2();
    gridRange2D = noHumanGG2D.getGridRange2D();
    layoutNH.setMinX(gridRange2D.x);
    layoutNH.setMinY(gridRange2D.y);
    layoutNH.setWidth(gridRange2D.width);
    layoutNH.setHeight(gridRange2D.height);
    // Definition of the TileCache
    RenderingHints hintsNH = new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache());
    hintsNH.put(JAI.KEY_IMAGE_LAYOUT, layoutNH);
    // Merging of the input not human targets
    notHumanTargets = BandMergeDescriptor.create(null, 0, hintsNH, tfNotHuman,
            notHumanList.toArray(imagesNotHuman));

    // cache the final images
    humanTargets = NullDescriptor.create(humanTargets,
            new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache()));

    notHumanTargets = NullDescriptor.create(notHumanTargets,
            new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache()));

    // Clearing of the initial lists
    notHumanList.clear();
    humanList.clear();
    // create a new array of the new images
    return new RenderedImage[] { humanTargets, notHumanTargets };
}

From source file:DefaultGraphics2D.java

/**
 * Renders an image, applying a transform from image space into user space
 * before drawing. The transformation from user space into device space is
 * done with the current <code>Transform</code> in the
 * <code>Graphics2D</code>. The specified transformation is applied to the
 * image before the transform attribute in the <code>Graphics2D</code>
 * context is applied. The rendering attributes applied include the
 * <code>Clip</code>, <code>Transform</code>, and <code>Composite</code>
 * attributes. Note that no rendering is done if the specified transform is
 * noninvertible.//from  w ww.java  2 s.c  o  m
 * 
 * @param img
 *          the <code>Image</code> to be rendered
 * @param xform
 *          the transformation from image space into user space
 * @param obs
 *          the {@link ImageObserver} to be notified as more of the
 *          <code>Image</code> is converted
 * @return <code>true</code> if the <code>Image</code> is fully loaded and
 *         completely rendered; <code>false</code> if the <code>Image</code>
 *         is still being loaded.
 * @see #transform
 * @see #setTransform
 * @see #setComposite
 * @see #clip
 * @see #setClip(Shape)
 */
public boolean drawImage(Image img, AffineTransform xform, ImageObserver obs) {
    boolean retVal = true;

    if (xform.getDeterminant() != 0) {
        AffineTransform inverseTransform = null;
        try {
            inverseTransform = xform.createInverse();
        } catch (NoninvertibleTransformException e) {
            // Should never happen since we checked the
            // matrix determinant
            throw new Error(e.getMessage());
        }

        gc.transform(xform);
        retVal = drawImage(img, 0, 0, null);
        gc.transform(inverseTransform);
    } else {
        AffineTransform savTransform = new AffineTransform(gc.getTransform());
        gc.transform(xform);
        retVal = drawImage(img, 0, 0, null);
        gc.setTransform(savTransform);
    }

    return retVal;

}

From source file:DefaultGraphics2D.java

/**
 * @param defaultDeviceTransform//from  w w  w.  j a va  2  s  . c om
 *          Default affine transform applied to map the user space to the user
 *          space.
 */
public GraphicContext(AffineTransform defaultDeviceTransform) {
    this();
    defaultTransform = new AffineTransform(defaultDeviceTransform);
    transform = new AffineTransform(defaultTransform);
    if (!defaultTransform.isIdentity())
        transformStack.add(TransformStackElement.createGeneralTransformElement(defaultTransform));
}

From source file:DefaultGraphics2D.java

/**
 * @return a deep copy of this context//  w  w w. j  a  va2s.  c om
 */
public Object clone() {
    GraphicContext copyGc = new GraphicContext(defaultTransform);

    //
    // Now, copy each GC element in turn
    //

    // Default transform
    /* Set in constructor */

    // Transform
    copyGc.transform = new AffineTransform(this.transform);

    // Transform stack
    copyGc.transformStack = new ArrayList(transformStack.size());
    for (int i = 0; i < this.transformStack.size(); i++) {
        TransformStackElement stackElement = (TransformStackElement) this.transformStack.get(i);
        copyGc.transformStack.add(stackElement.clone());
    }

    // Transform stack validity
    copyGc.transformStackValid = this.transformStackValid;

    // Paint (immutable by requirement)
    copyGc.paint = this.paint;

    // Stroke (immutable by requirement)
    copyGc.stroke = this.stroke;

    // Composite (immutable by requirement)
    copyGc.composite = this.composite;

    // Clip
    if (clip != null)
        copyGc.clip = new GeneralPath(clip);
    else
        copyGc.clip = null;

    // RenderingHints
    copyGc.hints = (RenderingHints) this.hints.clone();

    // Font (immutable)
    copyGc.font = this.font;

    // Background, Foreground (immutable)
    copyGc.background = this.background;
    copyGc.foreground = this.foreground;

    return copyGc;
}