Java Code Examples for org.locationtech.jts.geom.Geometry#getGeometryN()

The following examples show how to use org.locationtech.jts.geom.Geometry#getGeometryN() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OmsLW01_ChannelPolygonMerger.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inBankfull);

    List<Geometry> geoms = FeatureUtilities.featureCollectionToGeometriesList(inBankfull, true, null);

    // creates a unique feature with multipolygons
    Geometry union = CascadedPolygonUnion.union(geoms);

    // makes a buffer of each geometry in the feature and merges the touching geometries
    Geometry buffer = union.buffer(0.05);

    // splits the remaining geometries (not touching)
    List<Geometry> newGeoms = new ArrayList<Geometry>();
    for( int i = 0; i < buffer.getNumGeometries(); i++ ) {
        Geometry geometryN = buffer.getGeometryN(i);
        if (geometryN instanceof Polygon) {
            newGeoms.add(geometryN);
        }
    }

    outBankfull = FeatureUtilities.featureCollectionFromGeometry(inBankfull.getBounds().getCoordinateReferenceSystem(),
            newGeoms.toArray(GeometryUtilities.TYPE_POLYGON));

}
 
Example 2
Source File: FeatureCollectionPointsLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private void addPoint( SimpleFeature pointFeature ) {
    Geometry geometry = (Geometry) pointFeature.getDefaultGeometry();
    if (geometry == null) {
        return;
    }
    int numGeometries = geometry.getNumGeometries();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometryN = geometry.getGeometryN(i);
        if (geometryN instanceof Point) {
            Point point = (Point) geometryN;
            FeaturePoint marker = new FeaturePoint(Position.fromDegrees(point.getY(), point.getX(), 0), featureStoreInfo);
            marker.setFeature(pointFeature);
            marker.setAltitudeMode(WorldWind.CLAMP_TO_GROUND);
            marker.setAttributes(basicMarkerAttributes);
            addRenderable(marker);
        }
    }
}
 
Example 3
Source File: OmsGridsGenerator.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private void createPoints( CoordinateReferenceSystem crs, GeometryFactory gf, List<LineString> verticals,
        List<LineString> horizontals ) {
    outMap = new DefaultFeatureCollection();
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName(POINT);
    b.setCRS(crs);
    b.add("the_geom", Point.class);
    b.add("id", Long.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder fbuilder = new SimpleFeatureBuilder(type);

    Geometry gVer = gf.createMultiLineString(verticals.toArray(new LineString[0]));
    Geometry gHor = gf.createMultiLineString(horizontals.toArray(new LineString[0]));

    Geometry intersection = gHor.intersection(gVer);

    long index = 0;
    int numGeometries = intersection.getNumGeometries();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometry = intersection.getGeometryN(i);
        Object[] values = new Object[]{geometry, index++};
        fbuilder.addAll(values);
        SimpleFeature feature = fbuilder.buildFeature(null);
        ((DefaultFeatureCollection) outMap).add(feature);
    }
}
 
Example 4
Source File: JtsGeometrySerde.java    From presto with Apache License 2.0 6 votes vote down vote up
private static void writeGeometryCollection(Geometry collection, DynamicSliceOutput output)
{
    output.appendByte(GeometrySerializationType.GEOMETRY_COLLECTION.code());
    for (int geometryIndex = 0; geometryIndex < collection.getNumGeometries(); geometryIndex++) {
        Geometry geometry = collection.getGeometryN(geometryIndex);
        int startPosition = output.size();

        // leave 4 bytes for the shape length
        output.appendInt(0);
        writeGeometry(geometry, output);

        int endPosition = output.size();
        int length = endPosition - startPosition - Integer.BYTES;

        output.getUnderlyingSlice().setInt(startPosition, length);
    }
}
 
Example 5
Source File: GeometryUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static List<Geometry> extractSubGeometries( Geometry geometry ) {
    List<Geometry> geometriesList = new ArrayList<Geometry>();
    int numGeometries = geometry.getNumGeometries();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometryN = geometry.getGeometryN(i);
        geometriesList.add(geometryN);
    }
    return geometriesList;
}
 
Example 6
Source File: OmsAdige.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private void linkBasinWithNetwork() throws Exception {
    FeatureExtender fExt = new FeatureExtender(inNetwork.getSchema(), new String[]{NetworkChannel.NETNUMNAME},
            new Class[]{Integer.class});

    DefaultFeatureCollection newCollection = new DefaultFeatureCollection();

    SimpleFeatureIterator hillslopeFeatures = inHillslope.features();
    while( hillslopeFeatures.hasNext() ) {
        SimpleFeature hFeature = hillslopeFeatures.next();
        Object netNum = hFeature.getAttribute(NetworkChannel.NETNUMNAME);
        Geometry hGeometry = (Geometry) hFeature.getDefaultGeometry();
        PreparedGeometry preparedHGeometry = PreparedGeometryFactory.prepare(hGeometry);
        SimpleFeatureIterator netFeatures = inNetwork.features();
        while( netFeatures.hasNext() ) {
            SimpleFeature nFeature = netFeatures.next();
            Geometry geometry = (Geometry) nFeature.getDefaultGeometry();
            if (geometry.getNumGeometries() != 1) {
                throw new ModelsRuntimeException("The network geometries have to be single lines.", this);
            }
            LineString nLine = (LineString) geometry.getGeometryN(0);
            Point startPoint = nLine.getStartPoint();
            if (preparedHGeometry.contains(startPoint)) {
                SimpleFeature extendFeature = fExt.extendFeature(nFeature, new Object[]{netNum});
                newCollection.add(extendFeature);
                break;
            }
        }
    }
    inNetwork = newCollection;
}
 
Example 7
Source File: OmsLW09_NetworBufferMergerHolesRemover.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private List<Geometry> removeHoles( Geometry cleanPolygon ) {
    ArrayList<Geometry> gl = new ArrayList<Geometry>();
    for( int i = 0; i < cleanPolygon.getNumGeometries(); i++ ) {
        Polygon geometryN = (Polygon) cleanPolygon.getGeometryN(i);
        LineString exteriorRing = geometryN.getExteriorRing();
        Coordinate[] ringCoordinates = exteriorRing.getCoordinates();
        Polygon polygon = gf.createPolygon(ringCoordinates);
        gl.add(polygon);
    }
    return gl;
}
 
Example 8
Source File: RasterizedSpatialiteLasLayer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private static GeneralPath polygonToPath( PointTransformation pointTransformation, Geometry polygon, int finalTileSize ) {
    GeneralPath p = new GeneralPath();

    int numGeometries = polygon.getNumGeometries();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometryN = polygon.getGeometryN(i);
        Coordinate[] coordinates = geometryN.getCoordinates();
        final Point2D newP = new Point2D.Double();
        for( int j = 0; j < coordinates.length; j++ ) {
            pointTransformation.transform(coordinates[j], newP);
            double x = newP.getX();
            double y = newP.getY();
            if (x < 0) {
                x = 0;
            }
            if (y < 0) {
                y = 0;
            }
            if (x > TILESIZE) {
                x = TILESIZE;
            }
            if (y > TILESIZE) {
                y = TILESIZE;
            }

            if (j == 0) {
                p.moveTo(x, y);
            } else {
                p.lineTo(x, y);
            }
        }
    }
    p.closePath();
    return p;
}
 
Example 9
Source File: GeopackageVectorLayer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private void addLine( Geometry geometry, BasicShapeAttributes shapeAttributes, boolean convert ) {
        if (geometry == null) {
            return;
        }
        Coordinate[] coordinates = geometry.getCoordinates();
        if (coordinates.length < 2)
            return;

        int numGeometries = geometry.getNumGeometries();
        for( int i = 0; i < numGeometries; i++ ) {
            Geometry geometryN = geometry.getGeometryN(i);
            if (geometryN instanceof LineString) {
                LineString line = (LineString) geometryN;
                Coordinate[] lineCoords = line.getCoordinates();
                int numVertices = lineCoords.length;
                List<Position> verticesList = new ArrayList<>(numVertices);
                for( int j = 0; j < numVertices; j++ ) {
                    Coordinate c = lineCoords[j];
                    if (convert) {
                        c = MercatorUtils.convert3857To4326(c);
                    }
                    bounds.expandToInclude(c);
                    verticesList.add(Position.fromDegrees(c.y, c.x));
                }
                FeatureLine path = new FeatureLine(verticesList, null);
//                path.setFeature(lineFeature);
                path.setAltitudeMode(mElevationMode);
                path.setAttributes(shapeAttributes);
                path.setHighlightAttributes(highlightAttrs);

                addRenderable(path);
            }
        }
    }
 
Example 10
Source File: ShapefilesFolderLayer.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private void addLine( SimpleFeature lineFeature, BasicShapeAttributes shapeAttributes ) {
    Geometry geometry = (Geometry) lineFeature.getDefaultGeometry();
    if (geometry == null) {
        return;
    }
    Coordinate[] coordinates = geometry.getCoordinates();
    if (coordinates.length < 2)
        return;

    int numGeometries = geometry.getNumGeometries();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometryN = geometry.getGeometryN(i);
        if (geometryN instanceof LineString) {
            LineString line = (LineString) geometryN;
            Coordinate[] lineCoords = line.getCoordinates();
            int numVertices = lineCoords.length;
            List<Position> verticesList = new ArrayList<>(numVertices);
            for( int j = 0; j < numVertices; j++ ) {
                Coordinate c = lineCoords[j];
                verticesList.add(Position.fromDegrees(c.y, c.x));
            }
            FeatureLine path = new FeatureLine(verticesList, null);
            path.setFeature(lineFeature);
            path.setAltitudeMode(mElevationMode);
            path.setAttributes(shapeAttributes);
            path.setHighlightAttributes(highlightAttrs);

            addRenderable(path);
        }
    }
}
 
Example 11
Source File: OmsLW08_NetworkBufferWidthCalculator.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
private LineString getLineGeometry( SimpleFeature f ) {
    String pfaf = f.getAttribute(PFAF).toString();
    String linkID = f.getAttribute(LINKID).toString();
    String id = pfaf + "_" + linkID;
    Geometry geometry = pfafId2WidthLine.get(id);
    Geometry geometryN = geometry.getGeometryN(0);
    return (LineString) geometryN;
}
 
Example 12
Source File: OmsLineSmootherMcMaster.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if the given geometry is connected to any other line.
 * 
 * @param geometryN the geometry to test.
 * @return true if the geometry is alone in the space, i.e. not connected at
 *              one of the ends to any other geometry.
 */
private boolean isAlone( Geometry geometryN ) {
    Coordinate[] coordinates = geometryN.getCoordinates();
    if (coordinates.length > 1) {
        Coordinate first = coordinates[0];
        Coordinate last = coordinates[coordinates.length - 1];
        for( SimpleFeature line : linesList ) {
            Geometry lineGeom = (Geometry) line.getDefaultGeometry();
            int numGeometries = lineGeom.getNumGeometries();
            for( int i = 0; i < numGeometries; i++ ) {
                Geometry subGeom = lineGeom.getGeometryN(i);
                Coordinate[] lineCoordinates = subGeom.getCoordinates();
                if (lineCoordinates.length < 2) {
                    continue;
                } else {
                    Coordinate tmpFirst = lineCoordinates[0];
                    Coordinate tmpLast = lineCoordinates[lineCoordinates.length - 1];
                    if (tmpFirst.distance(first) < SAMEPOINTTHRESHOLD || tmpFirst.distance(last) < SAMEPOINTTHRESHOLD
                            || tmpLast.distance(first) < SAMEPOINTTHRESHOLD || tmpLast.distance(last) < SAMEPOINTTHRESHOLD) {
                        return false;
                    }
                }
            }
        }
    }
    // 1 point line or no connection, mark it as alone for removal
    return true;
}
 
Example 13
Source File: TinHandler.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generate a tin from a given coords list. The internal tin geoms array is set from the result.
 * 
 * @param coordinateList the coords to use for the tin generation.
 */
private void generateTin( List<Coordinate> coordinateList ) {
    pm.beginTask("Generate tin...", -1);
    DelaunayTriangulationBuilder b = new DelaunayTriangulationBuilder();
    b.setSites(coordinateList);
    Geometry tinTriangles = b.getTriangles(gf);
    tinGeometries = new Geometry[tinTriangles.getNumGeometries()];
    for( int i = 0; i < tinTriangles.getNumGeometries(); i++ ) {
        tinGeometries[i] = tinTriangles.getGeometryN(i);
    }
    pm.done();
}
 
Example 14
Source File: PolylineShape.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Constructor
 *
 * @param geometry Geometry
 */
public PolylineShape(Geometry geometry) {
    this();
    Coordinate[] cs = geometry.getCoordinates();
    List<PointD> points = new ArrayList();
    for (Coordinate c : cs) {
        points.add(new PointD(c.x, c.y));
    }
    switch (geometry.getGeometryType()) {
        case "MultiLineString":
            this._points = points;
            List<PointD> pp;
            int n = geometry.getNumGeometries();
            _numParts = n;
            List<Integer> partlist = new ArrayList<>();
            int idx = 0;
            for (int i = 0; i < n; i++) {
                LineString poly = (LineString) geometry.getGeometryN(i);
                partlist.add(idx);
                Polyline polyline = new Polyline();
                pp = new ArrayList<>();
                for (int j = idx; j < idx + poly.getNumPoints(); j++) {
                    pp.add(points.get(j));
                }
                polyline.setPointList(pp);
                idx += poly.getNumPoints();
                ((List<Polyline>) this._polylines).add(polyline);
            }
            parts = new int[n];
            for (int i = 0; i < parts.length; i++) {
                parts[i] = partlist.get(i);
            }
            this.setExtent(MIMath.getPointsExtent(_points));
            break;
        default:
            this.setPoints(points);
            break;
    }
}
 
Example 15
Source File: TestBasinShape.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("nls")
public void testBasinShape() throws Exception {
    HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();

    double[][] pitData = HMTestMaps.pitData;
    GridCoverage2D pitCoverage = CoverageUtilities.buildCoverage("pit", pitData, envelopeParams, crs, true);
    double[][] basinsData = HMTestMaps.basinShapeData;
    GridCoverage2D basinsCoverage = CoverageUtilities.buildCoverage("basins", basinsData, envelopeParams, crs, true);

    OmsBasinShape basin = new OmsBasinShape();
    basin.inElev = pitCoverage;
    basin.inBasins = basinsCoverage;
    basin.pm = pm;

    basin.process();

    SimpleFeatureCollection basinsFC = basin.outBasins;

    FeatureIterator<SimpleFeature> basinsIter = basinsFC.features();
    while( basinsIter.hasNext() ) {
        SimpleFeature feature = basinsIter.next();
        Geometry line = (Geometry) feature.getDefaultGeometry();

        int numGeometries = line.getNumGeometries();
        for( int i = 0; i < numGeometries; i++ ) {
            Geometry geometryN = line.getGeometryN(i);
            int length = geometryN.getCoordinates().length;
            if (length == 9) {
                Geometry g1 = new WKTReader().read(geom1Txt);
                assertTrue(geometryN.equals(g1));
            }
            if (length == 5) {
                Geometry g2 = new WKTReader().read(geom2Txt);
                assertTrue(geometryN.equals(g2));
            }
        }
    }
    basinsIter.close();

}
 
Example 16
Source File: DxfUtils.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private static String polygon2Dxf( FeatureMate featureMate, String layerName, String elevationAttrName, boolean suffix ) {
    Geometry geometry = featureMate.getGeometry();
    int numGeometries = geometry.getNumGeometries();
    StringBuilder sb = new StringBuilder();
    for( int g = 0; g < numGeometries; g++ ) {
        Polygon geom = (Polygon) geometry.getGeometryN(g);

        Coordinate[] coords = geom.getExteriorRing().getCoordinates();
        sb.append(DxfGroup.toString(0, POLYLINE));
        sb.append(DxfGroup.toString(8, layerName));

        SimpleFeature feature = featureMate.getFeature();
        handleLTYPE(feature, sb);
        handleELEVATION(feature, sb);
        handleTHICKNESS(feature, sb);
        handleColor(feature, sb);

        double elev = Double.NaN;
        if (elevationAttrName != null) {
            Double tmp = featureMate.getAttribute(elevationAttrName, Double.class);
            if (tmp != null) {
                elev = tmp;
            }
        }

        sb.append(DxfGroup.toString(66, 1));
        sb.append(DxfGroup.toString(10, ZERO));
        sb.append(DxfGroup.toString(20, ZERO));
        coords[0].z = elev;
        if (!Double.isNaN(coords[0].z))
            sb.append(DxfGroup.toString(30, ZERO));
        sb.append(DxfGroup.toString(70, 9));
        for( int i = 0; i < coords.length; i++ ) {
            sb.append(DxfGroup.toString(0, VERTEX));
            sb.append(DxfGroup.toString(8, layerName));
            sb.append(DxfGroup.toString(10, coords[i].x, precision));
            sb.append(DxfGroup.toString(20, coords[i].y, precision));
            coords[i].z = elev;
            if (!Double.isNaN(coords[i].z))
                sb.append(DxfGroup.toString(30, coords[i].z, precision));
            sb.append(DxfGroup.toString(70, 32));
        }
        sb.append(DxfGroup.toString(0, SEQEND));
        for( int h = 0; h < geom.getNumInteriorRing(); h++ ) {
            sb.append(DxfGroup.toString(0, POLYLINE));
            if (suffix)
                sb.append(DxfGroup.toString(8, layerName + SUFFIX));
            else
                sb.append(DxfGroup.toString(8, layerName));

            handleLTYPE(feature, sb);
            handleTHICKNESS(feature, sb);
            handleColor(feature, sb);

            sb.append(DxfGroup.toString(66, 1));
            sb.append(DxfGroup.toString(10, ZERO));
            sb.append(DxfGroup.toString(20, ZERO));
            coords[0].z = elev;
            if (!Double.isNaN(coords[0].z))
                sb.append(DxfGroup.toString(30, ZERO));
            sb.append(DxfGroup.toString(70, 9));
            coords = geom.getInteriorRingN(h).getCoordinates();
            for( int i = 0; i < coords.length; i++ ) {
                sb.append(DxfGroup.toString(0, VERTEX));
                if (suffix)
                    sb.append(DxfGroup.toString(8, layerName + SUFFIX));
                else
                    sb.append(DxfGroup.toString(8, layerName));
                sb.append(DxfGroup.toString(10, coords[i].x, precision));
                sb.append(DxfGroup.toString(20, coords[i].y, precision));
                coords[i].z = elev;
                if (!Double.isNaN(coords[i].z))
                    sb.append(DxfGroup.toString(30, coords[i].z, precision));
                sb.append(DxfGroup.toString(70, 32));
            }
            sb.append(DxfGroup.toString(0, SEQEND));
        }
    }
    return sb.toString();
}
 
Example 17
Source File: OmsDelaunayTriangulation.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inMap);

    if (!EGeometryType.isPoint(inMap.getSchema().getGeometryDescriptor())) {
        throw new ModelsIllegalargumentException("The input geometry needs to be points.", this, pm);
    }

    if (fElev != null) {
        fElev = FeatureUtilities.findAttributeName(inMap.getSchema(), fElev);
        if (fElev == null) {
            throw new ModelsIllegalargumentException("Couldn't find field: " + fElev, this);
        }
    }

    CoordinateReferenceSystem crs = inMap.getBounds().getCoordinateReferenceSystem();
    List<SimpleFeature> fList = FeatureUtilities.featureCollectionToList(inMap);

    pm.beginTask("Processing...", fList.size());
    DelaunayTriangulationBuilder b = new DelaunayTriangulationBuilder();
    List<Coordinate> cList = new ArrayList<Coordinate>();
    for( SimpleFeature f : fList ) {
        Geometry geometry = (Geometry) f.getDefaultGeometry();
        double elev = 0.0;
        if (fElev != null)
            elev = (Double) f.getAttribute(fElev);

        Coordinate c = geometry.getCoordinate();
        c.z = elev;
        cList.add(c);
        pm.worked(1);
    }
    pm.done();

    b.setSites(cList);

    List<Geometry> geosList = new ArrayList<Geometry>();
    Geometry triangles = b.getTriangles(gf);
    for( int i = 0; i < triangles.getNumGeometries(); i++ ) {
        Geometry geometryN = triangles.getGeometryN(i);
        Coordinate[] coordinates = geometryN.getCoordinates();
        double min = Double.POSITIVE_INFINITY;
        double max = Double.NEGATIVE_INFINITY;
        for( Coordinate coordinate : coordinates ) {
            min = Math.min(min, coordinate.z);
            max = Math.max(max, coordinate.z);
        }
        geometryN.setUserData(new String[]{"" + min, "" + max});
        geosList.add(geometryN);
    }
    outMap = FeatureUtilities.featureCollectionFromGeometry(crs, geosList.toArray(new Geometry[0]));
}
 
Example 18
Source File: OmsLinesRasterizer.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inVector);

    if (pNorth == null || pSouth == null || pWest == null || pEast == null || pRows == null || pCols == null) {
        throw new ModelsIllegalargumentException(
                "It is necessary to supply all the information about the processing region. Did you set the boundaries and rows/cols?",
                this, pm);
    }
    SimpleFeatureType schema = inVector.getSchema();
    CoordinateReferenceSystem crs = schema.getCoordinateReferenceSystem();
    GridGeometry2D inGrid = gridGeometryFromRegionValues(pNorth, pSouth, pEast, pWest, pCols, pRows, crs);

    if (!EGeometryType.isLine(schema.getGeometryDescriptor())) {
        throw new ModelsRuntimeException("The module works only with line vectors.", this);
    }

    RegionMap regionMap = CoverageUtilities.gridGeometry2RegionParamsMap(inGrid);
    double n = regionMap.getNorth();
    double s = regionMap.getSouth();
    double e = regionMap.getEast();
    double w = regionMap.getWest();
    double xRes = regionMap.getXres();
    double yRes = regionMap.getYres();
    double step = Math.min(xRes, yRes);

    WritableRaster outWR = CoverageUtilities.createWritableRaster(regionMap.getCols(), regionMap.getRows(), null, null,
            HMConstants.doubleNovalue);
    WritableRandomIter outIter = RandomIterFactory.createWritable(outWR, null);

    List<FeatureMate> matesList = FeatureUtilities.featureCollectionToMatesList(inVector);
    pm.beginTask("Rasterizing lines...", matesList.size());
    String fCatChecked = null;
    for( FeatureMate featureMate : matesList ) {
        Geometry geometry = featureMate.getGeometry();
        for( int i = 0; i < geometry.getNumGeometries(); i++ ) {
            Geometry geometryN = geometry.getGeometryN(i);
            List<Coordinate> lineCoordinatesAtStep = GeometryUtilities.getCoordinatesAtInterval((LineString) geometryN, step,
                    true, -1, -1);

            double cat;
            if (fCat == null) {
                cat = pCat;
            } else {
                if (fCatChecked == null) {
                    fCatChecked = FeatureUtilities.findAttributeName(featureMate.getFeature().getFeatureType(), fCat);
                    if (fCatChecked == null) {
                        throw new ModelsIllegalargumentException("Could not find an attribute named: " + fCat, this, pm);
                    }
                }
                cat = featureMate.getAttribute(fCat, Double.class);
            }

            for( Coordinate lineCoordinate : lineCoordinatesAtStep ) {
                if (!NumericsUtilities.isBetween(lineCoordinate.x, w, e)
                        || !NumericsUtilities.isBetween(lineCoordinate.y, s, n)) {
                    continue;
                }

                GridCoordinates2D onGrid = inGrid.worldToGrid(new DirectPosition2D(lineCoordinate.x, lineCoordinate.y));
                outIter.setSample(onGrid.x, onGrid.y, 0, cat);
            }
        }
        pm.worked(1);
    }
    pm.done();

    outRaster = CoverageUtilities.buildCoverage("pointsraster", outWR, regionMap, inVector.getSchema()
            .getCoordinateReferenceSystem());
}
 
Example 19
Source File: LasTriangulation2Dsm.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inLas, inDtm, outRaster);

    GridCoverage2D inDtmGC = getRaster(inDtm);
    Polygon polygon = CoverageUtilities.getRegionPolygon(inDtmGC);
    CoordinateReferenceSystem crs = inDtmGC.getCoordinateReferenceSystem();

    List<Coordinate> lasCoordinates = new ArrayList<Coordinate>();
    pm.beginTask("Preparing triangulation...", -1);
    try (ALasDataManager lasData = ALasDataManager.getDataManager(new File(inLas), null, 0.0, crs)) {
        lasData.open();
        List<LasRecord> lasPoints = lasData.getPointsInGeometry(polygon, false);
        for( LasRecord lasRecord : lasPoints ) {
            lasCoordinates.add(new Coordinate(lasRecord.x, lasRecord.y, lasRecord.z));
        }
    }

    DelaunayTriangulationBuilder triangulationBuilder = new DelaunayTriangulationBuilder();
    triangulationBuilder.setSites(lasCoordinates);
    Geometry triangles = triangulationBuilder.getTriangles(gf);
    pm.done();

    int numTriangles = triangles.getNumGeometries();
    pm.beginTask("Extracting triangles based on threshold...", numTriangles);
    ArrayList<Geometry> trianglesList = new ArrayList<Geometry>();
    for( int i = 0; i < numTriangles; i++ ) {
        pm.worked(1);
        Geometry geometryN = triangles.getGeometryN(i);
        Coordinate[] coordinates = geometryN.getCoordinates();
        double diff1 = abs(coordinates[0].z - coordinates[1].z);
        if (diff1 > pElevThres) {
            continue;
        }
        double diff2 = abs(coordinates[0].z - coordinates[2].z);
        if (diff2 > pElevThres) {
            continue;
        }
        double diff3 = abs(coordinates[1].z - coordinates[2].z);
        if (diff3 > pElevThres) {
            continue;
        }
        trianglesList.add(geometryN);
    }
    pm.done();

    int newNumTriangles = trianglesList.size();
    int removedNum = numTriangles - newNumTriangles;
    pm.message("Original triangles: " + numTriangles);
    pm.message("New triangles: " + newNumTriangles);
    pm.message("Removed triangles: " + removedNum);

    pm.beginTask("Create triangles index...", newNumTriangles);
    final STRtree tree = new STRtree(trianglesList.size());
    for( Geometry triangle : trianglesList ) {
        Envelope env = triangle.getEnvelopeInternal();
        tree.insert(env, triangle);
        pm.worked(1);
    }
    pm.done();

    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inDtmGC);
    double north = regionMap.getNorth();
    double south = regionMap.getSouth();
    double east = regionMap.getEast();
    double west = regionMap.getWest();

    if (pXres == null || pYres == null) {
        pXres = regionMap.getXres();
        pYres = regionMap.getYres();
    }
    final int newRows = (int) round((north - south) / pYres);
    int newCols = (int) round((east - west) / pXres);

    final GridGeometry2D newGridGeometry2D = CoverageUtilities.gridGeometryFromRegionValues(north, south, east, west,
            newCols, newRows, crs);
    RegionMap newRegionMap = CoverageUtilities.gridGeometry2RegionParamsMap(newGridGeometry2D);
    final WritableRaster newWR = CoverageUtilities.createWritableRaster(newCols, newRows, null, null,
            HMConstants.doubleNovalue);

    ThreadedRunnable< ? > runner = new ThreadedRunnable(getDefaultThreadsNum(), null);
    pm.beginTask("Setting raster points...", newCols);
    for( int c = 0; c < newCols; c++ ) {
        final int fCol = c;
        runner.executeRunnable(new Runnable(){
            public void run() {
                try {
                    makeRow(tree, newRows, newGridGeometry2D, newWR, fCol);
                } catch (TransformException e) {
                    e.printStackTrace();
                }
                pm.worked(1);
            }
        });
    }
    runner.waitAndClose();
    pm.done();

    GridCoverage2D outRasterGC = CoverageUtilities.buildCoverage("outraster", newWR, newRegionMap, crs);
    dumpRaster(outRasterGC, outRaster);
}
 
Example 20
Source File: JTS.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
     * Merges a sequence of points or paths if the first instance is an implementation of this library.
     *
     * @throws ClassCastException if an element in the iterator is not a JTS geometry.
     */
    @Override
    final Geometry tryMergePolylines(Object next, final Iterator<?> polylines) {
        if (!(next instanceof MultiLineString || next instanceof LineString || next instanceof Point)) {
            return null;
        }
        final List<Coordinate> coordinates = new ArrayList<>();
        final List<LineString> lines = new ArrayList<>();
add:    for (;;) {
            if (next instanceof Point) {
                final Coordinate pt = ((Point) next).getCoordinate();
                if (!Double.isNaN(pt.x) && !Double.isNaN(pt.y)) {
                    coordinates.add(pt);
                } else {
                    toLineString(coordinates, lines);
                    coordinates.clear();
                }
            } else {
                final Geometry g = (Geometry) next;
                final int n = g.getNumGeometries();
                for (int i=0; i<n; i++) {
                    final LineString ls = (LineString) g.getGeometryN(i);
                    if (coordinates.isEmpty()) {
                        lines.add(ls);
                    } else {
                        coordinates.addAll(Arrays.asList(ls.getCoordinates()));
                        toLineString(coordinates, lines);
                        coordinates.clear();
                    }
                }
            }
            /*
             * 'polylines.hasNext()' check is conceptually part of 'for' instruction,
             * except that we need to skip this condition during the first iteration.
             */
            do if (!polylines.hasNext()) break add;
            while ((next = polylines.next()) == null);
        }
        toLineString(coordinates, lines);
        return toGeometry(lines);
    }