Statistics
| Revision:

svn-gvsig-desktop / tags / v2_0_0_Build_2020 / libraries / libFMap_geometries / src / org / gvsig / fmap / geom / util / Converter.java @ 33789

History | View | Annotate | Download (38.6 KB)

1 21308 jiyarza
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2 20761 jmvivo
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23 21308 jiyarza
 *   Av. Blasco Ib??ez, 50
24 20761 jmvivo
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package org.gvsig.fmap.geom.util;
42
43
import java.awt.Shape;
44
import java.awt.geom.AffineTransform;
45
import java.awt.geom.Area;
46
import java.awt.geom.NoninvertibleTransformException;
47
import java.awt.geom.PathIterator;
48
import java.awt.geom.Rectangle2D;
49
import java.lang.reflect.Array;
50
import java.util.ArrayList;
51
52
import org.gvsig.fmap.geom.Geometry;
53 26328 jpiera
import org.gvsig.fmap.geom.GeometryLocator;
54 26867 jpiera
import org.gvsig.fmap.geom.GeometryManager;
55
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
56
import org.gvsig.fmap.geom.Geometry.TYPES;
57 27032 jpiera
import org.gvsig.fmap.geom.aggregate.MultiCurve;
58
import org.gvsig.fmap.geom.aggregate.MultiPoint;
59
import org.gvsig.fmap.geom.aggregate.MultiPrimitive;
60 27030 jpiera
import org.gvsig.fmap.geom.aggregate.MultiSurface;
61 27397 jpiera
import org.gvsig.fmap.geom.exception.CreateGeometryException;
62 20761 jmvivo
import org.gvsig.fmap.geom.primitive.GeneralPathX;
63 26867 jpiera
import org.gvsig.fmap.geom.primitive.Surface;
64 27397 jpiera
import org.slf4j.Logger;
65
import org.slf4j.LoggerFactory;
66 20761 jmvivo
67
import com.vividsolutions.jts.algorithm.CGAlgorithms;
68
import com.vividsolutions.jts.algorithm.RobustCGAlgorithms;
69
import com.vividsolutions.jts.geom.Coordinate;
70
import com.vividsolutions.jts.geom.CoordinateArrays;
71
import com.vividsolutions.jts.geom.Envelope;
72
import com.vividsolutions.jts.geom.GeometryCollection;
73
import com.vividsolutions.jts.geom.LineString;
74
import com.vividsolutions.jts.geom.LinearRing;
75
import com.vividsolutions.jts.geom.MultiLineString;
76
import com.vividsolutions.jts.geom.MultiPolygon;
77
import com.vividsolutions.jts.geom.Point;
78
import com.vividsolutions.jts.geom.Polygon;
79
80
/**
81 33111 cordinyana
 * Clase con varios m?todos est?ticos utilizados para pasar de java2d a jts
82
 * y viceversa.
83
 *
84 20761 jmvivo
 * @author fjp
85 33111 cordinyana
 * @deprecated to be removed or moved from API to implementation in gvSIG 2.1.0
86 20761 jmvivo
 */
87 20860 jiyarza
public class Converter {
88 27397 jpiera
        private static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
89
        private static final Logger logger = LoggerFactory.getLogger(Converter.class);
90 28396 jmvivo
91 21308 jiyarza
        //private static Logger logger = Logger.getLogger(Converter.class);
92 22287 vcaballero
93 20761 jmvivo
        /**
94
         * ?QU? PODEMOS HACER CON LOS MULTIPOINT??? => DEBER?AMOS TRABAJAR CON UN
95
         * ARRAY DE PUNTOS EN FShape.....Pensarlo bien.
96
         */
97 20869 jiyarza
        public final static com.vividsolutions.jts.geom.GeometryFactory geomFactory = new com.vividsolutions.jts.geom.GeometryFactory();
98 20761 jmvivo
        public static CGAlgorithms cga = new RobustCGAlgorithms();
99
        // private final static AffineTransform at = new AffineTransform();
100
        //private static double POINT_MARKER_SIZE = 3.0;
101
102 26867 jpiera
        private static GeometryManager manager = GeometryLocator.getGeometryManager();
103 20761 jmvivo
104
        //returns true if testPoint is a point in the pointList list.
105
        static boolean pointInList(Coordinate testPoint, Coordinate[] pointList) {
106
                int t;
107
                int numpoints;
108
                Coordinate p;
109
110
                numpoints = Array.getLength(pointList);
111
112
                for (t = 0; t < numpoints; t++) {
113
                        p = pointList[t];
114
115
                        if ((testPoint.x == p.x) && (testPoint.y == p.y) &&
116
                                        ((testPoint.z == p.z) || (!(testPoint.z == testPoint.z))) //nan test; x!=x iff x is nan
117
                        ) {
118
                                return true;
119
                        }
120
                }
121
122
                return false;
123
        }
124
125
        /**
126
         * Receives a JTS Geometry and returns a fmap IGeometry
127
         * @param jtsGeometry jts Geometry
128
         * @return IGeometry of FMap
129
         * @author azabala
130 29097 jpiera
         * @throws CreateGeometryException
131 20761 jmvivo
         */
132 29097 jpiera
        public static Geometry jtsToGeometry(com.vividsolutions.jts.geom.Geometry geo) throws CreateGeometryException{
133 22783 vcaballero
                Geometry shpNew = null;
134
135
                try {
136
                        if (geo instanceof Point) {
137 29097 jpiera
                                shpNew = geomManager.createPoint(((Point) geo).getX(),((Point) geo).getY(), SUBTYPES.GEOM2D);
138 22783 vcaballero
                        }
139
140
                        if (geo.isEmpty()) {
141
                                shpNew = null;
142
                        }
143
144 27397 jpiera
                        try{
145 22783 vcaballero
                        if (geo instanceof Polygon) {
146 27397 jpiera
                                shpNew = geomManager.createSurface(toShape((Polygon) geo), SUBTYPES.GEOM2D);
147 22783 vcaballero
                        }
148
149
                        if (geo instanceof MultiPolygon) {
150 27397 jpiera
                                shpNew = geomManager.createSurface(toShape((MultiPolygon) geo), SUBTYPES.GEOM2D);
151 22783 vcaballero
                        }
152
153
                        if (geo instanceof LineString) {
154 27397 jpiera
                                shpNew = geomManager.createCurve(toShape((LineString) geo), SUBTYPES.GEOM2D);
155 22783 vcaballero
                        }
156
157
                        if (geo instanceof MultiLineString) {
158 27397 jpiera
                                shpNew = geomManager.createCurve(toShape((MultiLineString) geo), SUBTYPES.GEOM2D);
159 22783 vcaballero
                        }
160 27397 jpiera
                        }catch(CreateGeometryException e){
161
                                logger.error("Error creating a geometry", e);
162
                        }
163 22783 vcaballero
164
                        /* OJO: CON ALGO COMO FSHAPE NO S? C?MO PODEMOS IMPLEMENTAR UN GeometryCollection
165
                         * No sabremos si queremos una l?nea o un pol?gono.....
166
                         *  if (geometry instanceof GeometryCollection) {
167
                                  return toShape((GeometryCollection) geometry);
168
                           } */
169
                        return shpNew;
170
                } catch (NoninvertibleTransformException e) {
171
                        // TODO Auto-generated catch block
172
                        e.printStackTrace();
173
                }
174
175
                return null;
176
177
//
178
//                FShape shape = Converter.jts_to_java2d(jtsGeometry);
179
//                return factory.createGeometry(shape);
180 20761 jmvivo
        }
181
182 20953 jiyarza
        /**
183
         * Convierte un MultiPoint2D a un MultiPoint de JTS
184
         * @param geom
185
         * @return
186 22287 vcaballero
         */
187 27032 jpiera
        public com.vividsolutions.jts.geom.Geometry geometryToJts(MultiPoint geom) {
188 20953 jiyarza
                Coordinate[] theGeoms = new Coordinate[geom.getPrimitivesNumber()];
189
                for (int i = 0; i < theGeoms.length; i++) {
190 28396 jmvivo
                        java.awt.geom.Point2D p = geom.getPrimitiveAt(i)
191 20953 jiyarza
                                        .getHandlers(Geometry.SELECTHANDLER)[0].getPoint();
192
                        Coordinate c = new Coordinate(p.getX(), p.getY());
193
                        theGeoms[i] = c;
194
                }
195
                com.vividsolutions.jts.geom.MultiPoint geomCol = new com.vividsolutions.jts.geom.GeometryFactory()
196
                                .createMultiPoint(theGeoms);
197
                return geomCol;
198
        }
199 22287 vcaballero
200 20953 jiyarza
        /**
201
         * Convierte una MultiCurve2D en una MultiLineString de JTS
202
         * @param geom
203
         * @return
204
         */
205 27032 jpiera
        public static com.vividsolutions.jts.geom.Geometry geometryToJts(MultiCurve geom) {
206 20953 jiyarza
                LineString[] lines = new LineString[geom.getPrimitivesNumber()];
207
        for (int i = 0; i < lines.length; i++){
208 28396 jmvivo
                lines[i] = (LineString) geometryToJts((geom.getPrimitiveAt(i)));
209 20953 jiyarza
        }
210 22287 vcaballero
        return new com.vividsolutions.jts.geom.GeometryFactory().createMultiLineString(lines);
211
        }
212
213 20953 jiyarza
        /**
214
         * Convierte una MultiSurface2D en un MultiPolygon de JTS
215
         * @return
216
         */
217 27030 jpiera
        public com.vividsolutions.jts.geom.Geometry geometryToJts(MultiSurface geom) {
218 20953 jiyarza
                Polygon[] polygons = new Polygon[geom.getPrimitivesNumber()];
219
        for (int i = 0; i < polygons.length; i++){
220 28396 jmvivo
                polygons[i] = (Polygon) geometryToJts((geom.getPrimitiveAt(i)));
221 20953 jiyarza
        }
222 22287 vcaballero
        return new com.vividsolutions.jts.geom.GeometryFactory().createMultiPolygon(polygons);
223
        }
224 20953 jiyarza
225
        /**
226
         * Convierte una BaseMultiPrimitive en una GeometryCollection de JTS
227
         * @return
228
         */
229 27032 jpiera
        public com.vividsolutions.jts.geom.Geometry geometryToJts(MultiPrimitive geom) {
230 20953 jiyarza
                com.vividsolutions.jts.geom.Geometry[] geometriesAux = new LineString[geom.getPrimitivesNumber()];
231
                for (int i = 0; i < geometriesAux.length; i++) {
232 28396 jmvivo
                        geometriesAux[i] = geometryToJts((geom.getPrimitiveAt(i)));
233 20953 jiyarza
                }
234
                return new com.vividsolutions.jts.geom.GeometryFactory().createGeometryCollection(geometriesAux);
235
        }
236 22287 vcaballero
237 28396 jmvivo
        public static com.vividsolutions.jts.geom.Geometry geometryToJtsWithSRID(
238
                        Geometry geom, int srid) {
239
                // logger.debug(geom.getClass());
240
                // logger.debug(new Integer(geom.getShapeType()));
241
                return geometryToJts(geom, geom.getType(), srid);
242
        }
243 22287 vcaballero
244 28396 jmvivo
245 20996 jiyarza
        public static com.vividsolutions.jts.geom.Geometry geometryToJts(Geometry geom) {
246 21308 jiyarza
                //logger.debug(geom.getClass());
247
                //logger.debug(new Integer(geom.getShapeType()));
248 28396 jmvivo
                return geometryToJts(geom, geom.getType(), -1);
249 20918 jiyarza
        }
250 22287 vcaballero
251 22783 vcaballero
//        public static com.vividsolutions.jts.geom.Geometry java2d_to_jts(FShape shp) {
252
//                return java2d_to_jts(shp, shp.getShapeType());
253
//        }
254 28627 jmvivo
255
        private static boolean isClosed(Coordinate firstCoordinate, Coordinate lastCoordinate){
256
                double diff = Math.abs(lastCoordinate.x - firstCoordinate.x);
257
                if (diff > 0.000001){
258
                        return false;
259
                }
260
                diff = Math.abs(lastCoordinate.y - firstCoordinate.y);
261
                if (diff > 0.000001) {
262
                        return false;
263
                }
264
                return true;
265
        }
266
267 20761 jmvivo
        /**
268
         * Convierte un FShape a una Geometry del JTS. Para ello, utilizamos un
269
         * "flattened PathIterator". El flattened indica que las curvas las pasa a
270
         * segmentos de l?nea recta AUTOMATICAMENTE!!!.
271
         *
272
         * @param shp FShape que se quiere convertir.
273
         *
274
         * @return Geometry de JTS.
275
         */
276 28396 jmvivo
        private static com.vividsolutions.jts.geom.Geometry geometryToJts(
277
                        Geometry shp, int shapeType, int srid) {
278 20761 jmvivo
279
280
                com.vividsolutions.jts.geom.Geometry geoJTS = null;
281
                Coordinate coord;
282
                //Coordinate[] coords;
283
                ArrayList arrayCoords = null;
284
                ArrayList arrayLines;
285
                LineString lin;
286
                //LinearRing linRing;
287
                //LinearRing linRingExt = null;
288
                int theType;
289
                int numParts = 0;
290
291
                //                 Use this array to store segment coordinate data
292
                double[] theData = new double[6];
293
                PathIterator theIterator;
294
295 21308 jiyarza
                //logger.debug(shp.toString());
296 22287 vcaballero
297 28396 jmvivo
298 20918 jiyarza
                switch (shapeType) {
299 28396 jmvivo
                case Geometry.TYPES.POINT:
300 27029 jpiera
                        org.gvsig.fmap.geom.primitive.impl.Point2D p = (org.gvsig.fmap.geom.primitive.impl.Point2D) shp;
301 22783 vcaballero
                        coord = new Coordinate(p.getX(), p.getY());
302
                        geoJTS = geomFactory.createPoint(coord);
303 28396 jmvivo
                        geoJTS.setSRID(srid);
304 20761 jmvivo
305 22783 vcaballero
                        break;
306 20761 jmvivo
307 33681 fdiaz
             case Geometry.TYPES.MULTIPOINT:
308
                    org.gvsig.fmap.geom.aggregate.impl.MultiPoint2D mp = (org.gvsig.fmap.geom.aggregate.impl.MultiPoint2D) shp;
309
                    int numPoints = mp.getPrimitivesNumber();
310
                    Coordinate[] coordinates = new Coordinate[numPoints];
311
                    for(int i=0; i<numPoints; i++){
312
                        p = mp.getPoint(i);
313
                        coordinates[i]=new Coordinate(p.getX(), p.getY());
314
                    }
315
                    geoJTS = geomFactory.createMultiPoint(coordinates);
316
                    geoJTS.setSRID(srid);
317
318
                    break;
319
320 22783 vcaballero
                case Geometry.TYPES.CURVE:
321 28396 jmvivo
                case Geometry.TYPES.ARC:
322 22783 vcaballero
                        arrayLines = new ArrayList();
323 30323 jpiera
                        theIterator = shp.getPathIterator(null, manager.getFlatness());
324 20761 jmvivo
325 22783 vcaballero
                        while (!theIterator.isDone()) {
326
                                //while not done
327
                                theType = theIterator.currentSegment(theData);
328 20761 jmvivo
329 22783 vcaballero
                                //Populate a segment of the new
330
                                // GeneralPathX object.
331
                                //Process the current segment to populate a new
332
                                // segment of the new GeneralPathX object.
333
                                switch (theType) {
334
                                case PathIterator.SEG_MOVETO:
335 20761 jmvivo
336 22783 vcaballero
                                        // System.out.println("SEG_MOVETO");
337
                                        if (arrayCoords == null) {
338
                                                arrayCoords = new ArrayList();
339
                                        } else {
340
                                                lin = geomFactory.createLineString(CoordinateArrays.toCoordinateArray(
341
                                                                arrayCoords));
342 28396 jmvivo
                                                lin.setSRID(srid);
343 22783 vcaballero
                                                arrayLines.add(lin);
344
                                                arrayCoords = new ArrayList();
345
                                        }
346 20761 jmvivo
347 22783 vcaballero
                                        numParts++;
348 28396 jmvivo
                                        coord = new Coordinate(theData[0], theData[1]);
349 20761 jmvivo
350 28396 jmvivo
                                        arrayCoords.add(coord);
351
352 22783 vcaballero
                                        break;
353 20761 jmvivo
354 22783 vcaballero
                                case PathIterator.SEG_LINETO:
355 20761 jmvivo
356 22783 vcaballero
                                        // System.out.println("SEG_LINETO");
357
                                        arrayCoords.add(new Coordinate(theData[0],
358
                                                        theData[1]));
359 20761 jmvivo
360 22783 vcaballero
                                        break;
361 20761 jmvivo
362 22783 vcaballero
                                case PathIterator.SEG_QUADTO:
363
                                        System.out.println("Not supported here");
364 20761 jmvivo
365 22783 vcaballero
                                        break;
366 20761 jmvivo
367 22783 vcaballero
                                case PathIterator.SEG_CUBICTO:
368
                                        System.out.println("Not supported here");
369 20761 jmvivo
370 22783 vcaballero
                                        break;
371 20761 jmvivo
372 22783 vcaballero
                                case PathIterator.SEG_CLOSE:
373
                                        // A?adimos el primer punto para cerrar.
374
                                        Coordinate firstCoord = (Coordinate) arrayCoords.get(0);
375 28627 jmvivo
                                                // Solo anyadimos cuando no esta ya cerrado
376 22783 vcaballero
                                        arrayCoords.add(new Coordinate(firstCoord.x,
377
                                                        firstCoord.y));
378 20761 jmvivo
379 22783 vcaballero
                                        break;
380
                                } //end switch
381 20761 jmvivo
382 22783 vcaballero
                                theIterator.next();
383
                        } //end while loop
384 20761 jmvivo
385 28396 jmvivo
                        if (arrayCoords.size()<2) {
386 22783 vcaballero
                                break;
387 28396 jmvivo
                        }
388 22783 vcaballero
                        lin = new com.vividsolutions.jts.geom.GeometryFactory().createLineString(CoordinateArrays.toCoordinateArray(
389
                                        arrayCoords));
390 20761 jmvivo
391 28396 jmvivo
                        lin.setSRID(srid);
392 22783 vcaballero
                        // CAMBIO: ENTREGAMOS SIEMPRE MULTILINESTRING, QUE ES
393
                        // LO QUE HACE TODO EL MUNDO CUANDO ESCRIBE EN POSTGIS
394
                        // O CON GEOTOOLS
395
                        // if (numParts > 1) // Generamos una MultiLineString
396
                        //  {
397
                        arrayLines.add(lin);
398
                        geoJTS = geomFactory.createMultiLineString(com.vividsolutions.jts.geom.GeometryFactory.toLineStringArray(
399
                                        arrayLines));
400 28396 jmvivo
                        geoJTS.setSRID(srid);
401 22783 vcaballero
                        /* } else {
402
                         geoJTS = lin;
403
                         } */
404 20761 jmvivo
405 22783 vcaballero
                        break;
406 20761 jmvivo
407 22783 vcaballero
                case Geometry.TYPES.SURFACE:
408
                case Geometry.TYPES.CIRCLE:
409 28396 jmvivo
                case Geometry.TYPES.ELLIPSE:
410 22783 vcaballero
                        arrayLines = new ArrayList();
411 20761 jmvivo
412 22783 vcaballero
                        ArrayList shells = new ArrayList();
413
                        ArrayList holes = new ArrayList();
414
                        Coordinate[] points = null;
415 20761 jmvivo
416 30323 jpiera
                        theIterator = shp.getPathIterator(null, manager.getFlatness());
417 20761 jmvivo
418 22783 vcaballero
                        while (!theIterator.isDone()) {
419
                                //while not done
420
                                theType = theIterator.currentSegment(theData);
421 20761 jmvivo
422 22783 vcaballero
                                //Populate a segment of the new
423
                                // GeneralPathX object.
424
                                //Process the current segment to populate a new
425
                                // segment of the new GeneralPathX object.
426
                                switch (theType) {
427
                                case PathIterator.SEG_MOVETO:
428 20761 jmvivo
429 22783 vcaballero
                                        // System.out.println("SEG_MOVETO");
430
                                        if (arrayCoords == null) {
431
                                                arrayCoords = new ArrayList();
432
                                        } else {
433
                                                points = CoordinateArrays.toCoordinateArray(arrayCoords);
434 20761 jmvivo
435 22783 vcaballero
                                                try {
436
                                                        LinearRing ring = geomFactory.createLinearRing(points);
437 20761 jmvivo
438 22783 vcaballero
                                                        if (CGAlgorithms.isCCW(points)) {
439
                                                                holes.add(ring);
440
                                                        } else {
441
                                                                shells.add(ring);
442
                                                        }
443
                                                } catch (Exception e) {
444
                                                        /* (jaume) caso cuando todos los puntos son iguales
445
                                                         * devuelvo el propio punto
446
                                                         */
447
                                                        boolean same = true;
448
                                                        for (int i = 0; i < points.length-1 && same; i++) {
449
                                                                if (points[i].x != points[i+1].x ||
450
                                                                                points[i].y != points[i+1].y /*||
451
                                                                                points[i].z != points[i+1].z*/
452 28396 jmvivo
                                                                ) {
453
                                                                        same = false;
454
                                                                }
455 22783 vcaballero
                                                        }
456 28396 jmvivo
                                                        if (same) {
457 22783 vcaballero
                                                                return geomFactory.createPoint(points[0]);
458 28396 jmvivo
                                                        }
459 22783 vcaballero
                                                        /*
460
                                                         * caso cuando es una l?nea de 3 puntos, no creo un LinearRing, sino
461
                                                         * una linea
462
                                                         */
463 28396 jmvivo
                                                        if (points.length>1 && points.length<=3) {
464 22783 vcaballero
                                                                // return geomFactory.createLineString(points);
465
                                                                return geomFactory.createMultiLineString(new LineString[] {geomFactory.createLineString(points)});
466 28396 jmvivo
                                                        }
467 20761 jmvivo
468 22783 vcaballero
                                                        System.err.println(
469
                                                        "Caught Topology exception in GMLLinearRingHandler");
470 20761 jmvivo
471 22783 vcaballero
                                                        return null;
472
                                                }
473 20761 jmvivo
474 22783 vcaballero
                                                /* if (numParts == 1)
475
                                                 {
476
                                                 linRingExt = new GeometryFactory().createLinearRing(
477
                                                 CoordinateArrays.toCoordinateArray(arrayCoords));
478
                                                 }
479
                                                 else
480
                                                 {
481
                                                 linRing = new GeometryFactory().createLinearRing(
482
                                                 CoordinateArrays.toCoordinateArray(arrayCoords));
483
                                                 arrayLines.add(linRing);
484
                                                 } */
485
                                                arrayCoords = new ArrayList();
486
                                        }
487 20761 jmvivo
488 22783 vcaballero
                                        numParts++;
489
                                        arrayCoords.add(new Coordinate(theData[0],
490
                                                        theData[1]));
491 20761 jmvivo
492 22783 vcaballero
                                        break;
493 20761 jmvivo
494 22783 vcaballero
                                case PathIterator.SEG_LINETO:
495 20761 jmvivo
496 22783 vcaballero
                                        // System.out.println("SEG_LINETO");
497
                                        arrayCoords.add(new Coordinate(theData[0],
498
                                                        theData[1]));
499 20761 jmvivo
500 22783 vcaballero
                                        break;
501 20761 jmvivo
502 22783 vcaballero
                                case PathIterator.SEG_QUADTO:
503
                                        System.out.println("SEG_QUADTO Not supported here");
504 20761 jmvivo
505 22783 vcaballero
                                        break;
506 20761 jmvivo
507 22783 vcaballero
                                case PathIterator.SEG_CUBICTO:
508
                                        System.out.println("SEG_CUBICTO Not supported here");
509 20761 jmvivo
510 22783 vcaballero
                                        break;
511 20761 jmvivo
512 22783 vcaballero
                                case PathIterator.SEG_CLOSE:
513 20761 jmvivo
514 22783 vcaballero
                                        // A?adimos el primer punto para cerrar.
515
                                        Coordinate firstCoord = (Coordinate) arrayCoords.get(0);
516
                                        arrayCoords.add(new Coordinate(firstCoord.x,
517
                                                        firstCoord.y));
518 20761 jmvivo
519 22783 vcaballero
                                        break;
520
                                } //end switch
521 20761 jmvivo
522 22783 vcaballero
                                // System.out.println("theData[0] = " + theData[0] + " theData[1]=" + theData[1]);
523
                                theIterator.next();
524
                        } //end while loop
525 20761 jmvivo
526 28627 jmvivo
527
                        Coordinate firstCoord = (Coordinate) arrayCoords.get(0);
528
                        Coordinate lastCoord = (Coordinate) arrayCoords.get(arrayCoords
529
                                        .size() - 1);
530
                        if (!isClosed(firstCoord, lastCoord)) {
531
                                arrayCoords.add(firstCoord);
532
                        }
533 22783 vcaballero
                        points = CoordinateArrays.toCoordinateArray(arrayCoords);
534 20761 jmvivo
535 22783 vcaballero
                        try {
536
                                LinearRing ring = geomFactory.createLinearRing(points);
537 20761 jmvivo
538 22783 vcaballero
                                if (CGAlgorithms.isCCW(points)) {
539
                                        holes.add(ring);
540
                                } else {
541
                                        shells.add(ring);
542 20761 jmvivo
                                }
543 28396 jmvivo
                                ring.setSRID(srid);
544 22783 vcaballero
                        } catch (Exception e) {
545
                                /* (jaume) caso cuando todos los puntos son iguales
546
                                 * devuelvo el propio punto
547
                                 */
548
                                boolean same = true;
549
                                for (int i = 0; i < points.length-1 && same; i++) {
550
                                        if (points[i].x != points[i+1].x ||
551
                                                        points[i].y != points[i+1].y /*||
552
                                                        points[i].z != points[i+1].z*/
553 28396 jmvivo
                                        ) {
554
                                                same = false;
555
                                        }
556 22783 vcaballero
                                }
557 28396 jmvivo
                                if (same) {
558
                                        geoJTS = geomFactory.createPoint(points[0]);
559
                                        geoJTS.setSRID(srid);
560
                                        return geoJTS;
561
                                }
562 22783 vcaballero
                                /*
563
                                 * caso cuando es una l?nea de 3 puntos, no creo un LinearRing, sino
564
                                 * una linea
565
                                 */
566 28396 jmvivo
                                if (points.length>1 && points.length<=3) {
567 22783 vcaballero
                                        // return geomFactory.createLineString(points);
568 28396 jmvivo
                                        geoJTS = geomFactory
569
                                                        .createMultiLineString(new LineString[] { geomFactory
570
                                                                        .createLineString(points) });
571
                                        geoJTS.setSRID(srid);
572
                                        return geoJTS;
573
                                }
574 22783 vcaballero
                                System.err.println(
575
                                "Caught Topology exception in GMLLinearRingHandler");
576 20761 jmvivo
577 22783 vcaballero
                                return null;
578
                        }
579 20761 jmvivo
580 22783 vcaballero
                        /* linRing = new GeometryFactory().createLinearRing(
581
                         CoordinateArrays.toCoordinateArray(arrayCoords)); */
582 20761 jmvivo
583 22783 vcaballero
                        // System.out.println("NumParts = " + numParts);
584
                        //now we have a list of all shells and all holes
585
                        ArrayList holesForShells = new ArrayList(shells.size());
586 20761 jmvivo
587 22783 vcaballero
                        for (int i = 0; i < shells.size(); i++) {
588
                                holesForShells.add(new ArrayList());
589
                        }
590 20761 jmvivo
591 22783 vcaballero
                        //find homes
592
                        for (int i = 0; i < holes.size(); i++) {
593
                                LinearRing testRing = (LinearRing) holes.get(i);
594
                                LinearRing minShell = null;
595
                                Envelope minEnv = null;
596
                                Envelope testEnv = testRing.getEnvelopeInternal();
597
                                Coordinate testPt = testRing.getCoordinateN(0);
598
                                LinearRing tryRing = null;
599 20761 jmvivo
600 22783 vcaballero
                                for (int j = 0; j < shells.size(); j++) {
601
                                        tryRing = (LinearRing) shells.get(j);
602 20761 jmvivo
603 22783 vcaballero
                                        Envelope tryEnv = tryRing.getEnvelopeInternal();
604 20761 jmvivo
605 22783 vcaballero
                                        if (minShell != null) {
606
                                                minEnv = minShell.getEnvelopeInternal();
607
                                        }
608 20761 jmvivo
609 22783 vcaballero
                                        boolean isContained = false;
610
                                        Coordinate[] coordList = tryRing.getCoordinates();
611 20761 jmvivo
612 22783 vcaballero
                                        if (tryEnv.contains(testEnv) &&
613
                                                        (CGAlgorithms.isPointInRing(testPt, coordList) ||
614
                                                                        (pointInList(testPt, coordList)))) {
615
                                                isContained = true;
616
                                        }
617
618
                                        // check if this new containing ring is smaller than the current minimum ring
619
                                        if (isContained) {
620
                                                if ((minShell == null) || minEnv.contains(tryEnv)) {
621
                                                        minShell = tryRing;
622 20761 jmvivo
                                                }
623
                                        }
624 22783 vcaballero
                                }
625 20761 jmvivo
626 22783 vcaballero
                                if (minShell == null) {
627
//                                        System.out.println(
628
//                                        "polygon found with a hole thats not inside a shell");
629
//                                        azabala: we do the assumption that this hole is really a shell (polygon)
630
//                                        whose point werent digitized in the right order
631
                                        Coordinate[] cs = testRing.getCoordinates();
632
                                        Coordinate[] reversed = new Coordinate[cs.length];
633
                                        int pointIndex = 0;
634
                                        for(int z = cs.length-1; z >= 0; z--){
635
                                                reversed[pointIndex] = cs[z];
636
                                                pointIndex++;
637 20761 jmvivo
                                        }
638 22783 vcaballero
                                        LinearRing newRing = geomFactory.createLinearRing(reversed);
639
                                        shells.add(newRing);
640
                                        holesForShells.add(new ArrayList());
641
                                } else {
642
                                        ((ArrayList) holesForShells.get(shells.indexOf(minShell))).add(testRing);
643 20761 jmvivo
                                }
644 22783 vcaballero
                        }
645 20761 jmvivo
646 22783 vcaballero
                        Polygon[] polygons = new Polygon[shells.size()];
647 20761 jmvivo
648 22783 vcaballero
                        for (int i = 0; i < shells.size(); i++) {
649
                                polygons[i] = geomFactory.createPolygon((LinearRing) shells.get(
650
                                                i),
651
                                                (LinearRing[]) ((ArrayList) holesForShells.get(i)).toArray(
652 20761 jmvivo
                                                                new LinearRing[0]));
653 28396 jmvivo
                                polygons[i].setSRID(srid);
654 22783 vcaballero
                        }
655
                        // CAMBIO: ENTREGAMOS SIEMPRE MULTILINESTRING, QUE ES
656
                        // LO QUE HACE TODO EL MUNDO CUANDO ESCRIBE EN POSTGIS
657
                        // O CON GEOTOOLS
658
                        // if (numParts > 1) // Generamos una MultiLineString
659 20761 jmvivo
660 22783 vcaballero
                        /* if (polygons.length == 1) {
661
                         return polygons[0];
662
                         } */
663 20761 jmvivo
664 22783 vcaballero
                        // FIN CAMBIO
665 20761 jmvivo
666 22783 vcaballero
                        holesForShells = null;
667
                        shells = null;
668
                        holes = null;
669 20761 jmvivo
670 22783 vcaballero
                        //its a multi part
671
                        geoJTS = geomFactory.createMultiPolygon(polygons);
672 28396 jmvivo
                        geoJTS.setSRID(srid);
673 20761 jmvivo
674 22783 vcaballero
                        /* if (numParts > 1) // Generamos un Polygon con agujeros
675
                         {
676
                         arrayLines.add(linRing);
677
                         // geoJTS = new GeometryFactory().createPolygon(linRingExt,
678
                          // GeometryFactory.toLinearRingArray(arrayLines));
679
                           geoJTS = new GeometryFactory().buildGeometry(arrayLines);
680 20761 jmvivo

681 22783 vcaballero
                           // geoJTS = Polygonizer.class.
682
                            }
683
                            else
684
                            {
685
                            geoJTS = new GeometryFactory().createPolygon(linRing,null);
686
                            } */
687
                        break;
688 20761 jmvivo
                }
689
690 28396 jmvivo
                geoJTS.setSRID(srid);
691 20761 jmvivo
                return geoJTS;
692
        }
693
694
        /**
695
         * Converts JTS Geometry objects into Java 2D Shape objects
696
         *
697
         * @param geo Geometry de JTS.
698
         *
699
         * @return FShape.
700
         */
701 22783 vcaballero
//        public static FShape jts_to_java2d(com.vividsolutions.jts.geom.Geometry geo) {
702
//                FShape shpNew = null;
703
//
704
//                try {
705
//                        if (geo instanceof Point) {
706
//                                shpNew = new org.gvsig.fmap.geom.primitive.Point2D(null, null, ((Point) geo).getX(), ((Point) geo).getY());
707
//                        }
708
//
709
//                        if (geo.isEmpty()) {
710
//                                shpNew = null;
711
//                        }
712
//
713
//                        if (geo instanceof Polygon) {
714
//                                shpNew = new Surface2D(null, null, toShape((Polygon) geo));
715
//                        }
716
//
717
//                        if (geo instanceof MultiPolygon) {
718
//                                shpNew = new Surface2D(null, null, toShape((MultiPolygon) geo));
719
//                        }
720
//
721
//                        if (geo instanceof LineString) {
722
//                                shpNew = new Curve2D(null, null, toShape((LineString) geo));
723
//                        }
724
//
725
//                        if (geo instanceof MultiLineString) {
726
//                                shpNew = new Curve2D(null, null, toShape((MultiLineString) geo));
727
//                        }
728
//
729
//                        /* OJO: CON ALGO COMO FSHAPE NO S? C?MO PODEMOS IMPLEMENTAR UN GeometryCollection
730
//                         * No sabremos si queremos una l?nea o un pol?gono.....
731
//                         *  if (geometry instanceof GeometryCollection) {
732
//                                  return toShape((GeometryCollection) geometry);
733
//                           } */
734
//                        return shpNew;
735
//                } catch (NoninvertibleTransformException e) {
736
//                        // TODO Auto-generated catch block
737
//                        e.printStackTrace();
738
//                }
739
//
740
//                return null;
741
//        }
742 20761 jmvivo
743
        /**
744
         * DOCUMENT ME!
745
         *
746
         * @param p DOCUMENT ME!
747
         *
748
         * @return DOCUMENT ME!
749
         */
750
        private static GeneralPathX toShape(Polygon p) {
751
                GeneralPathX resul = new GeneralPathX();
752
                Coordinate coord;
753
754
                for (int i = 0; i < p.getExteriorRing().getNumPoints(); i++) {
755
                        coord = p.getExteriorRing().getCoordinateN(i);
756
757
                        if (i == 0) {
758
                                resul.moveTo(coord.x,coord.y);
759
                        } else {
760
                                resul.lineTo(coord.x,coord.y);
761
                        }
762
                }
763
764
                for (int j = 0; j < p.getNumInteriorRing(); j++) {
765
                        LineString hole = p.getInteriorRingN(j);
766
767
                        for (int k = 0; k < hole.getNumPoints(); k++) {
768
                                coord = hole.getCoordinateN(k);
769
770
                                if (k == 0) {
771
                                        resul.moveTo(coord.x, coord.y);
772
                                } else {
773
                                        resul.lineTo(coord.x, coord.y);
774
                                }
775
                        }
776
                }
777
778
                return resul;
779
        }
780
781
        /**
782
         * DOCUMENT ME!
783
         *
784
         * @param modelCoordinates DOCUMENT ME!
785
         *
786
         * @return DOCUMENT ME!
787
         *
788
         * @throws NoninvertibleTransformException DOCUMENT ME!
789
         *
790
        private Coordinate[] toViewCoordinates(Coordinate[] modelCoordinates)
791
                throws NoninvertibleTransformException {
792
                Coordinate[] viewCoordinates = new Coordinate[modelCoordinates.length];
793

794
                for (int i = 0; i < modelCoordinates.length; i++) {
795
                        FPoint2D point2D = coordinate2FPoint2D(modelCoordinates[i]);
796
                        viewCoordinates[i] = new Coordinate(point2D.getX(), point2D.getY());
797
                }
798

799
                return viewCoordinates;
800 29097 jpiera
        }
801
         * @throws CreateGeometryException */
802 20761 jmvivo
803
        /* private Shape toShape(GeometryCollection gc)
804
           throws NoninvertibleTransformException {
805
           GeometryCollectionShape shape = new GeometryCollectionShape();
806
           for (int i = 0; i < gc.getNumGeometries(); i++) {
807
                   Geometry g = (Geometry) gc.getGeometryN(i);
808
                   shape.add(toShape(g));
809
           }
810
           return shape;
811
           } */
812
        private static GeneralPathX toShape(MultiLineString mls)
813 29097 jpiera
                throws NoninvertibleTransformException, CreateGeometryException {
814 20761 jmvivo
                GeneralPathX path = new GeneralPathX();
815
816
                for (int i = 0; i < mls.getNumGeometries(); i++) {
817
                        LineString lineString = (LineString) mls.getGeometryN(i);
818 29972 jldominguez
                        path.append(toShape(lineString).getPathIterator(null), false);
819 20761 jmvivo
                }
820
821
                //BasicFeatureRenderer expects LineStrings and MultiLineStrings to be
822
                //converted to GeneralPathXs. [Jon Aquino]
823
                return path;
824
        }
825
826
        /**
827
         * DOCUMENT ME!
828
         *
829
         * @param lineString DOCUMENT ME!
830
         *
831
         * @return DOCUMENT ME!
832
         *
833
         * @throws NoninvertibleTransformException DOCUMENT ME!
834 29097 jpiera
         * @throws CreateGeometryException
835 20761 jmvivo
         */
836
        private static GeneralPathX toShape(LineString lineString)
837 29097 jpiera
                throws NoninvertibleTransformException, CreateGeometryException {
838 20761 jmvivo
                GeneralPathX shape = new GeneralPathX();
839 29097 jpiera
                org.gvsig.fmap.geom.primitive.Point viewPoint = coordinate2FPoint2D(lineString.getCoordinateN(0));
840 20761 jmvivo
                shape.moveTo(viewPoint.getX(), viewPoint.getY());
841
842
                for (int i = 1; i < lineString.getNumPoints(); i++) {
843
                        viewPoint = coordinate2FPoint2D(lineString.getCoordinateN(i));
844
                        shape.lineTo(viewPoint.getX(), viewPoint.getY());
845
                }
846
847
                //BasicFeatureRenderer expects LineStrings and MultiLineStrings to be
848
                //converted to GeneralPathXs. [Jon Aquino]
849
                return shape;
850
        }
851
852
        /* TODO No se usa
853
         * DOCUMENT ME!
854
         *
855
         * @param point DOCUMENT ME!
856
         *
857
         * @return DOCUMENT ME!
858
         *
859
         * @throws NoninvertibleTransformException DOCUMENT ME!
860
         *
861
        private static Point2D toShape(Point point)
862
                throws NoninvertibleTransformException {
863
                Point2D viewPoint = coordinate2FPoint2D(point.getCoordinate());
864

865
                return viewPoint;
866
        }
867
*/
868 22287 vcaballero
869 20761 jmvivo
        /**
870 22287 vcaballero
         *
871 20761 jmvivo
         */
872
        private static GeneralPathX toShape(MultiPolygon mp)
873
        throws NoninvertibleTransformException {
874
        GeneralPathX path = new GeneralPathX();
875
876
        for (int i = 0; i < mp.getNumGeometries(); i++) {
877
                Polygon polygon = (Polygon) mp.getGeometryN(i);
878 29972 jldominguez
                path.append(toShape(polygon).getPathIterator(null), false);
879 20761 jmvivo
        }
880
881
        //BasicFeatureRenderer expects LineStrings and MultiLineStrings to be
882
        //converted to GeneralPathXs. [Jon Aquino]
883
        return path;
884
}
885
        /**
886
         * DOCUMENT ME!
887
         *
888
         * @param coord DOCUMENT ME!
889
         *
890
         * @return DOCUMENT ME!
891 29097 jpiera
         * @throws CreateGeometryException
892 20761 jmvivo
         */
893 29097 jpiera
        public static org.gvsig.fmap.geom.primitive.Point coordinate2FPoint2D(Coordinate coord) throws CreateGeometryException {
894
                return geomManager.createPoint(coord.x, coord.y, SUBTYPES.GEOM2D); //,coord.z);
895 20761 jmvivo
        }
896
897
        /**
898
         * Convierte una Geometry de JTS a GeneralPathX.
899
         *
900
         * @param geometry Geometry a convertir.
901
         *
902
         * @return GeneralPathX.
903
         *
904
         * @throws NoninvertibleTransformException
905 29097 jpiera
         * @throws CreateGeometryException
906 20761 jmvivo
         * @throws IllegalArgumentException
907
         */
908
        public static GeneralPathX toShape(com.vividsolutions.jts.geom.Geometry geometry)
909 29097 jpiera
                throws NoninvertibleTransformException, CreateGeometryException {
910 20761 jmvivo
                if (geometry.isEmpty()) {
911
                        return new GeneralPathX();
912
                }
913
914
                if (geometry instanceof Polygon) {
915
                        return toShape((Polygon) geometry);
916
                }
917
918
                if (geometry instanceof MultiPolygon) {
919
                        return toShape((MultiPolygon) geometry);
920
                }
921
922
                if (geometry instanceof LineString) {
923
                        return toShape((LineString) geometry);
924
                }
925
926
                if (geometry instanceof MultiLineString) {
927
                        return toShape((MultiLineString) geometry);
928
                }
929
930
                if (geometry instanceof GeometryCollection) {
931 28396 jmvivo
                        return toShape(geometry);
932 20761 jmvivo
                }
933
934
                throw new IllegalArgumentException("Unrecognized Geometry class: " +
935
                        geometry.getClass());
936
        }
937
938
939
    public static GeneralPathX transformToInts(GeneralPathX gp, AffineTransform at) {
940
        GeneralPathX newGp = new GeneralPathX();
941
        PathIterator theIterator;
942
        int theType;
943
        int numParts = 0;
944
        double[] theData = new double[6];
945
        java.awt.geom.Point2D ptDst = new java.awt.geom.Point2D.Double();
946
        java.awt.geom.Point2D ptSrc = new java.awt.geom.Point2D.Double();
947
        boolean bFirst = true;
948
        int xInt, yInt, antX = -1, antY = -1;
949
950
        theIterator = gp.getPathIterator(null); //, flatness);
951
952
        while (!theIterator.isDone()) {
953
            theType = theIterator.currentSegment(theData);
954
            switch (theType) {
955
                case PathIterator.SEG_MOVETO:
956
                    numParts++;
957
                    ptSrc.setLocation(theData[0], theData[1]);
958
                    at.transform(ptSrc, ptDst);
959
                    antX = (int) ptDst.getX();
960
                    antY = (int) ptDst.getY();
961
                    newGp.moveTo(antX, antY);
962
                    bFirst = true;
963
                    break;
964
965
                case PathIterator.SEG_LINETO:
966
                    ptSrc.setLocation(theData[0], theData[1]);
967
                    at.transform(ptSrc, ptDst);
968
                    xInt = (int) ptDst.getX();
969
                    yInt = (int) ptDst.getY();
970
                    if ((bFirst) || ((xInt != antX) || (yInt != antY)))
971
                    {
972
                        newGp.lineTo(xInt, yInt);
973
                        antX = xInt;
974
                        antY = yInt;
975
                        bFirst = false;
976
                    }
977
                    break;
978
979
                case PathIterator.SEG_QUADTO:
980
                    System.out.println("Not supported here");
981
982
                    break;
983
984
                case PathIterator.SEG_CUBICTO:
985
                    System.out.println("Not supported here");
986
987
                    break;
988
989
                case PathIterator.SEG_CLOSE:
990
                    newGp.closePath();
991
992
                    break;
993
            } //end switch
994
995
            theIterator.next();
996
        } //end while loop
997
998
        return newGp;
999
    }
1000 29097 jpiera
    public static Geometry transformToInts(Geometry gp, AffineTransform at) throws CreateGeometryException {
1001 20761 jmvivo
        GeneralPathX newGp = new GeneralPathX();
1002
        double[] theData = new double[6];
1003
        double[] aux = new double[6];
1004
1005
        // newGp.reset();
1006
        PathIterator theIterator;
1007
        int theType;
1008
        int numParts = 0;
1009
1010
        java.awt.geom.Point2D ptDst = new java.awt.geom.Point2D.Double();
1011
        java.awt.geom.Point2D ptSrc = new java.awt.geom.Point2D.Double();
1012
        boolean bFirst = true;
1013
        int xInt, yInt, antX = -1, antY = -1;
1014
1015
1016
        theIterator = gp.getPathIterator(null); //, flatness);
1017
        int numSegmentsAdded = 0;
1018
        while (!theIterator.isDone()) {
1019
            theType = theIterator.currentSegment(theData);
1020
1021
            switch (theType) {
1022
                case PathIterator.SEG_MOVETO:
1023
                    numParts++;
1024
                    ptSrc.setLocation(theData[0], theData[1]);
1025
                    at.transform(ptSrc, ptDst);
1026
                    antX = (int) ptDst.getX();
1027
                    antY = (int) ptDst.getY();
1028
                    newGp.moveTo(antX, antY);
1029
                    numSegmentsAdded++;
1030
                    bFirst = true;
1031
                    break;
1032
1033
                case PathIterator.SEG_LINETO:
1034
                    ptSrc.setLocation(theData[0], theData[1]);
1035
                    at.transform(ptSrc, ptDst);
1036
                    xInt = (int) ptDst.getX();
1037
                    yInt = (int) ptDst.getY();
1038
                    if ((bFirst) || ((xInt != antX) || (yInt != antY)))
1039
                    {
1040
                        newGp.lineTo(xInt, yInt);
1041
                        antX = xInt;
1042
                        antY = yInt;
1043
                        bFirst = false;
1044
                        numSegmentsAdded++;
1045
                    }
1046
                    break;
1047
1048
                case PathIterator.SEG_QUADTO:
1049
                    at.transform(theData,0,aux,0,2);
1050
                    newGp.quadTo(aux[0], aux[1], aux[2], aux[3]);
1051
                    numSegmentsAdded++;
1052
                    break;
1053
1054
                case PathIterator.SEG_CUBICTO:
1055
                    at.transform(theData,0,aux,0,3);
1056
                    newGp.curveTo(aux[0], aux[1], aux[2], aux[3], aux[4], aux[5]);
1057
                    numSegmentsAdded++;
1058
                    break;
1059
1060
                case PathIterator.SEG_CLOSE:
1061 28396 jmvivo
                    if (numSegmentsAdded < 3) {
1062
                                                newGp.lineTo(antX, antY);
1063
                                        }
1064 20761 jmvivo
                    newGp.closePath();
1065
1066
                    break;
1067
            } //end switch
1068
1069
            theIterator.next();
1070
        } //end while loop
1071
1072 22783 vcaballero
        Geometry shp = null;
1073
        switch (gp.getType())
1074 20761 jmvivo
        {
1075 28396 jmvivo
            case Geometry.TYPES.POINT:
1076 29097 jpiera
                shp = geomManager.createPoint(ptDst.getX(), ptDst.getY(), SUBTYPES.GEOM2D);
1077 20761 jmvivo
                break;
1078
1079 22783 vcaballero
            case Geometry.TYPES.CURVE:
1080
            case Geometry.TYPES.ARC:
1081 27397 jpiera
                    try {
1082
                                        shp = geomManager.createCurve(newGp, SUBTYPES.GEOM2D);
1083
                                } catch (CreateGeometryException e1) {
1084
                                        logger.error("Error creating a curve", e1);
1085
                                }
1086 20761 jmvivo
                break;
1087
1088 22783 vcaballero
            case Geometry.TYPES.SURFACE:
1089
            case Geometry.TYPES.CIRCLE:
1090
            case Geometry.TYPES.ELLIPSE:
1091 20761 jmvivo
1092 27397 jpiera
                try {
1093
                                        shp = geomManager.createSurface(newGp, SUBTYPES.GEOM2D);
1094
                                } catch (CreateGeometryException e) {
1095
                                        logger.error("Error creating a surface", e);
1096
                                }
1097 20761 jmvivo
                break;
1098
        }
1099
        return shp;
1100
    }
1101
1102
    public static Rectangle2D convertEnvelopeToRectangle2D(Envelope jtsR)
1103
    {
1104
        Rectangle2D.Double r = new Rectangle2D.Double(jtsR.getMinX(),
1105
                jtsR.getMinY(), jtsR.getWidth(), jtsR.getHeight());
1106
        return r;
1107
    }
1108
1109 22287 vcaballero
    public static Envelope convertEnvelopeToJTS(org.gvsig.fmap.geom.primitive.Envelope r)
1110 20761 jmvivo
    {
1111 22287 vcaballero
            Envelope e = new Envelope(r.getMinimum(0), r.getMaximum(0), r.getMinimum(1),
1112
                        r.getMaximum(1));
1113 20761 jmvivo
            return e;
1114
    }
1115
1116
    /**
1117
     * Return a correct polygon (no hole)
1118
     * @param coordinates
1119
     * @return
1120
     */
1121
    public static Geometry getExteriorPolygon(Coordinate[] coordinates)
1122
    {
1123
            // isCCW = true => it's a hole
1124
            Coordinate[] vs=new Coordinate[coordinates.length];
1125
        if (CGAlgorithms.isCCW(coordinates)){
1126
                for (int i=vs.length-1;i>=0;i--){
1127
                        vs[i]=coordinates[i];
1128
                }
1129
        }else{
1130
                vs=coordinates;
1131
        }
1132
        LinearRing ring = geomFactory.createLinearRing(vs);
1133
1134
        try {
1135 26867 jpiera
                        Surface surface = (Surface)manager.create(TYPES.SURFACE, SUBTYPES.GEOM2D);
1136
                        surface.setGeneralPath(toShape(ring));
1137
                        return surface;
1138 20761 jmvivo
                } catch (NoninvertibleTransformException e) {
1139
                        e.printStackTrace();
1140 27397 jpiera
                } catch (CreateGeometryException e) {
1141 26867 jpiera
                        e.printStackTrace();
1142 20761 jmvivo
                }
1143
                return null;
1144
    }
1145
1146 27030 jpiera
    public static boolean isCCW(Point[] points)
1147 20761 jmvivo
    {
1148 26081 fdiaz
            int length = points.length;
1149
            Coordinate[] vs;
1150
            // CGAlgorithms.isCCW asume que la lista de puntos tienen el primer
1151
            // y el ultimo puntos iguales.... y que este algoritmo est? solo
1152
            // garantizado con anillos v?lidos.
1153
            if (points[0].getX() != points[length-1].getX() || points[0].getY() != points[length-1].getY()) {
1154
                vs=new Coordinate[length+1];
1155
                vs[points.length] = new Coordinate(points[0].getX(), points[0].getY());
1156
            } else {
1157
                vs=new Coordinate[length];
1158
            }
1159
               for (int i=0; i<length; i++){
1160 20761 jmvivo
                    vs[i] = new Coordinate(points[i].getX(), points[i].getY());
1161
            }
1162
1163
        return CGAlgorithms.isCCW(vs);
1164
    }
1165
1166 27030 jpiera
    public static boolean isCCW(Surface pol)
1167 20761 jmvivo
    {
1168 22783 vcaballero
            com.vividsolutions.jts.geom.Geometry jtsGeom = Converter.geometryToJts(pol);
1169 20761 jmvivo
            if (jtsGeom.getNumGeometries() == 1)
1170
            {
1171
                    Coordinate[] coords = jtsGeom.getCoordinates();
1172
                    return CGAlgorithms.isCCW(coords);
1173
            }
1174
            return false;
1175
1176
    }
1177
1178
1179
    /**
1180
     * Return a hole (CCW ordered points)
1181
     * @param coordinates
1182
     * @return
1183
     */
1184
    public static Geometry getHole(Coordinate[] coordinates)
1185
    {
1186
            // isCCW = true => it's a hole
1187
            Coordinate[] vs=new Coordinate[coordinates.length];
1188
        if (CGAlgorithms.isCCW(coordinates)){
1189
                vs=coordinates;
1190
1191
        }else{
1192
                for (int i=vs.length-1;i>=0;i--){
1193
                        vs[i]=coordinates[i];
1194
                }
1195
        }
1196
        LinearRing ring = geomFactory.createLinearRing(vs);
1197
1198
        try {
1199 26872 jpiera
                Surface surface = (Surface)manager.create(TYPES.SURFACE, SUBTYPES.GEOM2D);
1200
                surface.setGeneralPath(toShape(ring));
1201
                        return surface;
1202 20761 jmvivo
                } catch (NoninvertibleTransformException e) {
1203
                        e.printStackTrace();
1204 27397 jpiera
                } catch (CreateGeometryException e) {
1205 26872 jpiera
                        e.printStackTrace();
1206 20761 jmvivo
                }
1207
                return null;
1208
    }
1209
1210
        public static Shape getExteriorPolygon(GeneralPathX gp) {
1211
                Area area = new Area(gp);
1212
                area.isSingular();
1213
                return area;
1214
1215
1216
1217
        }
1218
        /**
1219
         * Use it ONLY for NOT multipart polygons.
1220
         * @param pol
1221
         * @return
1222
         */
1223 27030 jpiera
        public static Geometry getNotHolePolygon(Surface pol) {
1224 20761 jmvivo
                // isCCW == true => hole
1225
                Coordinate[] coords;
1226
                ArrayList arrayCoords = null;
1227
                int theType;
1228
                int numParts = 0;
1229
1230
                //                 Use this array to store segment coordinate data
1231
                double[] theData = new double[6];
1232
                PathIterator theIterator;
1233
1234
                                ArrayList shells = new ArrayList();
1235
                                ArrayList holes = new ArrayList();
1236
                                Coordinate[] points = null;
1237
1238 30323 jpiera
                                theIterator = pol.getPathIterator(null, manager.getFlatness());
1239 20761 jmvivo
1240
                                while (!theIterator.isDone()) {
1241
                                        //while not done
1242
                                        theType = theIterator.currentSegment(theData);
1243
1244
                                        //Populate a segment of the new
1245
                                        // GeneralPathX object.
1246
                                        //Process the current segment to populate a new
1247
                                        // segment of the new GeneralPathX object.
1248
                                        switch (theType) {
1249
                                                case PathIterator.SEG_MOVETO:
1250
1251
                                                        // System.out.println("SEG_MOVETO");
1252
                                                        if (arrayCoords == null) {
1253
                                                                arrayCoords = new ArrayList();
1254
                                                        } else {
1255
                                                                points = CoordinateArrays.toCoordinateArray(arrayCoords);
1256
1257
                                                                try {
1258
                                                                        LinearRing ring = geomFactory.createLinearRing(points);
1259
1260
                                                                        if (CGAlgorithms.isCCW(points)) {
1261
                                                                                holes.add(ring);
1262
                                                                        } else {
1263
                                                                                shells.add(ring);
1264
                                                                        }
1265
                                                                } catch (Exception e) {
1266
                                                                        System.err.println(
1267
                                                                                "Caught Topology exception in GMLLinearRingHandler");
1268
1269
                                                                        return null;
1270
                                                                }
1271
1272
                                                                /* if (numParts == 1)
1273
                                                                   {
1274
                                                                           linRingExt = new GeometryFactory().createLinearRing(
1275
                                                                                  CoordinateArrays.toCoordinateArray(arrayCoords));
1276
                                                                   }
1277
                                                                   else
1278
                                                                   {
1279
                                                                           linRing = new GeometryFactory().createLinearRing(
1280
                                                                                          CoordinateArrays.toCoordinateArray(arrayCoords));
1281
                                                                           arrayLines.add(linRing);
1282
                                                                   } */
1283
                                                                arrayCoords = new ArrayList();
1284
                                                        }
1285
1286
                                                        numParts++;
1287
                                                        arrayCoords.add(new Coordinate(theData[0],
1288
                                                                        theData[1]));
1289
1290
                                                        break;
1291
1292
                                                case PathIterator.SEG_LINETO:
1293
1294
                                                        // System.out.println("SEG_LINETO");
1295
                                                        arrayCoords.add(new Coordinate(theData[0],
1296
                                                                        theData[1]));
1297
1298
                                                        break;
1299
1300
                                                case PathIterator.SEG_QUADTO:
1301
                                                        System.out.println("SEG_QUADTO Not supported here");
1302
1303
                                                        break;
1304
1305
                                                case PathIterator.SEG_CUBICTO:
1306
                                                        System.out.println("SEG_CUBICTO Not supported here");
1307
1308
                                                        break;
1309
1310
                                                case PathIterator.SEG_CLOSE:
1311
1312
                                                        // A?adimos el primer punto para cerrar.
1313
                                                        Coordinate firstCoord = (Coordinate) arrayCoords.get(0);
1314
                                                        arrayCoords.add(new Coordinate(firstCoord.x,
1315
                                                                        firstCoord.y));
1316
1317
                                                        break;
1318
                                        } //end switch
1319
1320
                                        // System.out.println("theData[0] = " + theData[0] + " theData[1]=" + theData[1]);
1321
                                        theIterator.next();
1322
                                } //end while loop
1323
1324
                                arrayCoords.add(arrayCoords.get(0));
1325
                                coords = CoordinateArrays.toCoordinateArray(arrayCoords);
1326
1327
1328
                if (numParts == 1)
1329
                {
1330
                        return getExteriorPolygon(coords);
1331
                }
1332 22783 vcaballero
                return pol;
1333 20761 jmvivo
1334
        }
1335
1336
1337
    /* public static GeometryCollection convertFGeometryCollection(FGeometryCollection fGeomC)
1338
    {
1339

1340
        geomFactory.createGeometryCollection(theGeoms);
1341
    } */
1342
}