private boolean checkLayering(Area b) {
   ArrayList<Number> id = getVisible();
   Vector<Rectangle> rects = new Vector<Rectangle>(id.size());
   for (Number n : id) {
     rects.add(getIE().get(n).toRectangle());
   }
   Rectangle r = b.toRectangle();
   int index = 0;
   for (Rectangle rect : rects) {
     if (r.equals(rect)) {
       index = rects.indexOf(rect) + 1;
     }
   }
   for (int i = index; i < rects.size(); i++) {
     Rectangle rect = rects.get(i);
     if (r.intersects(rect)) {
       Rectangle isect = r.intersection(rect);
       isect.setRect(isect.x, isect.y, isect.getWidth() + 1, isect.getHeight() + 2);
       if (isect.contains(mascot.getAnchor())) {
         return false;
       }
     }
   }
   return true;
 }
示例#2
0
 public void mouseDragged(MouseEvent e) {
   if (dragging) {
     int x = e.getX() - offset.x;
     int y = e.getY() - offset.y;
     cropping.setClip(x, y);
   }
   if (resizing) {
     Point p = e.getPoint();
     Rectangle r = cropping.clip;
     int type = cropping.getCursor().getType();
     int dx = p.x - r.x;
     int dy = p.y - r.y;
     switch (type) {
       case Cursor.N_RESIZE_CURSOR:
         int height = r.height - dy;
         r.setRect(r.x, r.y + dy, r.width, height);
         break;
       case Cursor.NW_RESIZE_CURSOR:
         int width = r.width - dx;
         height = r.height - dy;
         r.setRect(r.x + dx, r.y + dy, width, height);
         break;
       case Cursor.W_RESIZE_CURSOR:
         width = r.width - dx;
         r.setRect(r.x + dx, r.y, width, r.height);
         break;
       case Cursor.SW_RESIZE_CURSOR:
         width = r.width - dx;
         height = dy;
         r.setRect(r.x + dx, r.y, width, height);
         break;
       case Cursor.S_RESIZE_CURSOR:
         height = dy;
         r.setRect(r.x, r.y, r.width, height);
         break;
       case Cursor.SE_RESIZE_CURSOR:
         width = dx;
         height = dy;
         r.setRect(r.x, r.y, width, height);
         break;
       case Cursor.E_RESIZE_CURSOR:
         width = dx;
         r.setRect(r.x, r.y, width, r.height);
         break;
       case Cursor.NE_RESIZE_CURSOR:
         width = dx;
         height = r.height - dy;
         r.setRect(r.x, r.y + dy, width, height);
         break;
       default:
         System.out.println("unexpected type: " + type);
     }
     cropping.repaint();
   }
 }
  private boolean sizeChanged() {
    if ((oldComponentInnards == null) || (componentInnards == null)) {
      return true;
    }

    oldComponentInnards.setRect(componentInnards);
    componentInnards = SwingUtilities.calculateInnerArea(progressBar, componentInnards);
    return !oldComponentInnards.equals(componentInnards);
  }
示例#4
0
  /**
   * Sets the go.
   *
   * @param go the go
   * @param so the so
   * @throws DbException the db exception
   */
  public void setGO(DbObject go, DbObject so) throws DbException {
    this.go = go;
    this.so = so;
    name = so == null ? null : so.getName();

    if (go != null) {
      Rectangle rect = (Rectangle) go.get(DbGraphic.fGraphicalObjectRectangle);
      bounds.setRect(rect);
    }
  }
示例#5
0
  /**
   * Adjust the size of the shape so it encompasses the text inside it.
   *
   * @return a <code>Rectangle2D</code> that is the bounds of this shape.
   */
  public Rectangle resizeToFitText() {
    Rectangle anchor = getAnchor();
    if (anchor.getWidth() == 0.) throw new POIXMLException("Anchor of the shape was not set.");
    double height = getTextHeight();
    height += 1; // add a pixel to compensate rounding errors

    anchor.setRect(anchor.getX(), anchor.getY(), anchor.getWidth(), height);
    setAnchor(anchor);

    return anchor;
  }
示例#6
0
  /**
   * Check cloning of the legendItemShape field.
   *
   * @throws CloneNotSupportedException
   */
  @Test
  public void testCloning_LegendItemShape() throws CloneNotSupportedException {
    Rectangle shape = new Rectangle(-4, -4, 8, 8);
    PiePlot p1 = new PiePlot();
    p1.setLegendItemShape(shape);
    PiePlot p2 = (PiePlot) p1.clone();
    assertNotSame(p1, p2);
    assertSame(p1.getClass(), p2.getClass());
    assertEquals(p1, p2);

    // change the shape and make sure it only affects p1
    shape.setRect(1.0, 2.0, 3.0, 4.0);
    assertFalse(p1.equals(p2));
  }
  public static Rectangle calculateInnerArea(final JComponent component, final Rectangle rect) {
    if (component == null) {
      return null;
    }

    Insets insets = component.getInsets();
    Rectangle bounds = component.getBounds(rect);
    bounds.setRect(
        insets.left,
        insets.top,
        bounds.width - insets.right - insets.left,
        bounds.height - insets.top - insets.bottom);
    return bounds;
  }
  public void update() {

    if (FLYSPEED == 0 && speedY <= 9) speedY += gravity;

    y += speedY + FLYSPEED;

    if (FLYSPEED < 0) FLYSPEED = (float) (FLYSPEED + 0.5);

    rect.setRect(x, y, 34, 24);

    if (y > 382) y = 382;
    if (y < -72) FLYSPEED = 0;
    // System.out.println(FLYSPEED);
  }
  public static Rectangle parseRectangle(final String boundsAsText) {
    try {
      final StringTokenizer tokenizer = new StringTokenizer(boundsAsText, ",");
      if (tokenizer.countTokens() == 4) {
        final double x = Double.parseDouble(tokenizer.nextToken());
        final double y = Double.parseDouble(tokenizer.nextToken());
        final double width = Double.parseDouble(tokenizer.nextToken());
        final double height = Double.parseDouble(tokenizer.nextToken());

        final Rectangle rectangle = new Rectangle();
        rectangle.setRect(x, y, width, height);
        return rectangle;
      }
      return null;
    } catch (Exception e) {
      DebugLog.log("Error while getting initial frame bounds.", e); // NON-NLS
      return null;
    }
  }
  private void navigationButtonScreenAdjustments(ScrollTo scrollTo) {
    scenesDepthFrame.pack();

    double width = scenesDepthFrame.getSize().getWidth();
    double screenWidth = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
    if (width > screenWidth) {
      Rectangle bounds = scenesDepthFrame.getBounds();
      bounds.setRect(bounds.getX(), bounds.getY(), screenWidth - 50, bounds.getHeight());
      scenesDepthFrame.setBounds(bounds);
    }

    JList list = scrollTo.getList(depthLists);
    list.requestFocusInWindow();
    list.setSelectedIndex(0);

    scenesDepthFrame.setVisible(true);

    // Must come before the setVisible method above
    scrollToTheLastList(scrollPane, scrollTo);
  }
  public void drawInsideRectangle(
      Graphics2D g, AffineTransform scaleInstance, Rectangle r, PrintRequestAttributeSet properties)
      throws SymbolDrawingException {
    markerFillProperties.setSampleSymbol(markerSymbol);
    switch (markerFillProperties.getFillStyle()) {
      case SINGLE_CENTERED_SYMBOL:
        FPoint2D p = new FPoint2D(r.getCenterX(), r.getCenterY());
        markerSymbol.draw(g, null, p, null);
        break;
      case GRID_FILL:
        {
          g.setClip(r);
          int size = (int) markerSymbol.getSize();
          if (size <= 0) size = 1;
          Rectangle rProv = new Rectangle();
          rProv.setFrame(0, 0, size, size);
          Paint resulPatternFill = null;

          BufferedImage sample = null;
          sample = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
          Graphics2D gAux = sample.createGraphics();

          double xSeparation = markerFillProperties.getXSeparation(); // TODO
          // apply
          // CartographicSupport
          double ySeparation = markerFillProperties.getYSeparation(); // TODO
          // apply
          // CartographicSupport
          double xOffset = markerFillProperties.getXOffset();
          double yOffset = markerFillProperties.getYOffset();

          markerSymbol.drawInsideRectangle(gAux, new AffineTransform(), rProv, properties);

          rProv.setRect(0, 0, rProv.getWidth() + xSeparation, rProv.getHeight() + ySeparation);

          BufferedImage bi =
              new BufferedImage(rProv.width, rProv.height, BufferedImage.TYPE_INT_ARGB);
          gAux = bi.createGraphics();
          gAux.drawImage(sample, null, (int) (xSeparation * 0.5), (int) (ySeparation * 0.5));

          resulPatternFill = new TexturePaint(bi, rProv);
          g.setColor(null);
          g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

          // g.translate(xOffset, rProv.getHeight()-yOffset);
          g.translate(xOffset, -yOffset);
          g.setPaint(resulPatternFill);
          g.fill(r);
          // g.translate(-xOffset, -rProv.getHeight()+yOffset);
          g.translate(-xOffset, yOffset);
          g.setClip(null);
        }
        break;
      case RANDOM_FILL:
        g.setClip(r);
        int x = r.x;
        int y = r.y;
        int width = r.width;
        int height = r.height;
        g.setBackground(null);

        markerSymbol.draw(g, null, new FPoint2D((x + width * 0.2), (y + height * 0.8)), null);
        markerSymbol.draw(g, null, new FPoint2D((x + width * 0.634), (y + height * 0.3)), null);
        markerSymbol.draw(g, null, new FPoint2D((x + width * 0.26), (y + height * 0.35)), null);
        markerSymbol.draw(g, null, new FPoint2D((x + width * 0.45), (y + height * 0.98)), null);
        markerSymbol.draw(g, null, new FPoint2D((x + width * 0.9), (y + height * 0.54)), null);
        markerSymbol.draw(g, null, new FPoint2D((x + width * 1.1), (y + height * 0.7)), null);
        g.setClip(null);
        break;
    }
    if (getOutline() != null && hasOutline()) {
      if (properties == null)
        getOutline().draw(g, scaleInstance, new FPolyline2D(new GeneralPathX(r)), null);
      else getOutline().print(g, scaleInstance, new FPolyline2D(new GeneralPathX(r)), properties);
    }
  }
示例#12
0
 public void setARectangle() {
   attackRect.setRect(new Rectangle((int) (this.xPos - 55f), (int) (this.yPos - 35f), 150, 150));
 }
  public void draw(Graphics2D g, AffineTransform affineTransform, FShape shp, Cancellable cancel) {
    switch (markerFillProperties.getFillStyle()) {
      case SINGLE_CENTERED_SYMBOL:
        // case a single marker is used into a polygon shapetype
        Geometry geom = FConverter.java2d_to_jts(shp);
        com.vividsolutions.jts.geom.Point centroid = geom.getCentroid();
        /*
         * Hay ocasiones en que jts no puede calcular un centroide y
         * devuelve NaN (por ejemplo con geometrías poligonales cuyos puntos
         * tienen todos la misma abscisa y distinta ordenada con tan solo
         * una diferencia de 1 ó 2 unidades) entonces, en lugar de utilizar
         * este centroide tomamos el centro del bounds del shp (la geometría
         * es tan pequeña que consideramos que deben coincidir).
         */
        if (!(Double.isNaN(centroid.getX()) || Double.isNaN(centroid.getY()))) {
          double centroidX = centroid.getX() + markerFillProperties.getXOffset();
          double centroidY = centroid.getY() + markerFillProperties.getYOffset();
          FPoint2D p = new FPoint2D(new Point2D.Double(centroidX, centroidY));
          markerSymbol.draw(g, affineTransform, p, null);
        } else {
          double centroidX = shp.getBounds().getCenterX();
          double centroidY = shp.getBounds().getCenterY();
          FPoint2D p = new FPoint2D(new Point2D.Double(centroidX, centroidY));
          markerSymbol.draw(g, affineTransform, p, null);
        }
        break;
      case GRID_FILL:
        // case a grid fill is used
        {
          Rectangle rClip = null;
          if (g.getClipBounds() != null) {
            rClip = (Rectangle) g.getClipBounds().clone();
            g.setClip(rClip.x, rClip.y, rClip.width, rClip.height);
          }
          g.clip(shp);

          int size = (int) markerSymbol.getSize();
          Rectangle rProv = new Rectangle();
          rProv.setFrame(0, 0, size, size);
          Paint resulPatternFill = null;

          double xSeparation = markerFillProperties.getXSeparation(); // TODO
          // apply
          // CartographicSupport
          double ySeparation = markerFillProperties.getYSeparation(); // TODO
          // apply
          // CartographicSupport
          double xOffset = markerFillProperties.getXOffset();
          double yOffset = markerFillProperties.getYOffset();

          BufferedImage sample = null;
          sample = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
          Graphics2D gAux = sample.createGraphics();

          try {
            markerSymbol.drawInsideRectangle(gAux, gAux.getTransform(), rProv, null);
          } catch (SymbolDrawingException e) {
            if (e.getType() == SymbolDrawingException.UNSUPPORTED_SET_OF_SETTINGS) {
              try {
                SymbologyFactory.getWarningSymbol(
                        SymbolDrawingException.STR_UNSUPPORTED_SET_OF_SETTINGS,
                        "",
                        SymbolDrawingException.UNSUPPORTED_SET_OF_SETTINGS)
                    .drawInsideRectangle(gAux, gAux.getTransform(), rProv, null);
              } catch (SymbolDrawingException e1) {
                // IMPOSSIBLE TO REACH THIS
              }
            } else {
              // should be unreachable code
              throw new Error(Messages.getString("symbol_shapetype_mismatch"));
            }
          }
          rProv.setRect(0, 0, rProv.getWidth() + xSeparation, rProv.getHeight() + ySeparation);

          BufferedImage bi =
              new BufferedImage(rProv.width, rProv.height, BufferedImage.TYPE_INT_ARGB);
          gAux = bi.createGraphics();
          gAux.drawImage(sample, null, (int) (xSeparation * 0.5), (int) (ySeparation * 0.5));

          resulPatternFill = new TexturePaint(bi, rProv);
          sample = null;
          gAux.dispose();

          g.setColor(null);
          g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

          g.translate(xOffset, -yOffset);
          g.setPaint(resulPatternFill);
          g.fill(shp);
          g.translate(-xOffset, +yOffset);
          g.setClip(rClip);
          bi = null;
        }
        break;
      case RANDOM_FILL:
        {
          double s = markerSymbol.getSize();
          Rectangle r = shp.getBounds();
          int drawCount = (int) (Math.min(r.getWidth(), r.getHeight()) / s);
          Random random = new Random();

          int minx = r.x;
          int miny = r.y;
          int width = r.width;
          int height = r.height;

          r = new Rectangle();
          g.setClip(shp);

          for (int i = 0; (cancel == null || !cancel.isCanceled()) && i < drawCount; i++) {
            int x = (int) Math.abs(random.nextDouble() * width);
            int y = (int) Math.abs(random.nextDouble() * height);
            x = x + minx;
            y = y + miny;
            markerSymbol.draw(g, new AffineTransform(), new FPoint2D(x, y), cancel);
          }
          g.setClip(null);
        }
        break;
    }
    if (getOutline() != null) {
      getOutline().draw(g, affineTransform, shp, cancel);
    }
  }
示例#14
0
  /**
   * Overrides Step getMark method.
   *
   * @param trackerPanel the tracker panel
   * @return the mark
   */
  protected Mark getMark(TrackerPanel trackerPanel) {
    Mark mark = marks.get(trackerPanel);
    TPoint selection = null;
    if (mark == null) {
      selection = trackerPanel.getSelectedPoint();
      Point p = null; // draws this step as "selected" shape if not null
      valid = true; // true if step is not NaN
      for (int n = 0; n < points.length; n++) {
        if (!valid) continue;
        // determine if point is valid (ie not NaN)
        valid = valid && !Double.isNaN(points[n].getX()) && !Double.isNaN(points[n].getY());
        screenPoints[n] = points[n].getScreenPosition(trackerPanel);
        // step is "selected" if trackerPanel selectedPoint is position or selectedSteps contains
        // this step
        if (valid && (selection == points[n] || trackerPanel.selectedSteps.contains(this))) {
          p = screenPoints[n];
        }
      }
      if (p == null) {
        if (footprint instanceof PositionVectorFootprint) {
          twoPoints[0] = screenPoints[0];
          twoPoints[1] = trackerPanel.getSnapPoint().getScreenPosition(trackerPanel);
          mark = footprint.getMark(twoPoints);
        } else mark = footprint.getMark(screenPoints);
      } else {
        transform.setToTranslation(p.x, p.y);
        int scale = FontSizer.getIntegerFactor();
        if (scale > 1) {
          transform.scale(scale, scale);
        }
        final Color color = footprint.getColor();
        final Shape selectedShape = transform.createTransformedShape(selectionShape);
        mark =
            new Mark() {
              public void draw(Graphics2D g, boolean highlighted) {
                g.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                Paint gpaint = g.getPaint();
                g.setPaint(color);
                g.fill(selectedShape);
                g.setPaint(gpaint);
              }

              public Rectangle getBounds(boolean highlighted) {
                return selectedShape.getBounds();
              }
            };
      }
      final Mark theMark = mark;
      mark =
          new Mark() {
            public void draw(Graphics2D g, boolean highlighted) {
              if (!valid) {
                return;
              }
              theMark.draw(g, highlighted);
            }

            public Rectangle getBounds(boolean highlighted) {
              return theMark.getBounds(highlighted);
            }
          };
      marks.put(trackerPanel, mark);
      // get new text layout
      String s = ""; // $NON-NLS-1$
      VideoClip clip = trackerPanel.getPlayer().getVideoClip();
      if (clip.getStepCount() != 1) {
        s += clip.frameToStep(getFrameNumber());
      }
      if (s.length() == 0) s = " "; // $NON-NLS-1$
      TextLayout layout = new TextLayout(s, textLayoutFont, frc);
      textLayouts.put(trackerPanel, layout);
      // get layout position (bottom left corner of text)
      p = getLayoutPosition(trackerPanel);
      Rectangle bounds = layoutBounds.get(trackerPanel);
      if (bounds == null) {
        bounds = new Rectangle();
        layoutBounds.put(trackerPanel, bounds);
      }
      Rectangle2D rect = layout.getBounds();
      // set bounds (top left corner and size)
      bounds.setRect(p.x, p.y - rect.getHeight(), rect.getWidth(), rect.getHeight());
    }
    return mark;
  }
示例#15
0
 public void setRectangle() {
   rect.setRect(new Rectangle((int) this.xPos, (int) this.yPos, 32, 64));
 }
示例#16
0
 /**
  * Sets the height.
  *
  * @param h the new height
  */
 public void setHeight(int h) {
   bounds.setRect(bounds.x, bounds.y, bounds.width, h);
 }
示例#17
0
 /**
  * Sets the dimension.
  *
  * @param w the w
  * @param h the h
  */
 public void setDimension(int w, int h) {
   bounds.setRect(bounds.x, bounds.y, w, h);
 }
示例#18
0
 /**
  * Sets the location.
  *
  * @param x the x
  * @param y the y
  */
 public void setLocation(int x, int y) {
   bounds.setRect(x, y, bounds.width, bounds.height);
 }
示例#19
0
 /*
  * (non-Javadoc)
  *
  * @see org.modelsphere.jack.srtool.features.layout.graph.Vertex#setLocation( java.awt.Point)
  */
 @Override
 public void setLocation(Point point) {
   bounds.setRect(point.x, point.y, bounds.width, bounds.height);
 }
示例#20
0
 /**
  * Sets the width.
  *
  * @param w the new width
  */
 public void setWidth(int w) {
   bounds.setRect(bounds.x, bounds.y, w, bounds.height);
 }
示例#21
0
  /**
   * 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.
   */
  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 ReferencedEnvelope bbox =
        inclusionGeometry != null
            ? new ReferencedEnvelope(
                granuleBBOX.intersection(inclusionGeometry.getEnvelopeInternal()),
                granuleBBOX.getCoordinateReferenceSystem())
            : granuleBBOX;
    boolean doFiltering = false;
    if (filterMe) {
      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;
    }

    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
      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.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);
      final 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);
      final double x = finalRaster2Model.getTranslateX();
      final double y = finalRaster2Model.getTranslateY();

      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);

      // 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;
      }
      ROI granuleLoadingShape = null;
      if (granuleROIShape != null) {

        final Point2D translate =
            mosaicWorldToGrid.transform(new DirectPosition2D(x, y), (Point2D) null);
        AffineTransform tx2 = new AffineTransform();
        tx2.preConcatenate(
            AffineTransform.getScaleInstance(
                ((AffineTransform) mosaicWorldToGrid).getScaleX(),
                -((AffineTransform) mosaicWorldToGrid).getScaleY()));
        tx2.preConcatenate(
            AffineTransform.getScaleInstance(
                ((AffineTransform) baseGridToWorld).getScaleX(),
                -((AffineTransform) baseGridToWorld).getScaleY()));
        tx2.preConcatenate(
            AffineTransform.getTranslateInstance(translate.getX(), translate.getY()));
        granuleLoadingShape = (ROI) granuleROIShape.transform(tx2);
      }
      // 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, granuleLoadingShape, granuleUrl, doFiltering);
      } 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);
        }
        //                boolean hasScaleX=!(Math.abs(finalRaster2Model.getScaleX()-1) <
        // 1E-2/(raster.getWidth()+1-raster.getMinX()));
        //                boolean hasScaleY=!(Math.abs(finalRaster2Model.getScaleY()-1) <
        // 1E-2/(raster.getHeight()+1-raster.getMinY()));
        //                boolean hasShearX=!(finalRaster2Model.getShearX() == 0.0);
        //                boolean hasShearY=!(finalRaster2Model.getShearY() == 0.0);
        //                boolean hasTranslateX=!(Math.abs(finalRaster2Model.getTranslateX()) <
        // 0.01F);
        //                boolean hasTranslateY=!(Math.abs(finalRaster2Model.getTranslateY()) <
        // 0.01F);
        //                boolean isTranslateXInt=!(Math.abs(finalRaster2Model.getTranslateX() -
        // (int) finalRaster2Model.getTranslateX()) <  0.01F);
        //                boolean isTranslateYInt=!(Math.abs(finalRaster2Model.getTranslateY() -
        // (int) finalRaster2Model.getTranslateY()) <  0.01F);
        //
        //                boolean isIdentity = finalRaster2Model.isIdentity() &&
        // !hasScaleX&&!hasScaleY &&!hasTranslateX&&!hasTranslateY;

        //                // TODO how can we check that the a skew is harmelss????
        //                if(isIdentity){
        //                    // TODO check if we are missing anything like tiling or such that
        // comes from hints
        //                    return new GranuleLoadingResult(raster, granuleLoadingShape,
        // granuleUrl, doFiltering);
        //                }
        //
        //                // TOLERANCE ON PIXELS SIZE
        //
        //                // Check and see if the affine transform is in fact doing
        //                // a Translate operation. That is a scale by 1 and no rotation.
        //                // In which case call translate. Note that only integer translate
        //                // is applicable. For non-integer translate we'll have to do the
        //                // affine.
        //                // If the hints contain an ImageLayout hint, we can't use
        //                // TranslateIntOpImage since it isn't capable of dealing with that.
        //                // Get ImageLayout from renderHints if any.
        //                ImageLayout layout = RIFUtil.getImageLayoutHint(localHints);
        //                if ( !hasScaleX &&
        //                     !hasScaleY  &&
        //                      !hasShearX&&
        //                      !hasShearY&&
        //                      isTranslateXInt&&
        //                      isTranslateYInt&&
        //                    layout == null) {
        //                    // It's a integer translate
        //                    return new GranuleLoadingResult(new TranslateIntOpImage(raster,
        //                                                    localHints,
        //                                                   (int) finalRaster2Model.getShearX(),
        //                                                   (int)
        // finalRaster2Model.getShearY()),granuleLoadingShape, granuleUrl, doFiltering);
        //                }

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

    } 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();
        }
      }
    }
  }
示例#22
0
 /**
  * Translate.
  *
  * @param dx the dx
  * @param dy the dy
  */
 public void translate(int dx, int dy) {
   bounds.setRect(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height);
 }
示例#23
0
 /*
  * (non-Javadoc)
  *
  * @see org.modelsphere.jack.srtool.features.layout.graph.Vertex#setDimension
  * (java.awt.Dimension)
  */
 @Override
 public void setDimension(Dimension dimension) {
   bounds.setRect(bounds.x, bounds.y, dimension.width, dimension.height);
 }
示例#24
0
    public void plotMemoryUsage(int x1, int y1, int x2, int y2, int npool) {

      MemoryPoolMXBean mp = mpools.get(npool);
      float usedMemory = mp.getUsage().getUsed();
      float totalMemory = mp.getUsage().getMax();

      // .. Draw allocated and used strings ..
      big.setColor(Color.green);

      // Print Max memory allocated for this memory pool.
      big.drawString(
          String.valueOf((int) totalMemory / 1024) + "K Max ",
          x1 + 4.0f,
          (float) y1 + ascent + 0.5f);
      big.setColor(Color.yellow);

      // Print the memory pool name.
      big.drawString(mp.getName(), x1 + x2 / 2, (float) y1 + ascent + 0.5f);

      // Print the memory used by this memory pool.
      usedStr = String.valueOf((int) usedMemory / 1024) + "K used";
      big.setColor(Color.green);
      big.drawString(usedStr, x1 + 4, y1 + y2 - descent);

      // Calculate remaining size
      float ssH = ascent + descent;
      float remainingHeight = (float) (y2 - (ssH * 2) - 0.5f);
      float blockHeight = remainingHeight / 10;
      float blockWidth = 20.0f;
      float remainingWidth = (float) (x2 - blockWidth - 10);

      // .. Memory Free ..
      big.setColor(mfColor);
      int MemUsage = (int) (((totalMemory - usedMemory) / totalMemory) * 10);
      int i = 0;
      for (; i < MemUsage; i++) {
        mfRect.setRect(
            x1 + 5, (float) y1 + ssH + i * blockHeight, blockWidth, (float) blockHeight - 1);
        big.fill(mfRect);
      }

      // .. Memory Used ..
      big.setColor(Color.green);
      for (; i < 10; i++) {
        muRect.setRect(
            x1 + 5, (float) y1 + ssH + i * blockHeight, blockWidth, (float) blockHeight - 1);
        big.fill(muRect);
      }

      // .. Draw History Graph ..
      if (remainingWidth <= 30) remainingWidth = (float) 30;
      if (remainingHeight <= ssH) remainingHeight = (float) ssH;
      big.setColor(graphColor);
      int graphX = x1 + 30;
      int graphY = y1 + (int) ssH;
      int graphW = (int) remainingWidth;
      int graphH = (int) remainingHeight;

      graphOutlineRect.setRect(graphX, graphY, graphW, graphH);
      big.draw(graphOutlineRect);

      int graphRow = graphH / 10;

      // .. Draw row ..
      for (int j = graphY; j <= graphH + graphY; j += graphRow) {
        graphLine.setLine(graphX, j, graphX + graphW, j);
        big.draw(graphLine);
      }

      // .. Draw animated column movement ..
      int graphColumn = graphW / 15;

      if (columnInc == 0) {
        columnInc = graphColumn;
      }

      for (int j = graphX + columnInc; j < graphW + graphX; j += graphColumn) {
        graphLine.setLine(j, graphY, j, graphY + graphH);
        big.draw(graphLine);
      }

      --columnInc;

      // Plot memory usage by this memory pool.
      if (usedMem[npool] == null) {
        usedMem[npool] = new float[usageHistCount];
        ptNum[npool] = 0;
      }

      // save memory usage history.
      usedMem[npool][ptNum[npool]] = usedMemory;

      big.setColor(Color.yellow);

      int w1; // width of memory usage history.
      if (ptNum[npool] > graphW) {
        w1 = graphW;
      } else {
        w1 = ptNum[npool];
      }

      for (int j = graphX + graphW - w1, k = ptNum[npool] - w1; k < ptNum[npool]; k++, j++) {
        if (k != 0) {
          if (usedMem[npool][k] != usedMem[npool][k - 1]) {
            int h1 =
                (int) (graphY + graphH * ((totalMemory - usedMem[npool][k - 1]) / totalMemory));
            int h2 = (int) (graphY + graphH * ((totalMemory - usedMem[npool][k]) / totalMemory));
            big.drawLine(j - 1, h1, j, h2);
          } else {
            int h1 = (int) (graphY + graphH * ((totalMemory - usedMem[npool][k]) / totalMemory));
            big.fillRect(j, h1, 1, 1);
          }
        }
      }
      if (ptNum[npool] + 2 == usedMem[npool].length) {
        // throw out oldest point
        for (int j = 1; j < ptNum[npool]; j++) {
          usedMem[npool][j - 1] = usedMem[npool][j];
        }
        --ptNum[npool];
      } else {
        ptNum[npool]++;
      }
    }
 private final void paintImage(Point pt) {
   tree.paintImmediately(rect2D.getBounds());
   rect2D.setRect((int) pt.getX(), (int) pt.getY(), image.getWidth(), image.getHeight());
   tree.getGraphics().drawImage(image, (int) pt.getX(), (int) pt.getY(), tree);
 }
示例#26
0
    public void paint(Graphics g) {

      if (big == null) {
        return;
      }

      big.setBackground(getBackground());
      big.clearRect(0, 0, w, h);

      float freeMemory = (float) r.freeMemory();
      float totalMemory = (float) r.totalMemory();

      // .. Draw allocated and used strings ..
      big.setColor(GREEN);
      big.drawString(
          String.valueOf((int) totalMemory / 1024) + "K allocated", 4.0f, (float) ascent + 0.5f);
      usedStr = String.valueOf(((int) (totalMemory - freeMemory)) / 1024) + "K used";
      big.drawString(usedStr, 4, h - descent);

      // Calculate remaining size
      float ssH = ascent + descent;
      float remainingHeight = (float) (h - (ssH * 2) - 0.5f);
      float blockHeight = remainingHeight / 10;
      float blockWidth = 20.0f;
      float remainingWidth = (float) (w - blockWidth - 10);

      // .. Memory Free ..
      big.setColor(mfColor);
      int MemUsage = (int) ((freeMemory / totalMemory) * 10);
      int i = 0;
      for (; i < MemUsage; i++) {
        mfRect.setRect(5, (float) ssH + i * blockHeight, blockWidth, (float) blockHeight - 1);
        big.fill(mfRect);
      }

      // .. Memory Used ..
      big.setColor(GREEN);
      for (; i < 10; i++) {
        muRect.setRect(5, (float) ssH + i * blockHeight, blockWidth, (float) blockHeight - 1);
        big.fill(muRect);
      }

      // .. Draw History Graph ..
      big.setColor(graphColor);
      int graphX = 30;
      int graphY = (int) ssH;
      int graphW = w - graphX - 5;
      int graphH = (int) remainingHeight;
      graphOutlineRect.setRect(graphX, graphY, graphW, graphH);
      big.draw(graphOutlineRect);

      int graphRow = graphH / 10;

      // .. Draw row ..
      for (int j = graphY; j <= graphH + graphY; j += graphRow) {
        graphLine.setLine(graphX, j, graphX + graphW, j);
        big.draw(graphLine);
      }

      // .. Draw animated column movement ..
      int graphColumn = graphW / 15;

      if (columnInc == 0) {
        columnInc = graphColumn;
      }

      for (int j = graphX + columnInc; j < graphW + graphX; j += graphColumn) {
        graphLine.setLine(j, graphY, j, graphY + graphH);
        big.draw(graphLine);
      }

      --columnInc;

      if (pts == null) {
        pts = new int[graphW];
        ptNum = 0;
      } else if (pts.length != graphW) {
        int tmp[] = null;
        if (ptNum < graphW) {
          tmp = new int[ptNum];
          System.arraycopy(pts, 0, tmp, 0, tmp.length);
        } else {
          tmp = new int[graphW];
          System.arraycopy(pts, pts.length - tmp.length, tmp, 0, tmp.length);
          ptNum = tmp.length - 2;
        }
        pts = new int[graphW];
        System.arraycopy(tmp, 0, pts, 0, tmp.length);
      } else {
        big.setColor(YELLOW);
        pts[ptNum] = (int) (graphY + graphH * (freeMemory / totalMemory));
        for (int j = graphX + graphW - ptNum, k = 0; k < ptNum; k++, j++) {
          if (k != 0) {
            if (pts[k] != pts[k - 1]) {
              big.drawLine(j - 1, pts[k - 1], j, pts[k]);
            } else {
              big.fillRect(j, pts[k], 1, 1);
            }
          }
        }
        if (ptNum + 2 == pts.length) {
          // throw out oldest point
          for (int j = 1; j < ptNum; j++) {
            pts[j - 1] = pts[j];
          }
          --ptNum;
        } else {
          ptNum++;
        }
      }
      g.drawImage(bimg, 0, 0, this);
    }