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

The following examples show how to use org.locationtech.jts.geom.Geometry#getNumGeometries() . 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: 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 2
Source File: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * Recursively decompose geometry into a set of envelopes to create a single set.
 *
 * @param geometry
 * @param destinationListOfSets
 * @param checkTopoEquality
 */
private static boolean constructListOfConstraintSetsFromGeometry(
    final Geometry geometry,
    final List<ConstraintSet> destinationListOfSets,
    final boolean checkTopoEquality) {

  // Get the envelope of the geometry being held
  final int n = geometry.getNumGeometries();
  boolean retVal = true;
  if (n > 1) {
    retVal = false;
    for (int gi = 0; gi < n; gi++) {
      constructListOfConstraintSetsFromGeometry(
          geometry.getGeometryN(gi),
          destinationListOfSets,
          checkTopoEquality);
    }
  } else {
    final Envelope env = geometry.getEnvelopeInternal();
    destinationListOfSets.add(basicConstraintSetFromEnvelope(env));
    if (checkTopoEquality) {
      retVal = new GeometryFactory().toGeometry(env).equalsTopo(geometry);
    }
  }
  return retVal;
}
 
Example 3
Source File: DxfUtils.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Write a {@link SimpleFeature} to dxf string.
 * 
 * @param featureMate the feature to convert.
 * @param layerName the layer name in case none is in the attributes.
 * @param elevationAttrName the attribute defining elevation or <code>null</code>.
 * @param suffix <code>true</code> if suffix is needed.
 * @param force2CoordsToLine if <code>true</code>, lines that are composed of just 2 coordinates
 *                      will be handled as LINE instead of the default which is POLYLINE.
 * @return the string representation.
 */
public static String feature2Dxf( FeatureMate featureMate, String layerName, String elevationAttrName, boolean suffix,
        boolean force2CoordsToLine ) {
    Geometry g = featureMate.getGeometry();

    if (EGeometryType.isPoint(g)) {
        return point2Dxf(featureMate, layerName, elevationAttrName);
    } else if (EGeometryType.isLine(g)) {
        return lineString2Dxf(featureMate, layerName, elevationAttrName, force2CoordsToLine);
    } else if (EGeometryType.isPolygon(g)) {
        return polygon2Dxf(featureMate, layerName, elevationAttrName, suffix);
    } else if (g instanceof GeometryCollection) {
        StringBuilder sb = new StringBuilder();
        for( int i = 0; i < g.getNumGeometries(); i++ ) {
            SimpleFeature ff = SimpleFeatureBuilder.copy(featureMate.getFeature());
            ff.setDefaultGeometry(g.getGeometryN(i));
            FeatureMate fm = new FeatureMate(ff);
            sb.append(feature2Dxf(fm, layerName, elevationAttrName, suffix, force2CoordsToLine));
        }
        return sb.toString();
    } else {
        return null;
    }
}
 
Example 4
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 5
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 6
Source File: Shape.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Split shape
 * @param line Split line
 * @return Splitted shapes
 */
public List<Shape> split(Shape line){
    Geometry g1 = this.toGeometry();
    Geometry g2 = line.toGeometry();
    if (this.getShapeType().isPolygon()){
        Polygonizer polygonizer = new Polygonizer();
        Geometry polygons = g1.getBoundary().union(g2);
        polygonizer.add(polygons);
        List<Geometry> polys = (List)polygonizer.getPolygons();   
        List<Shape> polyShapes = new ArrayList<>();
        for (int i = 0; i < polys.size(); i++){
            org.locationtech.jts.geom.Polygon poly = (org.locationtech.jts.geom.Polygon)polys.get(i);
            if (poly.getInteriorPoint().within(g1))
                polyShapes.add(new PolygonShape(poly));
        }
        return polyShapes;
    } else if (this.getShapeType().isLine()){
        Geometry ugeo = g1.union(g2);            
        List<Shape> lineShapes = new ArrayList<>();
        for (int i = 0; i < ugeo.getNumGeometries(); i++){
            Geometry geo = ugeo.getGeometryN(i);
            if (geo.buffer(0.001).within(g1.buffer(0.0011)))
                lineShapes.add(new PolylineShape(geo));
        }
        return lineShapes;
    }
    
    return null;
}
 
Example 7
Source File: GeoWaveFunctionsDescriptor.java    From datawave with Apache License 2.0 5 votes vote down vote up
protected static List<Geometry> getAllEnvelopeGeometries(Geometry geom) {
    List<Geometry> geometries = new ArrayList<>();
    if (geom.getNumGeometries() > 1)
        for (int geoIdx = 0; geoIdx < geom.getNumGeometries(); geoIdx++)
            geometries.addAll(getAllEnvelopeGeometries(geom.getGeometryN(geoIdx)));
    else
        geometries.add(geom.getEnvelope());
    return geometries;
}
 
Example 8
Source File: GeoWaveFunctionsDescriptor.java    From datawave with Apache License 2.0 5 votes vote down vote up
protected static List<Envelope> getSeparateEnvelopes(Geometry geom, int maxEnvelopes) {
    if (geom.getNumGeometries() > 0) {
        List<Geometry> geometries = getAllEnvelopeGeometries(geom);
        List<Geometry> intersectedGeometries = new ArrayList<>();
        
        if (combineIntersectedGeometries(geometries, intersectedGeometries, maxEnvelopes))
            return intersectedGeometries.stream().map(Geometry::getEnvelopeInternal).collect(Collectors.toList());
    }
    return Arrays.asList(geom.getEnvelopeInternal());
}
 
Example 9
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 10
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 11
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 12
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 13
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 14
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 15
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);
    }
 
Example 16
Source File: OmsLW03_NetworkHierarchyToPointsSplitter.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inNet);

    if (pGauklerStrickler < 10) {
        throw new ModelsIllegalargumentException("KS can't be negative.", this);
    }

    // Creates the list of contained features
    List<SimpleFeature> netList = FeatureUtilities.featureCollectionToList(inNet);

    // Creates the output feature collection
    DefaultFeatureCollection outNetPointsFC = new DefaultFeatureCollection();

    // Creates the structure of the output point layer
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("net");
    b.setCRS(inNet.getBounds().getCoordinateReferenceSystem());
    b.add("the_geom", Point.class);
    b.add(PFAF, String.class);
    b.add(LINKID, Integer.class);
    b.add(GAUKLER, Double.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);

    /*for each line generates the points geometries of the contained  
     * vertexes with attributes -> it is assumed that the input network is
     * the output of the tool NetworkAttributesBuilder  
     */
    for( SimpleFeature netLineFeature : netList ) {
        int count = 1;
        Object pfaf = netLineFeature.getAttribute(PFAF);
        Geometry netLine = (Geometry) netLineFeature.getDefaultGeometry();
        for( int i = 0; i < netLine.getNumGeometries(); i++ ) {
            LineString net = (LineString) netLine.getGeometryN(i);
            Coordinate[] coordinates = net.getCoordinates();
            for( int j = 0; j < coordinates.length - 1; j++ ) {

                Point point = gf.createPoint(coordinates[j]);

                Object[] values = new Object[]{point, pfaf, count, pGauklerStrickler};
                builder.addAll(values);
                SimpleFeature feature = builder.buildFeature(null);

                outNetPointsFC.add(feature);
                count++;
            }
        }

    }
    outNetPoints = outNetPointsFC;
}
 
Example 17
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 18
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 19
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 20
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]));
}