/
GeometryUtils.java
1424 lines (1338 loc) · 46.1 KB
/
GeometryUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************************************
*
* GeometryUtils.java, in msi.gama.core, is part of the source code of the
* GAMA modeling and simulation platform (v.1.8.2).
*
* (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU)
*
* Visit https://github.com/gama-platform/gama for license information and contacts.
*
********************************************************************************************************/
package msi.gama.common.geometry;
import static msi.gama.metamodel.shape.IShape.Type.LINESTRING;
import static msi.gama.metamodel.shape.IShape.Type.MULTILINESTRING;
import static msi.gama.metamodel.shape.IShape.Type.MULTIPOINT;
import static msi.gama.metamodel.shape.IShape.Type.NULL;
import static msi.gama.metamodel.shape.IShape.Type.POINT;
import static msi.gama.metamodel.shape.IShape.Type.POLYGON;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
import org.geotools.geometry.jts.JTS;
import org.locationtech.jts.algorithm.Distance;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFilter;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.PrecisionModel;
import org.locationtech.jts.geom.impl.CoordinateArraySequence;
import org.locationtech.jts.geom.prep.PreparedGeometry;
import org.locationtech.jts.geom.prep.PreparedGeometryFactory;
import org.locationtech.jts.io.WKTWriter;
import org.locationtech.jts.operation.buffer.BufferParameters;
import org.locationtech.jts.precision.GeometryPrecisionReducer;
import org.locationtech.jts.simplify.DouglasPeuckerSimplifier;
import org.locationtech.jts.triangulate.ConformingDelaunayTriangulationBuilder;
import org.locationtech.jts.triangulate.ConstraintEnforcementException;
import org.locationtech.jts.triangulate.DelaunayTriangulationBuilder;
import org.locationtech.jts.triangulate.VoronoiDiagramBuilder;
import org.locationtech.jts.triangulate.quadedge.LocateFailureException;
import msi.gama.common.interfaces.IEnvelopeComputer;
import msi.gama.common.util.RandomUtils;
import msi.gama.metamodel.shape.GamaPoint;
import msi.gama.metamodel.shape.GamaShape;
import msi.gama.metamodel.shape.IShape;
import msi.gama.metamodel.shape.IShape.Type;
import msi.gama.runtime.GAMA;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gama.util.Collector;
import msi.gama.util.GamaListFactory;
import msi.gama.util.ICollector;
import msi.gama.util.IList;
import msi.gama.util.file.IGamaFile;
import msi.gama.util.graph.IGraph;
import msi.gaml.operators.Files;
import msi.gaml.operators.Graphs;
import msi.gaml.operators.Random;
import msi.gaml.operators.Spatial.Operators;
import msi.gaml.operators.Spatial.ThreeD;
import msi.gaml.species.ISpecies;
import msi.gaml.types.GamaGeometryType;
import msi.gaml.types.Types;
/**
* The class GamaGeometryUtils.
*
* @author drogoul
* @since 14 dec. 2011
*
*/
@SuppressWarnings ({ "unchecked", "rawtypes" })
public class GeometryUtils {
/** The envelope computers. */
private static List<IEnvelopeComputer> envelopeComputers = new ArrayList<>();
/**
* Adds the envelope computer.
*
* @param ec the ec
*/
// TODO AD Add IEnvelopeComputer as a service
public static void addEnvelopeComputer(final IEnvelopeComputer ec) {
envelopeComputers.add(ec);
}
/** The Constant GEOMETRY_FACTORY. */
public final static GamaGeometryFactory GEOMETRY_FACTORY = new GamaGeometryFactory();
/** The Constant PREPARED_GEOMETRY_FACTORY. */
public final static PreparedGeometryFactory PREPARED_GEOMETRY_FACTORY = new PreparedGeometryFactory();
/**
* Distance on polyline.
*
* @param line the line
* @param pt1 the pt 1
* @param pt2 the pt 2
* @return the double
*/
public static Double distanceOnPolyline(final IShape line, final GamaPoint pt1, final GamaPoint pt2) {
int indexS = 0;
int indexT = 0;
IList<GamaPoint> points = line.getPoints();
int nbSp = points.size();
if (nbSp == 2)
return pt1.euclidianDistanceTo(pt2);
else {
double distanceS = Double.MAX_VALUE;
double distanceT = Double.MAX_VALUE;
for (int i = 0; i < nbSp - 1; i++) {
final double distS = Distance.pointToSegment(pt1, points.get(i), points.get(i + 1));
final double distT = Distance.pointToSegment(pt2, points.get(i), points.get(i + 1));
if (distS < distanceS) {
distanceS = distS;
indexS = i;
}
if (distT < distanceT) {
distanceT = distT;
indexT = i;
}
}
}
if (indexS == indexT) return pt1.euclidianDistanceTo(pt2);
double distance = 0;
int minI, maxI;
GamaPoint source, target;
if (indexT > indexS) {
minI = indexS + 1;
maxI = indexT;
source = pt1;
target = pt2;
} else {
minI = indexT + 1;
maxI = indexS;
source = pt2;
target = pt1;
}
distance = source.euclidianDistanceTo(points.get(minI));
for (int i = minI; i < maxI - 1; i++) {
GamaPoint pt = points.get(i);
distance += source.euclidianDistanceTo(pt);
source = pt;
}
distance += source.euclidianDistanceTo(target);
return distance;
}
/**
* Point in geom.
*
* @param geom the geom
* @param rand the rand
* @return the gama point
*/
public static GamaPoint pointInGeom(final Geometry geom, final RandomUtils rand) {
// WARNING Only in 2D for Polygons !
if (geom == null || geom.getCoordinate() == null) return null;
if (geom instanceof Point || geom.getCoordinates().length < 2) return new GamaPoint(geom.getCoordinate());
if (geom instanceof LineString) {
final double perimeter = GeometryUtils.getContourCoordinates(geom).getLength();
final double dist = perimeter * rand.between(0.0, 1.0);
double sumDist = 0;
Coordinate pS = ((LineString) geom).getCoordinateN(0);
for (int i = 1; i < geom.getNumPoints(); i++) {
final Coordinate pT = ((LineString) geom).getCoordinateN(i);
final double d = pS.distance3D(pT);
if (d + sumDist >= dist) {
final double ratio = (dist - sumDist) / d;
final double newX = pS.x + ratio * (pT.x - pS.x);
final double newY = pS.y + ratio * (pT.y - pS.y);
final double newZ = pS.z + ratio * (pT.z - pS.z);
return new GamaPoint(newX, newY, newZ);
}
pS = pT;
sumDist += d;
}
}
if (geom instanceof Polygon) {
final Envelope env = geom.getEnvelopeInternal();
final double xMin = env.getMinX();
final double xMax = env.getMaxX();
final double yMin = env.getMinY();
final double yMax = env.getMaxY();
final double x = rand.between(xMin, xMax);
if (geom.getArea() > 0) {
final double y = rand.between(yMin, yMax);
final UniqueCoordinateSequence ucs = (UniqueCoordinateSequence) ICoordinates.ofLength(1);
ucs.setTo(x, y, 0);
final Point pt = GEOMETRY_FACTORY.createPoint(ucs);
while (!geom.intersects(pt)) {
ucs.setTo(rand.between(xMin, xMax), rand.between(yMin, yMax), 0);
pt.geometryChanged();
// pt.setLocation(rand.between(xMin, xMax), rand.between(yMin, yMax));
}
return ucs.at(0);
}
final Coordinate coord1 = new Coordinate(x, yMin);
final Coordinate coord2 = new Coordinate(x, yMax);
final Coordinate[] coords = { coord1, coord2 };
Geometry line = GEOMETRY_FACTORY.createLineString(coords);
try {
line = line.intersection(geom);
} catch (final Exception e) {
final PrecisionModel pm = new PrecisionModel(PrecisionModel.FLOATING_SINGLE);
line = GeometryPrecisionReducer.reducePointwise(line, pm)
.intersection(GeometryPrecisionReducer.reducePointwise(geom, pm));
}
return pointInGeom(line, rand);
}
if (geom instanceof GeometryCollection) {
if (geom instanceof MultiLineString) {
final IList<Double> distribution = GamaListFactory.create(Types.FLOAT);
for (int i = 0; i < geom.getNumGeometries(); i++) {
distribution.add(GeometryUtils.getContourCoordinates(geom.getGeometryN(i)).getLength());
}
final int index = Random.opRndChoice(GAMA.getRuntimeScope(), distribution);
return pointInGeom(geom.getGeometryN(index), rand);
}
if (geom instanceof MultiPolygon) {
final IList<Double> distribution = GamaListFactory.create(Types.FLOAT);
for (int i = 0; i < geom.getNumGeometries(); i++) { distribution.add(geom.getGeometryN(i).getArea()); }
final int index = Random.opRndChoice(GAMA.getRuntimeScope(), distribution);
return pointInGeom(geom.getGeometryN(index), rand);
}
return pointInGeom(geom.getGeometryN(rand.between(0, geom.getNumGeometries() - 1)), rand);
}
return null;
}
/**
* Point in geom.
*
* @param shape the shape
* @param rand the rand
* @return the gama point
*/
public static GamaPoint pointInGeom(final IShape shape, final RandomUtils rand) {
if (shape == null) return null;
return pointInGeom(shape.getInnerGeometry(), rand);
}
/**
* Minimise length.
*
* @param coords the coords
* @return the coordinate[]
*/
private static Coordinate[] minimiseLength(final Coordinate[] coords) {
final double dist1 = GEOMETRY_FACTORY.createLineString(coords).getLength();
final Coordinate[] coordstest1 = new Coordinate[3];
coordstest1[0] = coords[0];
coordstest1[1] = coords[2];
coordstest1[2] = coords[1];
final double dist2 = GEOMETRY_FACTORY.createLineString(coordstest1).getLength();
final Coordinate[] coordstest2 = new Coordinate[3];
coordstest2[0] = coords[1];
coordstest2[1] = coords[0];
coordstest2[2] = coords[2];
final double dist3 = GEOMETRY_FACTORY.createLineString(coordstest2).getLength();
if (dist1 <= dist2 && dist1 <= dist3) return coords;
if (dist2 <= dist1 && dist2 <= dist3) return coordstest1;
if (dist3 <= dist1 && dist3 <= dist2) return coordstest2;
return coords;
}
/**
* Nb common points.
*
* @param p1 the p 1
* @param p2 the p 2
* @return the int
*/
public static int nbCommonPoints(final Geometry p1, final Geometry p2) {
try (final ICollector<Coordinate> cp = Collector.getSet()) {
final List<Coordinate> coords = Arrays.asList(p1.getCoordinates());
for (final Coordinate pt : p2.getCoordinates()) { if (coords.contains(pt)) { cp.add(pt); } }
return cp.size();
}
}
/**
* Extract points.
*
* @param triangle the triangle
* @param connectedNodes the connected nodes
* @return the coordinate[]
*/
public static Coordinate[] extractPoints(final IShape triangle, final Set<IShape> connectedNodes) {
final Coordinate[] coords = triangle.getInnerGeometry().getCoordinates();
final int degree = connectedNodes.size();
final Coordinate[] c1 = { coords[0], coords[1] };
final Coordinate[] c2 = { coords[1], coords[2] };
final Coordinate[] c3 = { coords[2], coords[3] };
final LineString l1 = GEOMETRY_FACTORY.createLineString(c1);
final LineString l2 = GEOMETRY_FACTORY.createLineString(c2);
final LineString l3 = GEOMETRY_FACTORY.createLineString(c3);
final Coordinate[] pts = new Coordinate[degree];
if (degree == 3) {
pts[0] = l1.getCentroid().getCoordinate();
pts[1] = l2.getCentroid().getCoordinate();
pts[2] = l3.getCentroid().getCoordinate();
return minimiseLength(pts);
}
if (degree == 2) {
int cpt = 0;
for (final IShape n : connectedNodes) {
if (nbCommonPoints(l1, n.getInnerGeometry()) == 2) {
pts[cpt] = l1.getCentroid().getCoordinate();
cpt++;
} else if (nbCommonPoints(l2, n.getInnerGeometry()) == 2) {
pts[cpt] = l2.getCentroid().getCoordinate();
cpt++;
} else if (nbCommonPoints(l3, n.getInnerGeometry()) == 2) {
pts[cpt] = l3.getCentroid().getCoordinate();
cpt++;
}
}
} else
return null;
return pts;
}
/**
* Extract points.
*
* @param triangle1 the triangle 1
* @param triangle2 the triangle 2
* @return the coordinate[]
*/
public static Coordinate[] extractPoints(final IShape triangle1, final IShape triangle2) {
final Coordinate[] coords = triangle1.getInnerGeometry().getCoordinates();
final Coordinate[] c1 = { coords[0], coords[1] };
final Coordinate[] c2 = { coords[1], coords[2] };
final Coordinate[] c3 = { coords[2], coords[3] };
final LineString l1 = GEOMETRY_FACTORY.createLineString(c1);
final LineString l2 = GEOMETRY_FACTORY.createLineString(c2);
final LineString l3 = GEOMETRY_FACTORY.createLineString(c3);
final Coordinate[] pts = new Coordinate[3];
if (nbCommonPoints(l1, triangle2.getInnerGeometry()) == 2) {
pts[1] = l1.getCentroid().getCoordinate();
} else if (nbCommonPoints(l2, triangle2.getInnerGeometry()) == 2) {
pts[1] = l2.getCentroid().getCoordinate();
} else if (nbCommonPoints(l3, triangle2.getInnerGeometry()) == 2) { pts[1] = l3.getCentroid().getCoordinate(); }
pts[0] = triangle1.getCentroid();
pts[2] = triangle2.getCentroid();
return pts;
}
/**
* Hexagonal grid from geom.
*
* @param geom the geom
* @param nbRows the nb rows
* @param nbColumns the nb columns
* @return the i list
*/
public static IList<IShape> hexagonalGridFromGeom(final IShape geom, final int nbRows, final int nbColumns) {
final Envelope env = geom.getEnvelope();
final double widthEnv = env.getWidth();
final double heightEnv = env.getHeight();
double xmin = env.getMinX();
double ymin = env.getMinY();
final double widthHex = widthEnv / (nbColumns * 0.75 + 0.25);
final double heightHex = heightEnv / nbRows;
final IList<IShape> geoms = GamaListFactory.create(Types.GEOMETRY);
xmin += widthHex / 2.0;
ymin += heightHex / 2.0;
for (int l = 0; l < nbRows; l++) {
for (int c = 0; c < nbColumns; c = c + 2) {
final GamaShape poly = (GamaShape) GamaGeometryType.buildHexagon(widthHex, heightHex,
new GamaPoint(xmin + c * widthHex * 0.75, ymin + l * heightHex, 0));
if (geom.covers(poly)) { geoms.add(poly); }
}
}
for (int l = 0; l < nbRows; l++) {
for (int c = 1; c < nbColumns; c = c + 2) {
final GamaShape poly = (GamaShape) GamaGeometryType.buildHexagon(widthHex, heightHex,
new GamaPoint(xmin + c * widthHex * 0.75, ymin + (l + 0.5) * heightHex, 0));
if (geom.covers(poly)) { geoms.add(poly); }
}
}
return geoms;
}
/**
* Square discretization.
*
* @param geom the geom
* @param nb_squares the nb squares
* @param overlaps the overlaps
* @param coeff_precision the coeff precision
* @return the i list
*/
public static IList<IShape> squareDiscretization(final Geometry geom, final int nb_squares, final boolean overlaps,
final double coeff_precision) {
double size = Math.sqrt(geom.getArea() / nb_squares);
List<IShape> rectToRemove = new ArrayList<>();
IList<IShape> squares = discretization(geom, size, size, overlaps, rectToRemove);
if (squares.size() < nb_squares) {
while (squares.size() < nb_squares) {
size *= coeff_precision;
rectToRemove = new ArrayList<>();
squares = discretization(geom, size, size, overlaps, rectToRemove);
}
} else if (squares.size() > nb_squares) {
while (squares.size() > nb_squares) {
size /= coeff_precision;
final List<IShape> rectToRemove2 = new ArrayList<>();
final IList<IShape> squares2 = discretization(geom, size, size, overlaps, rectToRemove2);
if (squares2.size() < nb_squares) { break; }
squares = squares2;
rectToRemove = rectToRemove2;
}
}
final int nb = squares.size();
if (nb > nb_squares) {
if (nb - nb_squares > rectToRemove.size()) {
squares.removeAll(rectToRemove);
} else {
for (int i = 0; i < nb - nb_squares; i++) { squares.remove(rectToRemove.get(i)); }
}
}
return squares;
}
/**
* Discretization.
*
* @param geom the geom
* @param size_x the size x
* @param size_y the size y
* @param overlaps the overlaps
* @return the i list
*/
public static IList<IShape> discretization(final Geometry geom, final double size_x, final double size_y,
final boolean overlaps) {
return discretization(geom, size_x, size_y, overlaps, null);
}
/**
* Discretization.
*
* @param geom the geom
* @param size_x the size x
* @param size_y the size y
* @param overlaps the overlaps
* @param borders the borders
* @return the i list
*/
public static IList<IShape> discretization(final Geometry geom, final double size_x, final double size_y,
final boolean overlaps, final List<IShape> borders) {
final IList<IShape> geoms = GamaListFactory.create(Types.GEOMETRY);
if (geom instanceof GeometryCollection) {
final GeometryCollection gc = (GeometryCollection) geom;
for (int i = 0; i < gc.getNumGeometries(); i++) {
geoms.addAll(discretization(gc.getGeometryN(i), size_x, size_y, overlaps, borders));
}
} else {
final Envelope env = geom.getEnvelopeInternal();
final double xMax = env.getMaxX();
final double yMax = env.getMaxY();
double x = env.getMinX();
double y;
boolean firstX = true;
while (x < xMax) {
y = env.getMinY();
firstX = true;
while (y < yMax) {
final Coordinate c1 = new Coordinate(x, y);
final Coordinate c2 = new Coordinate(x + size_x, y);
final Coordinate c3 = new Coordinate(x + size_x, y + size_y);
final Coordinate c4 = new Coordinate(x, y + size_y);
final Coordinate[] cc = { c1, c2, c3, c4, c1 };
final Geometry square = GEOMETRY_FACTORY.createPolygon(GEOMETRY_FACTORY.createLinearRing(cc), null);
y += size_y;
if (!overlaps) {
if (square.coveredBy(geom)) {
final IShape sq = new GamaShape(square);
geoms.add(sq);
if (firstX && borders != null) { borders.add(sq); }
firstX = false;
}
} else if (square.intersects(geom)) {
final IShape sq = new GamaShape(square);
geoms.add(sq);
if (firstX && borders != null) { borders.add(sq); }
firstX = false;
}
}
x += size_x;
}
}
return geoms;
}
/**
* Geometry decomposition.
*
* @param geom the geom
* @param x_size the x size
* @param y_size the y size
* @return the i list
*/
public static IList<IShape> geometryDecomposition(final IShape geom, final double x_size, final double y_size) {
final IList<IShape> geoms = GamaListFactory.create(Types.GEOMETRY);
final double zVal = geom.getLocation().getZ();
final IList<IShape> rects = discretization(geom.getInnerGeometry(), x_size, y_size, true);
for (final IShape shape : rects) {
final IShape gg = Operators.inter(null, shape, geom);
if (gg != null && !gg.getInnerGeometry().isEmpty()) {
final GamaShape sp = new GamaShape(gg);
final GamaPoint[] pts = getPointsOf(sp);
for (int i = 0; i < pts.length; i++) {
final GamaPoint gp = pts[i];
if (zVal != gp.getZ()) { ThreeD.set_z(null, sp, i, zVal); }
}
geoms.add(sp);
}
}
return geoms;
}
/**
* Voronoi.
*
* @param scope the scope
* @param points the points
* @return the i list
*/
public static IList<IShape> voronoi(final IScope scope, final IList<GamaPoint> points) {
final IList<IShape> geoms = GamaListFactory.create(Types.GEOMETRY);
final VoronoiDiagramBuilder dtb = new VoronoiDiagramBuilder();
dtb.setClipEnvelope(scope.getSimulation().getEnvelope());
dtb.setSites(points);
final GeometryCollection g = (GeometryCollection) dtb.getDiagram(GEOMETRY_FACTORY);
final int nb = g.getNumGeometries();
for (int i = 0; i < nb; i++) {
final Geometry gg = g.getGeometryN(i);
geoms.add(new GamaShape(gg.intersection(scope.getSimulation().getInnerGeometry())));
}
return geoms;
}
/**
* Voronoi.
*
* @param scope the scope
* @param points the points
* @param clip the clip
* @return the i list
*/
public static IList<IShape> voronoi(final IScope scope, final IList<GamaPoint> points, final IShape clip) {
final IList<IShape> geoms = GamaListFactory.create(Types.GEOMETRY);
final VoronoiDiagramBuilder dtb = new VoronoiDiagramBuilder();
dtb.setClipEnvelope(clip.getEnvelope());
dtb.setSites(points);
final GeometryCollection g = (GeometryCollection) dtb.getDiagram(GEOMETRY_FACTORY);
final int nb = g.getNumGeometries();
for (int i = 0; i < nb; i++) {
final Geometry gg = g.getGeometryN(i);
geoms.add(new GamaShape(gg));
}
return geoms;
}
/**
* Triangulation.
*
* @param scope the scope
* @param lines the lines
* @return the i list
*/
public static IList<IShape> triangulation(final IScope scope, final IList<IShape> lines) {
final IList<IShape> geoms = GamaListFactory.create(Types.GEOMETRY);
final ConformingDelaunayTriangulationBuilder dtb = new ConformingDelaunayTriangulationBuilder();
final Geometry points = GamaGeometryType.geometriesToGeometry(scope, lines).getInnerGeometry();
dtb.setSites(points);
dtb.setConstraints(points);
final GeometryCollection tri = (GeometryCollection) dtb.getTriangles(GEOMETRY_FACTORY);
final int nb = tri.getNumGeometries();
for (int i = 0; i < nb; i++) {
final Geometry gg = tri.getGeometryN(i);
geoms.add(new GamaShape(gg));
}
return geoms;
}
/**
* Triangulation.
*
* @param scope the scope
* @param geom the geom
* @param toleranceTriangulation the tolerance triangulation
* @param toleranceClip the tolerance clip
* @param approxClipping the approx clipping
* @return the i list
*/
public static IList<IShape> triangulation(final IScope scope, final Geometry geom,
final double toleranceTriangulation, final double toleranceClip, final boolean approxClipping) {
final IList<IShape> geoms = GamaListFactory.create(Types.GEOMETRY);
if (geom instanceof GeometryCollection) {
final GeometryCollection gc = (GeometryCollection) geom;
for (int i = 0; i < gc.getNumGeometries(); i++) {
geoms.addAll(triangulation(scope, gc.getGeometryN(i), toleranceTriangulation, toleranceClip,
approxClipping));
}
} else {
final ConformingDelaunayTriangulationBuilder dtb = new ConformingDelaunayTriangulationBuilder();
dtb.setTolerance(toleranceTriangulation);
GeometryCollection tri = null;
try {
dtb.setSites(geom);
dtb.setConstraints(geom);
tri = (GeometryCollection) dtb.getTriangles(GEOMETRY_FACTORY);
} catch (final LocateFailureException | ConstraintEnforcementException e) {
dtb.setTolerance(toleranceTriangulation + 0.1);
dtb.setSites(geom);
dtb.setConstraints(geom);
tri = (GeometryCollection) dtb.getTriangles(GEOMETRY_FACTORY);
}
if (tri != null) { geoms.addAll(filterGeoms(tri, geom, toleranceClip, approxClipping)); }
}
return geoms;
}
/**
* Filter geoms.
*
* @param geom the geom
* @param clip the clip
* @param sizeTol the size tol
* @param approxClipping the approx clipping
* @return the i list
*/
private static IList<IShape> filterGeoms(final GeometryCollection geom, final Geometry clip, final double sizeTol,
final boolean approxClipping) {
if (geom == null) return null;
final double elevation = getContourCoordinates(clip).averageZ();
final boolean setZ = elevation != 0.0;
final IList<IShape> result = GamaListFactory.create(Types.GEOMETRY);
final Geometry bufferClip = sizeTol != 0.0 ? clip.buffer(sizeTol, 5, 0) : clip;
final PreparedGeometry buffered = PREPARED_GEOMETRY_FACTORY.create(bufferClip);
final Envelope3D env = Envelope3D.of(buffered.getGeometry());
try {
for (int i = 0; i < geom.getNumGeometries(); i++) {
final Geometry gg = geom.getGeometryN(i);
if (!clip.covers(gg.getCentroid())) { continue; }
final Coordinate[] coord = gg.getCoordinates();
boolean cond = env.covers(gg.getCentroid().getCoordinate());
cond = cond && (approxClipping
? buffered.covers(gg.getCentroid()) && buffered.covers(GEOMETRY_FACTORY.createPoint(coord[0]))
&& buffered.covers(GEOMETRY_FACTORY.createPoint(coord[1]))
&& buffered.covers(GEOMETRY_FACTORY.createPoint(coord[2]))
: bufferClip.covers(gg));
if (cond) {
if (setZ) {
final ICoordinates cc = getContourCoordinates(gg);
cc.setAllZ(elevation);
gg.geometryChanged();
}
result.add(new GamaShape(gg));
}
}
} finally {
env.dispose();
}
/*
* applyToInnerGeometries(geom, (gg) -> { final ICoordinates cc = getContourCoordinates(gg); if
* (cc.isCoveredBy(env) && buffered.covers(gg)) {
*
* } });
*/
return result;
}
/**
* Iterate over triangles.
*
* @param polygon the polygon
* @param action the action
*/
public static void iterateOverTriangles(final Polygon polygon, final Consumer<Geometry> action) {
final double elevation = getContourCoordinates(polygon).averageZ();
final double sizeTol = Math.sqrt(polygon.getArea()) / 100.0;
final DelaunayTriangulationBuilder dtb = new DelaunayTriangulationBuilder();
final PreparedGeometry buffered = PREPARED_GEOMETRY_FACTORY.create(polygon.buffer(sizeTol, 5, 0));
final Envelope3D env = Envelope3D.of(buffered.getGeometry());
try {
dtb.setSites(polygon);
dtb.setTolerance(sizeTol);
applyToInnerGeometries(dtb.getTriangles(GEOMETRY_FACTORY), gg -> {
final ICoordinates cc = getContourCoordinates(gg);
if (cc.isCoveredBy(env) && buffered.covers(gg)) {
cc.setAllZ(elevation);
gg.geometryChanged();
action.accept(gg);
}
});
} catch (final LocateFailureException | ConstraintEnforcementException e) {
final IScope scope = GAMA.getRuntimeScope();
GamaRuntimeException.warning("Impossible to triangulate: " + new WKTWriter().write(polygon), scope);
iterateOverTriangles((Polygon) DouglasPeuckerSimplifier.simplify(polygon, 0.1), action);
return;
} finally {
env.dispose();
}
}
/**
* Squeletisation.
*
* @param scope the scope
* @param geom the geom
* @param toleranceTriangulation the tolerance triangulation
* @param toleranceClip the tolerance clip
* @param approxClipping the approx clipping
* @return the list
*/
public static List<LineString> squeletisation(final IScope scope, final Geometry geom,
final double toleranceTriangulation, final double toleranceClip, final boolean approxClipping) {
final List<LineString> network = new ArrayList<>();
final IList polys =
GeometryUtils.triangulation(scope, geom, toleranceTriangulation, toleranceClip, approxClipping);
final IGraph graph = Graphs.spatialLineIntersectionTriangle(scope, polys);
final IList<IList> ccs = Graphs.connectedComponentOf(scope, graph);
for (final IList cc : ccs) {
if (cc.size() > 2) {
for (final Object o : cc) {
final GamaShape node = (GamaShape) o;
final Coordinate[] coordsArr =
GeometryUtils.extractPoints(node, new HashSet(Graphs.neighborsOf(scope, graph, node)));
if (coordsArr != null) { network.add(GEOMETRY_FACTORY.createLineString(coordsArr)); }
}
} else if (cc.size() == 2) {
final Coordinate[] coordsArr =
GeometryUtils.extractPoints((GamaShape) cc.get(0), (GamaShape) cc.get(1));
if (coordsArr != null) { network.add(GEOMETRY_FACTORY.createLineString(coordsArr)); }
}
}
return network;
}
/**
* Builds the geometry JTS.
*
* @param geomG the geom G
* @return the geometry
*/
public static Geometry buildGeometryJTS(final List<List<List<GamaPoint>>> geomG) {
final IShape.Type geometryType = geometryType(geomG);
switch (geometryType) {
case NULL:
return null;
case POINT:
return buildPoint(geomG.get(0));
case LINESTRING:
return buildLine(geomG.get(0));
case POLYGON:
return buildPolygon(geomG.get(0));
case MULTIPOINT:
final int nb = geomG.size();
final Point[] geoms = new Point[nb];
for (int i = 0; i < nb; i++) { geoms[i] = (Point) buildPoint(geomG.get(i)); }
return GEOMETRY_FACTORY.createMultiPoint(geoms);
case MULTILINESTRING:
final int n = geomG.size();
final LineString[] lines = new LineString[n];
for (int i = 0; i < n; i++) { lines[i] = (LineString) buildLine(geomG.get(i)); }
return GEOMETRY_FACTORY.createMultiLineString(lines);
case MULTIPOLYGON:
final int n3 = geomG.size();
final Polygon[] polys = new Polygon[n3];
for (int i = 0; i < n3; i++) { polys[i] = (Polygon) buildPolygon(geomG.get(i)); }
return GEOMETRY_FACTORY.createMultiPolygon(polys);
default:
return null;
}
}
/**
* Builds the point.
*
* @param listPoints the list points
* @return the geometry
*/
private static Geometry buildPoint(final List<List<GamaPoint>> listPoints) {
return GEOMETRY_FACTORY.createPoint(listPoints.get(0).get(0));
}
/**
* Builds the geometry collection.
*
* @param geoms the geoms
* @return the geometry
*/
public static Geometry buildGeometryCollection(final List<IShape> geoms) {
final int nb = geoms.size();
final Geometry[] geometries = new Geometry[nb];
for (int i = 0; i < nb; i++) { geometries[i] = geoms.get(i).getInnerGeometry(); }
return GEOMETRY_FACTORY.createGeometryCollection(geometries);
}
/**
* Builds the line.
*
* @param listPoints the list points
* @return the geometry
*/
private static Geometry buildLine(final List<List<GamaPoint>> listPoints) {
final List<GamaPoint> coords = listPoints.get(0);
final int nb = coords.size();
final Coordinate[] coordinates = new Coordinate[nb];
for (int i = 0; i < nb; i++) { coordinates[i] = coords.get(i); }
return GEOMETRY_FACTORY.createLineString(coordinates);
}
/**
* Builds the polygon.
*
* @param listPoints the list points
* @return the geometry
*/
private static Geometry buildPolygon(final List<List<GamaPoint>> listPoints) {
final List<GamaPoint> coords = listPoints.get(0);
final int nb = coords.size();
final Coordinate[] coordinates = new Coordinate[nb];
for (int i = 0; i < nb; i++) { coordinates[i] = coords.get(i); }
final int nbHoles = listPoints.size() - 1;
LinearRing[] holes = null;
if (nbHoles > 0) {
holes = new LinearRing[nbHoles];
for (int i = 0; i < nbHoles; i++) {
final List<GamaPoint> coordsH = listPoints.get(i + 1);
final int nbp = coordsH.size();
final Coordinate[] coordinatesH = new Coordinate[nbp];
for (int j = 0; j < nbp; j++) { coordinatesH[j] = coordsH.get(j); }
holes[i] = GEOMETRY_FACTORY.createLinearRing(coordinatesH);
}
}
return GEOMETRY_FACTORY.createPolygon(GEOMETRY_FACTORY.createLinearRing(coordinates), holes);
}
/**
* Geometry type.
*
* @param listPoints the list points
* @return the i shape. type
*/
private static IShape.Type geometryType(final List<List<List<GamaPoint>>> listPoints) {
final int size = listPoints.size();
if (size == 0) return NULL;
if (size == 1) return geometryTypeSimp(listPoints.get(0));
final IShape.Type type = geometryTypeSimp(listPoints.get(0));
switch (type) {
case POINT:
return MULTIPOINT;
case LINESTRING:
return MULTILINESTRING;
case POLYGON:
return POLYGON;
default:
return NULL;
}
}
/**
* Geometry type simp.
*
* @param listPoints the list points
* @return the i shape. type
*/
private static IShape.Type geometryTypeSimp(final List<List<GamaPoint>> listPoints) {
if (listPoints.isEmpty() || listPoints.get(0).isEmpty()) return NULL;
final List<GamaPoint> list0 = listPoints.get(0);
final int size0 = list0.size();
if (size0 == 1 || size0 == 2 && list0.get(0).equals(list0.get(listPoints.size() - 1))) return POINT;
if (!list0.get(0).equals(list0.get(listPoints.size() - 1)) || size0 < 3) return LINESTRING;
return POLYGON;
}
/**
* Locs on geometry.
*
* @param geom the geom
* @param distance the distance
* @return the i list
*/
public static IList<GamaPoint> locsOnGeometry(final Geometry geom, final Double distance) {
final IList<GamaPoint> locs = GamaListFactory.create(Types.POINT);
if (geom instanceof Point) {
locs.add(new GamaPoint(geom.getCoordinate()));
} else if (geom instanceof LineString) {
double distCur = 0;
final Coordinate[] coordsSimp = geom.getCoordinates();
if (coordsSimp.length > 0) { locs.add(new GamaPoint(coordsSimp[0])); }
final int nbSp = coordsSimp.length;
for (int i = 0; i < nbSp - 1; i++) {
Coordinate s = coordsSimp[i];
final Coordinate t = coordsSimp[i + 1];
while (true) {
final double dist = s.distance3D(t);
if (distance - distCur >= dist) {
if (distance - distCur > dist) {
distCur += dist;
} else {
distCur = 0;
locs.add(new GamaPoint(t));
}
break;
}
final double distTravel = distance - distCur;
final double ratio = distTravel / dist;
final double x_s = s.x + ratio * (t.x - s.x);
final double y_s = s.y + ratio * (t.y - s.y);
final double z_s = s.z + ratio * (t.z - s.z);
s = new Coordinate(x_s, y_s, z_s);
locs.add(new GamaPoint(s));
distCur = 0;
}
}
if (locs.size() > 1 && locs.get(0).distance3D(locs.get(locs.size() - 1)) < 0.1 * distance) {
locs.remove(locs.size() - 1);
}
} else if (geom instanceof Polygon) {
final Polygon poly = (Polygon) geom;
locs.addAll(locsOnGeometry(poly.getExteriorRing(), distance));
for (int i = 0; i < poly.getNumInteriorRing(); i++) {
locs.addAll(locsOnGeometry(poly.getInteriorRingN(i), distance));
}
}
return locs;
}
/**
* Locs along geometry.
*
* @param geom the geom
* @param rates the rates
* @return the i list
*/
public static IList<GamaPoint> locsAlongGeometry(final Geometry geom, final List<Double> rates) {
final IList<GamaPoint> locs = GamaListFactory.create(Types.POINT);
if (rates == null || rates.isEmpty()) return locs;
if (geom instanceof Point) {
for (int i = 0; i < rates.size(); i++) { locs.add(new GamaPoint(geom.getCoordinate())); }
} else if (geom instanceof LineString) {
for (Double rate : rates) {
final Coordinate[] coordsSimp = geom.getCoordinates();
final int nbSp = coordsSimp.length;
if (nbSp <= 0) return locs;
if (rate > 1.0) { rate = 1.0; }
if (rate < 0.0) { rate = 0.0; }
if (rate == 0) {
locs.add(new GamaPoint(coordsSimp[0]));
continue;
}
if (rate == 1) {
locs.add(new GamaPoint(coordsSimp[nbSp - 1]));
continue;
}
double distCur = 0;
final double distance = rate * geom.getLength();