Example usage for java.awt.geom AffineTransform transform

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

Introduction

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

Prototype

public Point2D transform(Point2D ptSrc, Point2D ptDst) 

Source Link

Document

Transforms the specified ptSrc and stores the result in ptDst .

Usage

From source file:edu.valelab.gaussianfit.datasettransformations.CoordinateMapper.java

private PointMap makeCleanedPointMap() {
    PointMap cleanedPointMap = pointMap_.copy();
    // TODO: copy controlPOints to cleanedControlPoints
    boolean continueQualityCheck = true;
    int nrOfRemovedSpots = 0;

    while (continueQualityCheck && cleanedPointMap.size() > 4) {
        // quality control on our new coordinate mapper.  
        // Apply an affine transform on our data and check distribution 

        CoordinateMapper.PointMap corPoints = new CoordinateMapper.PointMap();
        List<Double> distances = new ArrayList<Double>();
        double maxDistance = 0.0;
        AffineTransform af = generateAffineTransformFromPointPairs(cleanedPointMap);
        Point2D.Double maxPairKey = null;
        for (Map.Entry pair : cleanedPointMap.entrySet()) {
            Point2D.Double uPt = (Point2D.Double) pair.getValue();
            Point2D.Double otherPt = (Point2D.Double) pair.getKey();
            Point2D.Double corPt = (Point2D.Double) af.transform(otherPt, null);
            corPoints.put(uPt, corPt);//from   www. ja  v a 2  s . c  om
            double distance = Math.sqrt(NearestPoint2D.distance2(uPt, corPt));
            if (distance > maxDistance) {
                maxDistance = distance;
                maxPairKey = otherPt;
            }
            distances.add(distance);
        }
        Double avg = ListUtils.listAvg(distances);
        Double stdDev = ListUtils.listStdDev(distances, avg);

        // Quality control check
        if (2 * stdDev > avg) {
            nrOfRemovedSpots += 1;
            cleanedPointMap.remove(maxPairKey);
        } else {
            continueQualityCheck = false;
            ij.IJ.log("Removed " + nrOfRemovedSpots + " pairs, " + " avg. distance: " + avg + ", std. dev: "
                    + stdDev);
        }
    }
    return cleanedPointMap;
}

From source file:acmi.l2.clientmod.l2smr.Controller.java

@FXML
private void exportSM() {
    List<Actor> actors = this.table.getSelectionModel().getSelectedItems().stream().map(Actor::clone)
            .collect(Collectors.toList());

    if (actors.isEmpty())
        return;// ww  w  .  ja  v  a2  s.  c o  m

    int xy = 18 | (20 << 8);
    try {
        xy = getXY(getMapsDir(), this.unrChooser.getSelectionModel().getSelectedItem());
    } catch (IOException e) {
        showAlert(Alert.AlertType.WARNING, "Export", null, "Couldn't read map coords, using default 18_20");
    }
    ImportExportDialog dlg = new ImportExportDialog(xy & 0xff, (xy >> 8) & 0xff);
    ButtonType response = dlg.showAndWait().orElse(null);
    if (response != ButtonType.OK)
        return;

    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON", "*.json"));
    fileChooser.setTitle("Save");
    File file = fileChooser.showSaveDialog(getStage());
    if (file == null)
        return;

    longTask(progress -> {
        float x = dlg.getX(), y = dlg.getY(), z = dlg.getZ();
        double angle = dlg.getAngle();
        AffineTransform rotate = AffineTransform.getRotateInstance(Math.PI * angle / 180, x, y);
        AffineTransform translate = AffineTransform.getTranslateInstance(-x, -y);

        for (int i = 0; i < actors.size(); i++) {
            progress.accept((double) i / actors.size());
            Actor o = actors.get(i);
            Point2D.Float point = new Point2D.Float(o.getX(), o.getY());
            rotate.transform(point, point);
            translate.transform(point, point);

            o.setX(point.x);
            o.setY(point.y);
            o.setZ(o.getZ() - z);
            if (o.getYaw() == null)
                o.setYaw(0);
            o.setYaw(((int) (o.getYaw() + angle * 0xFFFF / 360)) & 0xFFFF);
        }
        progress.accept(-1.0);

        L2Map map = new L2Map(x, y, z, actors);
        ObjectMapper objectMapper = new ObjectMapper();

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            objectMapper.writeValue(baos, map);

            try (OutputStream fos = new FileOutputStream(file)) {
                baos.writeTo(fos);
            }
        }
    }, e -> onException("Export failed", e));
}

From source file:acmi.l2.clientmod.l2smr.Controller.java

@FXML
private void importSM() {
    if (this.unrChooser.getSelectionModel().getSelectedItem() == null)
        return;//from  ww w .  j a va 2s .c om

    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("JSON", "*.json"));
    fileChooser.setTitle("Open");
    File file = fileChooser.showOpenDialog(getStage());
    if (file == null)
        return;

    int xy = 18 | (20 << 8);
    try {
        xy = getXY(getMapsDir(), this.unrChooser.getSelectionModel().getSelectedItem());
    } catch (IOException e) {
        showAlert(Alert.AlertType.WARNING, "Import", null, "Couldn't read map coords, using default 18_20");
    }

    ImportExportDialog dlg = new ImportExportDialog(xy & 0xff, (xy >> 8) & 0xff);
    ButtonType response = dlg.showAndWait().orElse(null);
    if (response != ButtonType.OK)
        return;

    AffineTransform transform = AffineTransform.getRotateInstance(Math.PI * dlg.getAngle() / 180);

    ObjectMapper objectMapper = new ObjectMapper();
    try {
        L2Map map = objectMapper.readValue(file, L2Map.class);

        if (map.getStaticMeshes().isEmpty())
            return;

        longTask(progress -> {
            try (UnrealPackage up = new UnrealPackage(
                    new File(getMapsDir(), unrChooser.getSelectionModel().getSelectedItem()), false)) {
                up.addImportEntries(map.getStaticMeshes().stream().collect(
                        Collectors.toMap(Actor::getStaticMesh, a -> "Engine.StaticMesh", (o1, o2) -> o1)));

                for (int i = 0; i < map.getStaticMeshes().size(); i++) {
                    Actor actor = map.getStaticMeshes().get(i);

                    int newActorInd = StaticMeshActorUtil.addStaticMeshActor(up,
                            up.objectReferenceByName(actor.getStaticMesh(), c -> true), actor.getActorClass(),
                            true, true, oldFormat.isSelected());
                    UnrealPackage.ExportEntry newActor = (UnrealPackage.ExportEntry) up
                            .objectReference(newActorInd);

                    actor.setActorName(newActor.getObjectInnerFullName());
                    actor.setStaticMeshRef(up.objectReferenceByName(actor.getStaticMesh(), c -> true));

                    byte[] bytes = newActor.getObjectRawData();
                    Offsets offsets = StaticMeshActorUtil.getOffsets(bytes, up);

                    Point2D.Float point = new Point2D.Float(actor.getX(), actor.getY());
                    transform.transform(point, point);

                    actor.setX(dlg.getX() + point.x);
                    actor.setY(dlg.getY() + point.y);
                    actor.setZ(dlg.getZ() + actor.getZ());

                    actor.setYaw((actor.getYaw() + (int) (0xFFFF * dlg.getAngle() / 360)) & 0xFFFF);

                    StaticMeshActorUtil.setLocation(bytes, offsets, actor.getX(), actor.getY(), actor.getZ());
                    StaticMeshActorUtil.setRotation(bytes, offsets, actor.getPitch(), actor.getYaw(),
                            actor.getRoll());
                    if (actor.getScale3D() != null)
                        StaticMeshActorUtil.setDrawScale3D(bytes, offsets, actor.getScaleX(), actor.getScaleY(),
                                actor.getScaleZ());
                    if (actor.getScale() != null)
                        StaticMeshActorUtil.setDrawScale(bytes, offsets, actor.getScale());
                    if (actor.getRotationRate() != null)
                        StaticMeshActorUtil.setRotationRate(bytes, offsets, actor.getPitchRate(),
                                actor.getYawRate(), actor.getRollRate());
                    if (actor.getZoneRenderState() != null)
                        bytes = StaticMeshActorUtil.setZoneRenderState(bytes, offsets,
                                actor.getZoneRenderState());

                    newActor.setObjectRawData(bytes);

                    progress.accept((double) i / map.getStaticMeshes().size());
                }
            }

            Platform.runLater(() -> {
                String unr = unrChooser.getSelectionModel().getSelectedItem();
                Actor act = map.getStaticMeshes().get(map.getStaticMeshes().size() - 1);

                unrChooser.getSelectionModel().clearSelection();
                unrChooser.getSelectionModel().select(unr);

                table.getSelectionModel().select(act);
                table.scrollTo(act);
            });
        }, e -> onException("Import failed", e));
    } catch (IOException e) {
        onException("Import failed", e);
    }
}

From source file:nl.b3p.imagetool.ImageTool.java

public static Point transformToScreen(Point source, int bboxSrid, Bbox bbox, int width, int height)
        throws Exception {
    ReferencedEnvelope re = new ReferencedEnvelope(bbox.getMinx(), bbox.getMaxx(), bbox.getMiny(),
            bbox.getMaxy(), CRS.decode("EPSG:" + bboxSrid));
    AffineTransform transform = RendererUtilities.worldToScreenTransform(re, new Rectangle(width, height));
    Point result = new Point();
    transform.transform(source, result);
    return result;
}

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

private void saveAbsolutePosition(String id, PageViewport pv, int relativeIPP, int relativeBPP,
        AffineTransform tf) {
    Point position = new Point(relativeIPP, relativeBPP);
    tf.transform(position, position);
    idPositions.put(id, position);//  w ww.ja v  a 2s  . co  m
    // is there already a GoTo action waiting to be completed?
    GoToXYAction action = (GoToXYAction) actionSet.get(id);
    if (action != null) {
        noteGoToPosition(action, pv, position);
    }
}

From source file:org.apache.fop.render.pcl.PCLRenderingUtil.java

/**
 * Returns a coordinate in PCL's coordinate system when given a coordinate in the user
 * coordinate system./*from  w  ww  .j  av a  2  s .  c  o  m*/
 * @param x the X coordinate
 * @param y the Y coordinate
 * @param transform the currently valid transformation matrix
 * @param pageDefinition the currently valid page definition
 * @param printDirection the currently valid print direction
 * @return the transformed point
 */
public static Point2D transformedPoint(int x, int y, AffineTransform transform,
        PCLPageDefinition pageDefinition, int printDirection) {
    if (log.isTraceEnabled()) {
        log.trace("Current transform: " + transform);
    }
    Point2D.Float orgPoint = new Point2D.Float(x, y);
    Point2D.Float transPoint = new Point2D.Float();
    transform.transform(orgPoint, transPoint);
    //At this point we have the absolute position in FOP's coordinate system

    //Now get PCL coordinates taking the current print direction and the logical page
    //into account.
    Dimension pageSize = pageDefinition.getPhysicalPageSize();
    Rectangle logRect = pageDefinition.getLogicalPageRect();
    switch (printDirection) {
    case 0:
        transPoint.x -= logRect.x;
        transPoint.y -= logRect.y;
        break;
    case 90:
        float ty = transPoint.x;
        transPoint.x = pageSize.height - transPoint.y;
        transPoint.y = ty;
        transPoint.x -= logRect.y;
        transPoint.y -= logRect.x;
        break;
    case 180:
        transPoint.x = pageSize.width - transPoint.x;
        transPoint.y = pageSize.height - transPoint.y;
        transPoint.x -= pageSize.width - logRect.x - logRect.width;
        transPoint.y -= pageSize.height - logRect.y - logRect.height;
        //The next line is odd and is probably necessary due to the default value of the
        //Text Length command: "1/2 inch less than maximum text length"
        //I wonder why this isn't necessary for the 90 degree rotation. *shrug*
        transPoint.y -= UnitConv.in2mpt(0.5);
        break;
    case 270:
        float tx = transPoint.y;
        transPoint.y = pageSize.width - transPoint.x;
        transPoint.x = tx;
        transPoint.x -= pageSize.height - logRect.y - logRect.height;
        transPoint.y -= pageSize.width - logRect.x - logRect.width;
        break;
    default:
        throw new IllegalStateException("Illegal print direction: " + printDirection);
    }
    return transPoint;
}

From source file:org.apache.fop.svg.AbstractFOPTextPainter.java

/**
 * Paint a single text run on the Graphics2D at a given location.
 * @param run the text run to paint/*from w  w w .java 2  s .com*/
 * @param g2d the Graphics2D to paint to
 * @param loc the current location of the "cursor"
 * @return the new location of the "cursor" after painting the text run
 */
protected Point2D paintTextRun(StrokingTextPainter.TextRun run, Graphics2D g2d, Point2D loc) {
    AttributedCharacterIterator aci = run.getACI();
    aci.first();

    updateLocationFromACI(aci, loc);
    AffineTransform at = g2d.getTransform();
    loc = at.transform(loc, null);

    // font
    Font font = getFont(aci);
    if (font != null) {
        nativeTextHandler.setOverrideFont(font);
    }

    // color
    TextPaintInfo tpi = (TextPaintInfo) aci
            .getAttribute(GVTAttributedCharacterIterator.TextAttribute.PAINT_INFO);
    if (tpi == null) {
        return loc;
    }
    Paint foreground = tpi.fillPaint;
    if (foreground instanceof Color) {
        Color col = (Color) foreground;
        g2d.setColor(col);
    }
    g2d.setPaint(foreground);

    // text anchor
    TextNode.Anchor anchor = (TextNode.Anchor) aci
            .getAttribute(GVTAttributedCharacterIterator.TextAttribute.ANCHOR_TYPE);

    // text
    String txt = getText(aci);
    float advance = getStringWidth(txt, font);
    float tx = 0;
    if (anchor != null) {
        switch (anchor.getType()) {
        case TextNode.Anchor.ANCHOR_MIDDLE:
            tx = -advance / 2;
            break;
        case TextNode.Anchor.ANCHOR_END:
            tx = -advance;
            break;
        default: //nop
        }
    }

    // draw string
    double x = loc.getX();
    double y = loc.getY();
    try {
        try {
            nativeTextHandler.drawString(g2d, txt, (float) x + tx, (float) y);
        } catch (IOException ioe) {
            if (g2d instanceof AFPGraphics2D) {
                ((AFPGraphics2D) g2d).handleIOException(ioe);
            }
        }
    } finally {
        nativeTextHandler.setOverrideFont(null);
    }
    loc.setLocation(loc.getX() + advance, loc.getY());
    return loc;
}

From source file:org.apache.pdfbox.pdmodel.font.PDSimpleFont.java

/**
 * This will draw a string on a canvas using the font.
 *
 * @param g2d The graphics to draw onto.
 * @param at The transformation matrix with all information for scaling and shearing of the font.
 * @param x The x coordinate to draw at.
 * @param y The y coordinate to draw at.
 * @param glyphs The GlyphVector containing the glyphs to be drawn.
 *
 *///from  www  . ja  va2s .c o  m
protected void writeFont(final Graphics2D g2d, final AffineTransform at, final float x, final float y,
        final GlyphVector glyphs) {
    // check if we have a rotation
    if (!at.isIdentity()) {
        try {
            AffineTransform atInv = at.createInverse();
            // do only apply the size of the transform, rotation will be realized by rotating the graphics,
            // otherwise the hp printers will not render the font
            // apply the transformation to the graphics, which should be the same as applying the
            // transformation itself to the text
            g2d.transform(at);
            // translate the coordinates
            Point2D.Float newXy = new Point2D.Float(x, y);
            atInv.transform(new Point2D.Float(x, y), newXy);
            g2d.drawGlyphVector(glyphs, (float) newXy.getX(), (float) newXy.getY());
            // restore the original transformation
            g2d.transform(atInv);
        } catch (NoninvertibleTransformException e) {
            LOG.error("Error in " + getClass().getName() + ".writeFont", e);
        }
    } else {
        g2d.drawGlyphVector(glyphs, x, y);
    }
}

From source file:org.apache.pdfbox.pdmodel.graphics.shading.GouraudShadingContext.java

/**
 * Read a vertex from the bit input stream performs interpolations.
 *
 * @param input bit input stream//  w ww . j av  a  2 s  .  com
 * @param maxSrcCoord max value for source coordinate (2^bits-1)
 * @param maxSrcColor max value for source color (2^bits-1)
 * @param rangeX dest range for X
 * @param rangeY dest range for Y
 * @param colRangeTab dest range array for colors
 * @param matrix the pattern matrix concatenated with that of the parent content stream
 * @return a new vertex with the flag and the interpolated values
 * @throws IOException if something went wrong
 */
protected Vertex readVertex(ImageInputStream input, long maxSrcCoord, long maxSrcColor, PDRange rangeX,
        PDRange rangeY, PDRange[] colRangeTab, Matrix matrix, AffineTransform xform) throws IOException {
    float[] colorComponentTab = new float[numberOfColorComponents];
    long x = input.readBits(bitsPerCoordinate);
    long y = input.readBits(bitsPerCoordinate);
    float dstX = interpolate(x, maxSrcCoord, rangeX.getMin(), rangeX.getMax());
    float dstY = interpolate(y, maxSrcCoord, rangeY.getMin(), rangeY.getMax());
    LOG.debug("coord: " + String.format("[%06X,%06X] -> [%f,%f]", x, y, dstX, dstY));
    Point2D p = matrix.transformPoint(dstX, dstY);
    xform.transform(p, p);

    for (int n = 0; n < numberOfColorComponents; ++n) {
        int color = (int) input.readBits(bitsPerColorComponent);
        colorComponentTab[n] = interpolate(color, maxSrcColor, colRangeTab[n].getMin(),
                colRangeTab[n].getMax());
        LOG.debug("color[" + n + "]: " + color + "/" + String.format("%02x", color) + "-> color[" + n + "]: "
                + colorComponentTab[n]);
    }
    return new Vertex(p, colorComponentTab);
}

From source file:org.apache.pdfbox.pdmodel.graphics.shading.PatchMeshesShadingContext.java

/**
 * Read a single patch from a data stream, a patch contains information of its coordinates and
 * color parameters./*from ww  w.j a v a 2s.  c  o m*/
 *
 * @param input the image source data stream
 * @param isFree whether this is a free patch
 * @param implicitEdge implicit edge when a patch is not free, otherwise it's not used
 * @param implicitCornerColor implicit colors when a patch is not free, otherwise it's not used
 * @param maxSrcCoord the maximum coordinate value calculated from source data
 * @param maxSrcColor the maximum color value calculated from source data
 * @param rangeX range for coordinate x
 * @param rangeY range for coordinate y
 * @param colRange range for color
 * @param matrix the pattern matrix concatenated with that of the parent content stream
 * @param xform transformation for user to device space
 * @param controlPoints number of control points, 12 for type 6 shading and 16 for type 7 shading
 * @return a single patch
 * @throws IOException when something went wrong
 */
protected Patch readPatch(ImageInputStream input, boolean isFree, Point2D[] implicitEdge,
        float[][] implicitCornerColor, long maxSrcCoord, long maxSrcColor, PDRange rangeX, PDRange rangeY,
        PDRange[] colRange, Matrix matrix, AffineTransform xform, int controlPoints) throws IOException {
    float[][] color = new float[4][numberOfColorComponents];
    Point2D[] points = new Point2D[controlPoints];
    int pStart = 4, cStart = 2;
    if (isFree) {
        pStart = 0;
        cStart = 0;
    } else {
        points[0] = implicitEdge[0];
        points[1] = implicitEdge[1];
        points[2] = implicitEdge[2];
        points[3] = implicitEdge[3];

        for (int i = 0; i < numberOfColorComponents; i++) {
            color[0][i] = implicitCornerColor[0][i];
            color[1][i] = implicitCornerColor[1][i];
        }
    }

    try {
        for (int i = pStart; i < controlPoints; i++) {
            long x = input.readBits(bitsPerCoordinate);
            long y = input.readBits(bitsPerCoordinate);
            float px = interpolate(x, maxSrcCoord, rangeX.getMin(), rangeX.getMax());
            float py = interpolate(y, maxSrcCoord, rangeY.getMin(), rangeY.getMax());
            Point2D p = matrix.transformPoint(px, py);
            xform.transform(p, p);
            points[i] = p;
        }
        for (int i = cStart; i < 4; i++) {
            for (int j = 0; j < numberOfColorComponents; j++) {
                long c = input.readBits(bitsPerColorComponent);
                color[i][j] = interpolate(c, maxSrcColor, colRange[j].getMin(), colRange[j].getMax());
            }
        }
    } catch (EOFException ex) {
        LOG.debug("EOF");
        return null;
    }
    return generatePatch(points, color);
}