This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git
The following commit(s) were added to refs/heads/geoapi-4.0 by this push:
new d5c45760ca feat(Geometry): implement parametrize for several analytic
geometries
d5c45760ca is described below
commit d5c45760ca167af3ec7f0af38d32069c3f8f6fef
Author: jsorel <[email protected]>
AuthorDate: Fri Nov 20 15:23:09 2026 +0100
feat(Geometry): implement parametrize for several analytic geometries
---
.../main/org/apache/sis/geometries/Geometry.java | 5 +-
.../internal/shared/DefaultNurbSurface.java | 9 +
.../sis/geometries/operation/BSplineSampler.java | 308 +++++++++++++++++
.../geometries/operation/GeometryProcessor.java | 30 +-
.../sis/geometries/operation/Parametrize.java | 366 +++++++++++++++++++++
.../apache/sis/geometries/surface/Ellipsoid.java | 12 +
.../org/apache/sis/geometries/surface/Sphere.java | 12 +
.../sis/geometries/operation/DiscretizeTest.java | 93 ++++++
.../sis/geometries/operation/ParametrizeTest.java | 201 ++++++++++-
.../sis/geometries/operation/TessellateTest.java | 51 +++
10 files changed, 1082 insertions(+), 5 deletions(-)
diff --git
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/Geometry.java
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/Geometry.java
index d85eadb662..e4fb730c89 100644
---
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/Geometry.java
+++
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/Geometry.java
@@ -1121,6 +1121,8 @@ public sealed interface Geometry
* <li>The {@linkplain #getRepresentation() representation} of the
returned geometry is
* {@code PARAMETRIC}, {@code DISCRETE} or {@code TESSELLATED}.</li>
* <li>A geometry which is already at one of those levels, or empty, is
returned unchanged.</li>
+ * <li>Round shapes, such as spheres, ellipsoids, cylinders and
capsules, become rational NURBS surfaces.
+ * Boxes become polyhedra.</li>
* </ul>
*
* <p>Difference with ISO 19107: this operation has no equivalent in the
standard.</p>
@@ -1152,8 +1154,9 @@ public sealed interface Geometry
* of this geometry.</li>
* <li>Curves are converted with {@link Curve#asLine(Quantity,
Quantity)}, so a line string
* is densified when a spacing is given.</li>
+ * <li>B-spline surfaces become TINs. Analytic geometries are
{@linkplain #parametrize() parametrized} first.</li>
* <li>Other geometries which are already discrete or tessellated, or
empty, are returned unchanged.</li>
- * <li>Limitation: the spacing and the offset are applied to curves only.
+ * <li>Limitation: the spacing and the offset are applied to curves and
to B-spline surfaces only.
* Polygons and polyhedral patches are not subdivided.</li>
* </ul>
*
diff --git
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultNurbSurface.java
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultNurbSurface.java
index 65dfdc6079..f654da932a 100644
---
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultNurbSurface.java
+++
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/internal/shared/DefaultNurbSurface.java
@@ -398,6 +398,15 @@ public non-sealed class DefaultNurbSurface extends
AbstractGeometry implements N
return NDArrays.of(positions,
SampleSystem.of(getCoordinateReferenceSystem()),
controlPoints[0][0].getDataType());
}
+ /**
+ * Returns whether this surface has no control point. Overridden because
the default
+ * implementation uses the {@linkplain #getDataPoints() data points},
which are not supported yet.
+ */
+ @Override
+ public boolean isEmpty() {
+ return controlPoints.length == 0 || controlPoints[0].length == 0;
+ }
+
@Override
public DataPoints getDataPoints() {
throw new UnsupportedOperationException("Not supported yet.");
diff --git
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/BSplineSampler.java
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/BSplineSampler.java
new file mode 100644
index 0000000000..d9d1e3cf0c
--- /dev/null
+++
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/BSplineSampler.java
@@ -0,0 +1,308 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.geometries.operation;
+
+import java.util.ArrayList;
+import java.util.List;
+import javax.measure.Quantity;
+import javax.measure.Unit;
+import org.opengis.referencing.crs.CoordinateReferenceSystem;
+import org.apache.sis.geometries.Geometries;
+import org.apache.sis.geometries.GeometryFactory;
+import org.apache.sis.geometries.internal.shared.Curves;
+import org.apache.sis.geometries.surface.BSplineSurface;
+import org.apache.sis.geometries.surface.TIN;
+import org.apache.sis.geometries.surface.Triangle;
+
+
+/**
+ * Approximation of a B-spline surface by a TIN whose vertices lie on the
surface,
+ * used by {@link
GeometryProcessor#discretize(org.apache.sis.geometries.Geometry, Quantity,
Quantity)}.
+ *
+ * <p>The surface is sampled on a grid of parameters, with the same number of
divisions in every knot span.
+ * Each grid cell gives two triangles split along the diagonal going from
(u₀,v₀) to (u₁,v₁), which keeps
+ * the up-normal of the surface. Triangles collapsed at a pole or an apex are
omitted.</p>
+ *
+ * <p>Constraints:</p>
+ * <ul>
+ * <li>Without spacing nor offset, each knot span is divided {@value
#DEFAULT_DIVISIONS} times.</li>
+ * <li>Otherwise the divisions are doubled until the limits are met, up to
{@value #MAX_DIVISIONS}
+ * divisions per knot span.</li>
+ * <li>Limitation: the limits are checked at the middles of the triangle
edges only.
+ * The distance along the surface between two vertices is estimated by a
polyline
+ * through the middle of their edge.</li>
+ * </ul>
+ *
+ * @author Johann Sorel (Geomatys)
+ */
+final class BSplineSampler {
+
+ /**
+ * Number of divisions of each knot span when no limit is given.
+ */
+ static final int DEFAULT_DIVISIONS = 8;
+
+ /**
+ * Maximal number of divisions of each knot span, for protection against
unreachable limits.
+ */
+ static final int MAX_DIVISIONS = 256;
+
+ /**
+ * The surface to approximate.
+ */
+ private final BSplineSurface surface;
+
+ /**
+ * Distinct knots of each parameter inside the parameter domain, in
increasing order.
+ */
+ private final double[] breaksU, breaksV;
+
+ /**
+ * Prepares the sampling of the given surface.
+ *
+ * @param surface the surface to approximate.
+ */
+ BSplineSampler(final BSplineSurface surface) {
+ this.surface = surface;
+ final List<double[]> knots = surface.getKnots();
+ final int degree = surface.getDegree();
+ breaksU = breaks(knots.get(0), degree);
+ breaksV = breaks(knots.get(1), degree);
+ }
+
+ /**
+ * Returns the distinct knot values from the start to the end of the
parameter domain.
+ */
+ private static double[] breaks(final double[] knots, final int degree) {
+ final double start = knots[degree];
+ final double end = knots[knots.length - degree - 1];
+ final List<Double> values = new ArrayList<>();
+ values.add(start);
+ for (final double knot : knots) {
+ if (knot > values.get(values.size() - 1) && knot <= end) {
+ values.add(knot);
+ }
+ }
+ final double[] result = new double[values.size()];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = values.get(i);
+ }
+ return result;
+ }
+
+ /**
+ * Returns the triangulated approximation of the surface.
+ *
+ * @param spacing maximal distance along the surface between two
adjacent vertices, or zero or {@code null}.
+ * @param offset maximal distance between the surface and the
triangles, or zero or {@code null}.
+ * @return the approximation of the surface.
+ * @throws IllegalArgumentException if the spacing or the offset is
negative or not a length.
+ */
+ TIN sample(final Quantity<?> spacing, final Quantity<?> offset) {
+ final Unit<?> unit = Geometries.getLinearUnit(surface);
+ final double maxSpacing = distance(spacing, unit);
+ final double maxOffset = distance(offset, unit);
+ if (maxSpacing == 0 && maxOffset == 0) {
+ return triangles(grid(DEFAULT_DIVISIONS));
+ }
+ /*
+ * The grid is evaluated with twice the divisions: the samples of even
indices are the vertices,
+ * and the samples of odd indices are the middles of the edges, used
for checking the limits.
+ */
+ int divisions = 1;
+ double[][][] fine = grid(2 * divisions);
+ while (divisions < MAX_DIVISIONS && !accepts(fine, maxSpacing,
maxOffset)) {
+ divisions *= 2;
+ fine = grid(2 * divisions);
+ }
+ return triangles(vertices(fine));
+ }
+
+ /**
+ * Converts the given spacing or offset to the unit of the coordinates.
+ *
+ * @return the distance in the unit of the coordinates, or 0 for no limit.
+ */
+ private static double distance(final Quantity<?> q, final Unit<?> unit) {
+ if (q == null) {
+ return 0;
+ }
+ final double value = Curves.convert(q, unit);
+ if (!(value >= 0) || Double.isInfinite(value)) {
+ throw new IllegalArgumentException("The spacing and the offset of
an approximation must be"
+ + " positive or zero, but got " + q + '.');
+ }
+ return value;
+ }
+
+ /**
+ * Evaluates the surface on a grid dividing each knot span the given
number of times.
+ *
+ * @return positions indexed by [u index][v index][coordinate].
+ */
+ private double[][][] grid(final int divisions) {
+ final double[] us = parameters(breaksU, divisions);
+ final double[] vs = parameters(breaksV, divisions);
+ final double[][][] positions = new double[us.length][vs.length][];
+ for (int a = 0; a < us.length; a++) {
+ for (int b = 0; b < vs.length; b++) {
+ positions[a][b] = surface.getSurface(us[a],
vs[b]).toArrayDouble();
+ }
+ }
+ return positions;
+ }
+
+ /**
+ * Returns the parameters dividing each interval between the given breaks
the given number of times.
+ */
+ private static double[] parameters(final double[] breaks, final int
divisions) {
+ final double[] values = new double[(breaks.length - 1) * divisions +
1];
+ for (int s = 0; s + 1 < breaks.length; s++) {
+ for (int d = 0; d < divisions; d++) {
+ values[s * divisions + d] = breaks[s] + (breaks[s + 1] -
breaks[s]) * d / divisions;
+ }
+ }
+ values[values.length - 1] = breaks[breaks.length - 1];
+ return values;
+ }
+
+ /**
+ * Returns the samples of even indices, which are the vertices of a grid
evaluated with twice the divisions.
+ */
+ private static double[][][] vertices(final double[][][] fine) {
+ final double[][][] coarse = new double[fine.length / 2 +
1][fine[0].length / 2 + 1][];
+ for (int a = 0; a < coarse.length; a++) {
+ for (int b = 0; b < coarse[a].length; b++) {
+ coarse[a][b] = fine[2 * a][2 * b];
+ }
+ }
+ return coarse;
+ }
+
+ /**
+ * Returns whether the triangles made from the even samples of the given
grid meet the limits.
+ * Each edge between two vertices is checked at its middle, which is an
odd sample: the distance of
+ * that sample to the middle of the straight edge estimates the offset,
and the polyline through it
+ * estimates the distance along the surface.
+ */
+ private static boolean accepts(final double[][][] fine, final double
maxSpacing, final double maxOffset) {
+ for (int a = 0; a + 2 < fine.length; a += 2) {
+ for (int b = 0; b + 2 < fine[a].length; b += 2) {
+ final double[] p00 = fine[a][b];
+ if (!accepts(p00, fine[a + 1][b], fine[a + 2][b],
maxSpacing, maxOffset) || // Edge along u.
+ !accepts(p00, fine[a][b + 1], fine[a][b + 2],
maxSpacing, maxOffset) || // Edge along v.
+ !accepts(p00, fine[a + 1][b + 1], fine[a + 2][b + 2],
maxSpacing, maxOffset)) // Diagonal.
+ {
+ return false;
+ }
+ }
+ }
+ /*
+ * The edges on the last row and the last column are not the first
edges of any cell.
+ */
+ final int lastA = fine.length - 1, lastB = fine[0].length - 1;
+ for (int a = 0; a + 2 <= lastA; a += 2) {
+ if (!accepts(fine[a][lastB], fine[a + 1][lastB], fine[a +
2][lastB], maxSpacing, maxOffset)) {
+ return false;
+ }
+ }
+ for (int b = 0; b + 2 <= lastB; b += 2) {
+ if (!accepts(fine[lastA][b], fine[lastA][b + 1], fine[lastA][b +
2], maxSpacing, maxOffset)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns whether the edge from {@code start} to {@code end}, whose
middle on the surface is {@code middle},
+ * meets the limits.
+ */
+ private static boolean accepts(final double[] start, final double[]
middle, final double[] end,
+ final double maxSpacing, final double
maxOffset)
+ {
+ if (maxSpacing > 0 && distance(start, middle) + distance(middle, end)
> maxSpacing) {
+ return false;
+ }
+ if (maxOffset > 0) {
+ double sum = 0;
+ for (int i = 0; i < middle.length; i++) {
+ final double d = middle[i] - (start[i] + end[i]) / 2;
+ sum += d * d;
+ }
+ return Math.sqrt(sum) <= maxOffset;
+ }
+ return true;
+ }
+
+ private static double distance(final double[] p, final double[] q) {
+ double sum = 0;
+ for (int i = 0; i < p.length; i++) {
+ final double d = p[i] - q[i];
+ sum += d * d;
+ }
+ return Math.sqrt(sum);
+ }
+
+ /**
+ * Returns the TIN of the given grid of vertices, two triangles per cell.
+ */
+ private TIN triangles(final double[][][] grid) {
+ final CoordinateReferenceSystem crs =
surface.getCoordinateReferenceSystem();
+ final List<Triangle> triangles = new ArrayList<>();
+ for (int a = 0; a + 1 < grid.length; a++) {
+ for (int b = 0; b + 1 < grid[a].length; b++) {
+ final double[] p00 = grid[a][b], p10 = grid[a + 1][b];
+ final double[] p01 = grid[a][b + 1], p11 = grid[a + 1][b + 1];
+ addTriangle(triangles, crs, p00, p10, p11);
+ addTriangle(triangles, crs, p00, p11, p01);
+ }
+ }
+ return GeometryFactory.DEFAULT.createTIN(crs,
triangles.toArray(Triangle[]::new));
+ }
+
+ /**
+ * Adds the triangle of the given vertices, unless two of them are at the
same position.
+ */
+ private static void addTriangle(final List<Triangle> triangles, final
CoordinateReferenceSystem crs,
+ final double[] p0, final double[] p1,
final double[] p2)
+ {
+ if (same(p0, p1) || same(p1, p2) || same(p2, p0)) {
+ return;
+ }
+ final int dim = p0.length;
+ final double[] coordinates = new double[4 * dim];
+ System.arraycopy(p0, 0, coordinates, 0, dim);
+ System.arraycopy(p1, 0, coordinates, dim, dim);
+ System.arraycopy(p2, 0, coordinates, 2 * dim, dim);
+ System.arraycopy(p0, 0, coordinates, 3 * dim, dim);
+ final GeometryFactory factory = GeometryFactory.DEFAULT;
+
triangles.add(factory.createTriangle(factory.createLinearRing(factory.createDataPoints(crs,
coordinates))));
+ }
+
+ /**
+ * Returns whether the two positions are equal within a tolerance relative
to their magnitude,
+ * since the poles of a surface of revolution are computed with rounding
errors.
+ */
+ private static boolean same(final double[] p, final double[] q) {
+ double scale = 0;
+ for (int i = 0; i < p.length; i++) {
+ scale = Math.max(scale, Math.max(Math.abs(p[i]), Math.abs(q[i])));
+ }
+ return distance(p, q) <= 1E-12 * Math.max(1, scale);
+ }
+}
diff --git
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/GeometryProcessor.java
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/GeometryProcessor.java
index a15e2db417..db4d0e00bc 100644
---
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/GeometryProcessor.java
+++
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/GeometryProcessor.java
@@ -31,6 +31,7 @@ import org.opengis.annotation.UML;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.util.FactoryException;
+import org.apache.sis.geometries.BBox;
import org.apache.sis.geometries.Curve;
import org.apache.sis.geometries.DE9IM;
import org.apache.sis.geometries.DataPointsType;
@@ -39,6 +40,7 @@ import org.apache.sis.geometries.Geometry;
import org.apache.sis.geometries.GeometryCollection;
import org.apache.sis.geometries.GeometryFactory;
import org.apache.sis.geometries.GeometryType;
+import org.apache.sis.geometries.OBBox;
import org.apache.sis.geometries.Point;
import org.apache.sis.geometries.Prism;
import org.apache.sis.geometries.Representation;
@@ -51,9 +53,14 @@ import org.apache.sis.geometries.internal.shared.Vertex;
import org.apache.sis.geometries.mesh.MeshPrimitive;
import org.apache.sis.geometries.mesh.MeshPrimitiveVisitor;
import org.apache.sis.geometries.solid.Polyhedron;
+import org.apache.sis.geometries.surface.BSplineSurface;
+import org.apache.sis.geometries.surface.Capsule;
import org.apache.sis.geometries.surface.CurvePolygon;
+import org.apache.sis.geometries.surface.Cylinder;
+import org.apache.sis.geometries.surface.Ellipsoid;
import org.apache.sis.geometries.surface.Polygon;
import org.apache.sis.geometries.surface.PolyhedralSurface;
+import org.apache.sis.geometries.surface.Sphere;
import org.apache.sis.geometries.surface.Triangle;
import org.apache.sis.maths.Array;
import org.apache.sis.maths.Cursor;
@@ -539,7 +546,14 @@ public final class GeometryProcessor {
*
* <p>Constraints:</p>
* <ul>
- * <li>Geometries which are not {@linkplain Representation#ANALYTIC
analytic} are returned unchanged.</li>
+ * <li>Empty geometries and geometries which are not {@linkplain
Representation#ANALYTIC analytic}
+ * are returned unchanged.</li>
+ * <li>Spheres and ellipsoids become rational NURBS surfaces of 9 × 5
control points.</li>
+ * <li>A cylinder becomes its lateral NURBS surface, with the NURBS
disks closing its ends if it is
+ * {@linkplain Cylinder#isClosed() closed}.</li>
+ * <li>A capsule becomes a NURBS surface made of an arc of each capping
sphere and of the cone
+ * tangent to both.</li>
+ * <li>A box becomes a polygon in 2 dimensions, or a polyhedron in 3
dimensions.</li>
* <li>A prism is replaced by its {@linkplain Prism#toExtrusion()
extrusion}.</li>
* <li>The elements of a collection are converted one by one.</li>
* </ul>
@@ -551,10 +565,16 @@ public final class GeometryProcessor {
* @see Geometry#parametrize()
*/
public Geometry parametrize(Geometry geom) throws OperationException {
- if (geom.getRepresentation() != Representation.ANALYTIC) {
+ if (geom.isEmpty() || geom.getRepresentation() !=
Representation.ANALYTIC) {
return geom;
}
return switch (geom) {
+ case Sphere cdt -> Parametrize.sphere(cdt);
+ case Ellipsoid cdt -> Parametrize.ellipsoid(cdt);
+ case Cylinder cdt -> Parametrize.cylinder(cdt);
+ case Capsule cdt -> Parametrize.capsule(cdt);
+ case BBox cdt -> Parametrize.box(cdt);
+ case OBBox cdt -> Parametrize.box(cdt);
case Prism cdt -> cdt.toExtrusion();
case GeometryCollection<?> cdt -> convertElements(cdt,
this::parametrize);
default -> throw new UnsupportedOperationException(
@@ -569,8 +589,11 @@ public final class GeometryProcessor {
* <ul>
* <li>Curves are replaced by their {@linkplain Curve#asLine(Quantity,
Quantity) linear approximation}.</li>
* <li>Curve polygons are replaced by polygons whose rings are linear
approximations of the curves.</li>
+ * <li>B-spline surfaces are replaced by TINs whose vertices are sampled
on the surface.</li>
* <li>A prism is replaced by the {@linkplain Prism#toExtrusion()
extrusion} of its discretized base.</li>
* <li>The elements of a collection are converted one by one.</li>
+ * <li>Other {@linkplain Representation#ANALYTIC analytic} geometries are
+ * {@linkplain #parametrize(Geometry) parametrized} first.</li>
* <li>Other geometries already at the discrete level or below are
returned unchanged.</li>
* </ul>
*
@@ -595,10 +618,13 @@ public final class GeometryProcessor {
case MeshPrimitive cdt -> cdt;
case Curve cdt -> cdt.asLine(spacing, offset);
case CurvePolygon cdt -> discretize(cdt, spacing, offset);
+ case BSplineSurface cdt -> new
BSplineSampler(cdt).sample(spacing, offset);
case Prism cdt -> discretize(cdt, spacing, offset);
case GeometryCollection<?> cdt -> convertElements(cdt, (element)
-> discretize(element, spacing, offset));
default -> switch (geom.getRepresentation()) {
case EMPTY, DISCRETE, TESSELLATED -> geom;
+ // The parametric form is never analytic, otherwise
`parametrize` throws an exception.
+ case ANALYTIC -> discretize(parametrize(geom), spacing,
offset);
default -> throw new UnsupportedOperationException(
"Discretization of " + geom.getGeometryType() + "
geometries is not supported yet.");
};
diff --git
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Parametrize.java
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Parametrize.java
new file mode 100644
index 0000000000..8338fc22d9
--- /dev/null
+++
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/operation/Parametrize.java
@@ -0,0 +1,366 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.geometries.operation;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.opengis.referencing.crs.CoordinateReferenceSystem;
+import org.apache.sis.geometries.BBox;
+import org.apache.sis.geometries.Geometry;
+import org.apache.sis.geometries.GeometryCollection;
+import org.apache.sis.geometries.GeometryFactory;
+import org.apache.sis.geometries.GeometryType;
+import org.apache.sis.geometries.OBBox;
+import org.apache.sis.geometries.curve.LinearRing;
+import org.apache.sis.geometries.surface.Capsule;
+import org.apache.sis.geometries.surface.Cylinder;
+import org.apache.sis.geometries.surface.Ellipsoid;
+import org.apache.sis.geometries.surface.NurbSurface;
+import org.apache.sis.geometries.surface.Polygon;
+import org.apache.sis.geometries.surface.Sphere;
+import org.apache.sis.maths.DataType;
+import org.apache.sis.maths.Vector;
+import org.apache.sis.maths.Vectors;
+
+
+/**
+ * Exact parametric forms of analytic geometries, used by {@link
GeometryProcessor#parametrize(Geometry)}.
+ *
+ * <p>Round shapes become rational NURBS surfaces of degree 2, made by
revolving a profile around an axis:
+ * rational quadratic arcs represent circles and ellipses exactly. Boxes
become polyhedra.</p>
+ *
+ * <p>Constraints:</p>
+ * <ul>
+ * <li>The surfaces are parameterized with <var>u</var> turning
counterclockwise around the axis and
+ * <var>v</var> following the profile, so that their up-normal (∂S/∂u ×
∂S/∂v) points outward.</li>
+ * <li>Round shapes are parametrized in 3 dimensions only.</li>
+ * </ul>
+ *
+ * @author Johann Sorel (Geomatys)
+ */
+final class Parametrize {
+
+ /**
+ * Degree of the NURBS surfaces in both directions.
+ */
+ private static final int DEGREE = 2;
+
+ /**
+ * Weight of the control points at the corners of the quarter arcs:
cos(45°).
+ */
+ private static final double CORNER = Math.sqrt(0.5);
+
+ /**
+ * Unit circle made of four rational quadratic quarter arcs, as (x, y,
weight) for each control point.
+ */
+ private static final double[][] UNIT_CIRCLE = {
+ { 1, 0, 1}, { 1, 1, CORNER}, { 0, 1, 1}, {-1, 1, CORNER}, {-1, 0,
1},
+ {-1, -1, CORNER}, { 0, -1, 1}, { 1, -1, CORNER}, { 1, 0, 1}
+ };
+
+ /**
+ * Knots of {@link #UNIT_CIRCLE}, one quarter arc per knot interval.
+ */
+ private static final double[] CIRCLE_KNOTS = {0, 0, 0, 0.25, 0.25, 0.5,
0.5, 0.75, 0.75, 1, 1, 1};
+
+ /**
+ * Half meridian from the south pole to the north pole, as (radius,
height, weight) for each control point.
+ */
+ private static final double[][] MERIDIAN = {
+ {0, -1, 1}, {1, -1, CORNER}, {1, 0, 1}, {1, 1, CORNER}, {0, 1, 1}
+ };
+
+ /**
+ * Knots of {@link #MERIDIAN}, one quarter arc per knot interval.
+ */
+ private static final double[] MERIDIAN_KNOTS = {0, 0, 0, 0.5, 0.5, 1, 1,
1};
+
+ /**
+ * Knots of a straight segment given as a quadratic arc of three aligned
control points.
+ */
+ private static final double[] SEGMENT_KNOTS = {0, 0, 0, 1, 1, 1};
+
+ private Parametrize() {
+ }
+
+ /**
+ * Returns the sphere as a NURBS surface of 9 × 5 control points.
+ *
+ * @throws UnsupportedOperationException if the sphere is not
3-dimensional.
+ */
+ static NurbSurface sphere(final Sphere sphere) {
+ final double r = sphere.getRadius();
+ return ellipsoidal(sphere.getCoordinateReferenceSystem(),
sphere.getCenter(), new double[] {r, r, r});
+ }
+
+ /**
+ * Returns the ellipsoid as a NURBS surface of 9 × 5 control points:
+ * the NURBS sphere scaled by the semi-axes, NURBS being invariant under
affine transforms.
+ *
+ * @throws UnsupportedOperationException if the ellipsoid is not
3-dimensional.
+ */
+ static NurbSurface ellipsoid(final Ellipsoid ellipsoid) {
+ return ellipsoidal(ellipsoid.getCoordinateReferenceSystem(),
ellipsoid.getCenter(), ellipsoid.getSemiAxes());
+ }
+
+ /**
+ * Returns the ellipsoid of the given center and semi-axes, its axis of
revolution along the third axis.
+ */
+ private static NurbSurface ellipsoidal(final CoordinateReferenceSystem
crs, final Vector<?> center, final double[] semiAxes) {
+ ensure3D(center, "An ellipsoid");
+ final Frame frame = new Frame(center.copy(DataType.DOUBLE),
+ Vectors.create(new double[] {semiAxes[0], 0, 0},
DataType.DOUBLE),
+ Vectors.create(new double[] {0, semiAxes[1], 0},
DataType.DOUBLE),
+ Vectors.create(new double[] {0, 0, semiAxes[2]},
DataType.DOUBLE));
+ return frame.revolve(crs, MERIDIAN, MERIDIAN_KNOTS);
+ }
+
+ /**
+ * Returns the cylinder as its lateral NURBS surface, followed by the
disks closing its ends if it is closed.
+ * An end whose radius is zero, the apex of a cone, has no disk.
+ *
+ * @return the lateral surface if the cylinder is open, or a collection of
surfaces otherwise.
+ * @throws UnsupportedOperationException if the cylinder is not
3-dimensional.
+ * @throws OperationException if the two positions of the cylinder are the
same.
+ */
+ static Geometry cylinder(final Cylinder cylinder) {
+ final Vector<?> bottom =
cylinder.getDataPoints().getPosition(0).copy(DataType.DOUBLE);
+ final Vector<?> top =
cylinder.getDataPoints().getPosition(1).copy(DataType.DOUBLE);
+ ensure3D(bottom, "A cylinder");
+ final Vector<?> axisVector = top.subtract(bottom);
+ final double height = axisVector.length();
+ if (!(height > 0)) {
+ throw new OperationException("The cylinder has no axis, its two
positions are the same.");
+ }
+ final Frame frame = Frame.alongAxis(bottom, axisVector.scale(1 /
height));
+ final CoordinateReferenceSystem crs =
cylinder.getCoordinateReferenceSystem();
+ final double rb = cylinder.getRadiusBottom();
+ final double rt = cylinder.getRadiusTop();
+ final NurbSurface lateral = frame.revolve(crs,
+ new double[][] {{rb, 0, 1}, {(rb + rt) / 2, height / 2, 1},
{rt, height, 1}}, SEGMENT_KNOTS);
+ if (!cylinder.isClosed()) {
+ return lateral;
+ }
+ /*
+ * The bottom disk goes from the center to the rim and the top disk
from the rim to the center,
+ * so that both of them face away from the cylinder.
+ */
+ final List<NurbSurface> patches = new ArrayList<>(3);
+ if (rb > 0) {
+ patches.add(frame.revolve(crs, new double[][] {{0, 0, 1}, {rb / 2,
0, 1}, {rb, 0, 1}}, SEGMENT_KNOTS));
+ }
+ patches.add(lateral);
+ if (rt > 0) {
+ patches.add(frame.revolve(crs, new double[][] {{rt, height, 1},
{rt / 2, height, 1}, {0, height, 1}}, SEGMENT_KNOTS));
+ }
+ return
GeometryFactory.DEFAULT.createGeometryCollection(GeometryType.SURFACE, crs,
patches.toArray(NurbSurface[]::new));
+ }
+
+ /**
+ * Returns the capsule, the convex hull of its two capping spheres, as a
NURBS surface.
+ * The profile revolved around the axis is an arc of the bottom sphere
from the south pole,
+ * the segment tangent to both spheres, then an arc of the top sphere up
to the north pole.
+ * If one sphere contains the other one, the capsule is the largest sphere.
+ *
+ * @throws UnsupportedOperationException if the capsule is not
3-dimensional.
+ */
+ static NurbSurface capsule(final Capsule capsule) {
+ final Vector<?> bottom =
capsule.getDataPoints().getPosition(0).copy(DataType.DOUBLE);
+ final Vector<?> top =
capsule.getDataPoints().getPosition(1).copy(DataType.DOUBLE);
+ ensure3D(bottom, "A capsule");
+ final CoordinateReferenceSystem crs =
capsule.getCoordinateReferenceSystem();
+ final double rb = capsule.getRadiusBottom();
+ final double rt = capsule.getRadiusTop();
+ final Vector<?> axisVector = top.subtract(bottom);
+ final double height = axisVector.length();
+ if (!(height > Math.abs(rb - rt))) {
+ return (rb >= rt) ? ellipsoidal(crs, bottom, new double[] {rb, rb,
rb})
+ : ellipsoidal(crs, top, new double[] {rt, rt,
rt});
+ }
+ /*
+ * The segment tangent to both spheres touches them where their
outward normal is
+ * (cos α, sin α) in the (radius, height) plane, with sin α = (rb −
rt) / height.
+ */
+ final double alpha = Math.asin((rb - rt) / height);
+ final Profile profile = new Profile(0, -rb);
+ profile.arc(0, rb, -Math.PI / 2, alpha);
+ profile.line(rt * Math.cos(alpha), height + rt * Math.sin(alpha));
+ profile.arc(height, rt, alpha, Math.PI / 2);
+ return Frame.alongAxis(bottom, axisVector.scale(1 /
height)).revolve(crs, profile.points(), profile.knots());
+ }
+
+ /**
+ * Returns the box as a polygon in 2 dimensions, or as a polyhedron in 3
dimensions.
+ *
+ * @throws UnsupportedOperationException if the box has another number of
dimensions.
+ */
+ @SuppressWarnings("unchecked")
+ static Geometry box(final BBox box) {
+ return switch (box.getDimension()) {
+ case 2 -> GeometryFactory.DEFAULT.createPolygon((LinearRing)
box.getBoundary(), List.of());
+ case 3 ->
GeometryFactory.DEFAULT.createPolyhedron((GeometryCollection<Polygon>)
box.getBoundary(), List.of());
+ default -> throw new UnsupportedOperationException(
+ "A box is parametrized in 2 or 3 dimensions only, not " +
box.getDimension() + '.');
+ };
+ }
+
+ /**
+ * Returns the oriented box as a polyhedron.
+ */
+ @SuppressWarnings("unchecked")
+ static Geometry box(final OBBox box) {
+ return
GeometryFactory.DEFAULT.createPolyhedron((GeometryCollection<Polygon>)
box.getBoundary(), List.of());
+ }
+
+ /**
+ * Ensures that the given position is 3-dimensional.
+ */
+ private static void ensure3D(final Vector<?> position, final String shape)
{
+ if (position.getDimension() != 3) {
+ throw new UnsupportedOperationException(shape + " is parametrized
in 3 dimensions only.");
+ }
+ }
+
+ /**
+ * Local frame in which a profile is revolved: an origin and three axes,
which are scaled as needed.
+ *
+ * @param origin position of the frame origin.
+ * @param e1 first axis of the plane of the circles.
+ * @param e2 second axis of the plane of the circles.
+ * @param e3 axis of revolution.
+ */
+ private record Frame(Vector<?> origin, Vector<?> e1, Vector<?> e2,
Vector<?> e3) {
+
+ /**
+ * Returns the right-handed orthonormal frame whose third axis is the
given unit vector.
+ * The first axis is derived from the coordinate axis which is the
most perpendicular
+ * to the given one, for numerical stability.
+ *
+ * @param origin position of the frame origin.
+ * @param axis unit vector of the axis of revolution.
+ */
+ static Frame alongAxis(final Vector<?> origin, final Vector<?> axis) {
+ int k = 0;
+ for (int i = 1; i < 3; i++) {
+ if (Math.abs(axis.get(i)) < Math.abs(axis.get(k))) {
+ k = i;
+ }
+ }
+ final double[] unit = new double[3];
+ unit[k] = 1;
+ final Vector<?> u = Vectors.create(unit,
DataType.DOUBLE).subtract(axis.scale(axis.get(k))).normalize();
+ return new Frame(origin, u, axis.cross(u), axis);
+ }
+
+ /**
+ * Returns the position at the given coordinates in this frame.
+ */
+ Vector<?> at(final double a, final double b, final double c) {
+ return origin.add(e1.scale(a)).add(e2.scale(b)).add(e3.scale(c));
+ }
+
+ /**
+ * Returns the surface swept by the given profile turning once around
the third axis.
+ * The control points are the tensor product of the unit circle and of
the profile,
+ * with the products of their weights.
+ *
+ * @param crs reference system of the surface.
+ * @param profile control points of the profile, as (radius,
height, weight).
+ * @param profileKnots knots of the profile.
+ * @return the surface of revolution.
+ */
+ NurbSurface revolve(final CoordinateReferenceSystem crs, final
double[][] profile, final double[] profileKnots) {
+ final Vector<?>[][] points = new
Vector<?>[UNIT_CIRCLE.length][profile.length];
+ final double[][] weights = new
double[UNIT_CIRCLE.length][profile.length];
+ for (int i = 0; i < UNIT_CIRCLE.length; i++) {
+ final double[] c = UNIT_CIRCLE[i];
+ for (int j = 0; j < profile.length; j++) {
+ final double[] p = profile[j];
+ points[i][j] = at(c[0] * p[0], c[1] * p[0], p[1]);
+ weights[i][j] = c[2] * p[2];
+ }
+ }
+ return GeometryFactory.DEFAULT.createNurbSurface(crs, points,
weights,
+ CIRCLE_KNOTS.clone(), profileKnots.clone(), DEGREE);
+ }
+ }
+
+ /**
+ * Profile of a surface of revolution in the (radius, height) plane, made
of rational quadratic pieces
+ * joined end to end. Each piece is an arc of at most 90° or a straight
segment, and adds two control
+ * points: its middle control point and its end.
+ */
+ private static final class Profile {
+ /**
+ * Control points as (radius, height, weight).
+ */
+ private final List<double[]> points = new ArrayList<>();
+
+ /**
+ * Starts a profile at the given position.
+ */
+ Profile(final double radius, final double height) {
+ points.add(new double[] {radius, height, 1});
+ }
+
+ /**
+ * Appends the arc of the circle centered on the axis at the given
height, from angle {@code a0}
+ * to angle {@code a1} in radians, measured from the radial direction
toward the axis direction.
+ * The arc is expected to start at the end of the profile.
+ */
+ void arc(final double height, final double radius, final double a0,
final double a1) {
+ final int count = (int) Math.ceil(Math.abs(a1 - a0) / (Math.PI /
2) - 1E-12);
+ final double step = (a1 - a0) / Math.max(count, 1);
+ for (int i = 0; i < count; i++) {
+ final double start = a0 + step * i;
+ final double half = step / 2;
+ final double reach = radius / Math.cos(half); //
Distance to the intersection of the end tangents.
+ final double end = start + step;
+ points.add(new double[] {reach * Math.cos(start + half),
height + reach * Math.sin(start + half), Math.cos(half)});
+ points.add(new double[] {radius * Math.cos(end), height +
radius * Math.sin(end), 1});
+ }
+ }
+
+ /**
+ * Appends the straight segment from the end of the profile to the
given position.
+ */
+ void line(final double radius, final double height) {
+ final double[] start = points.get(points.size() - 1);
+ points.add(new double[] {(start[0] + radius) / 2, (start[1] +
height) / 2, 1});
+ points.add(new double[] {radius, height, 1});
+ }
+
+ /**
+ * Returns the control points as (radius, height, weight).
+ */
+ double[][] points() {
+ return points.toArray(double[][]::new);
+ }
+
+ /**
+ * Returns the knots, with one interval per piece and a double knot at
each junction.
+ */
+ double[] knots() {
+ final int pieces = (points.size() - 1) / 2;
+ final double[] knots = new double[2 * pieces + 4];
+ for (int i = 0; i < knots.length; i++) {
+ knots[i] = Math.clamp((double) ((i - 1) / 2) / pieces, 0, 1);
+ }
+ return knots;
+ }
+ }
+}
diff --git
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/surface/Ellipsoid.java
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/surface/Ellipsoid.java
index 775eb4b41d..5f62717af1 100644
---
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/surface/Ellipsoid.java
+++
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/surface/Ellipsoid.java
@@ -25,6 +25,7 @@ import org.apache.sis.geometries.DataPointsType;
import org.apache.sis.geometries.Geometry;
import org.apache.sis.geometries.GeometryFactory;
import org.apache.sis.geometries.GeometryType;
+import org.apache.sis.geometries.Representation;
import org.apache.sis.geometries.SurfaceInterpolation;
import org.apache.sis.geometries.internal.shared.DefaultEllipsoid;
import org.apache.sis.maths.NDRange;
@@ -65,6 +66,17 @@ public sealed interface Ellipsoid extends
ParametricCurveSurface
return GeometryType.ELLIPSOID;
}
+ /**
+ * Returns {@link Representation#ANALYTIC}: an ellipsoid is defined by its
center and its semi-axes,
+ * even though it can be traversed as a parametric curve surface.
+ *
+ * @see Geometry#parametrize()
+ */
+ @Override
+ default Representation getRepresentation() {
+ return Representation.ANALYTIC;
+ }
+
/**
* Returns {@code false}: an ellipsoid always has a center.
*/
diff --git
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/surface/Sphere.java
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/surface/Sphere.java
index c9c23b1e36..d7ce3bb52b 100644
---
a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/surface/Sphere.java
+++
b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/surface/Sphere.java
@@ -27,6 +27,7 @@ import org.apache.sis.geometries.Geometries;
import org.apache.sis.geometries.Geometry;
import org.apache.sis.geometries.GeometryFactory;
import org.apache.sis.geometries.GeometryType;
+import org.apache.sis.geometries.Representation;
import org.apache.sis.geometries.SurfaceInterpolation;
import org.apache.sis.geometries.internal.shared.DefaultSphere;
import org.apache.sis.maths.NDRange;
@@ -72,6 +73,17 @@ public sealed interface Sphere extends ParametricCurveSurface
return GeometryType.SPHERE;
}
+ /**
+ * Returns {@link Representation#ANALYTIC}: a sphere is defined by its
center and its radius,
+ * even though it can be traversed as a parametric curve surface.
+ *
+ * @see Geometry#parametrize()
+ */
+ @Override
+ default Representation getRepresentation() {
+ return Representation.ANALYTIC;
+ }
+
/**
* Returns {@code false}: a sphere always has a center.
*/
diff --git
a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/DiscretizeTest.java
b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/DiscretizeTest.java
index 9b03630bc2..384c3ed912 100644
---
a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/DiscretizeTest.java
+++
b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/DiscretizeTest.java
@@ -16,9 +16,13 @@
*/
package org.apache.sis.geometries.operation;
+import java.util.ArrayList;
+import java.util.List;
import javax.measure.Quantity;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
+import org.apache.sis.geometries.BBox;
import org.apache.sis.geometries.DataPoints;
+import org.apache.sis.geometries.Geometries;
import org.apache.sis.geometries.Geometry;
import org.apache.sis.geometries.GeometryCollection;
import org.apache.sis.geometries.GeometryFactory;
@@ -30,7 +34,11 @@ import org.apache.sis.geometries.curve.CircularString;
import org.apache.sis.geometries.curve.LineString;
import org.apache.sis.geometries.solid.Polyhedron;
import org.apache.sis.geometries.surface.CurvePolygon;
+import org.apache.sis.geometries.surface.Cylinder;
import org.apache.sis.geometries.surface.Polygon;
+import org.apache.sis.geometries.surface.Sphere;
+import org.apache.sis.geometries.surface.TIN;
+import org.apache.sis.geometries.surface.Triangle;
import org.apache.sis.maths.DataType;
import org.apache.sis.maths.Vector;
import org.apache.sis.maths.Vectors;
@@ -53,6 +61,8 @@ public class DiscretizeTest {
private static final CoordinateReferenceSystem CRS2D =
CommonCRS.WGS84.normalizedGeographic();
+ private static final CoordinateReferenceSystem CRS3D =
Geometries.getUndefinedCRS(3);
+
private static final GeometryFactory F = GeometryFactory.DEFAULT;
/**
@@ -143,6 +153,89 @@ public class DiscretizeTest {
assertEquals(GeometryType.CURVE, lines.getElementType());
}
+ /**
+ * A sphere is parametrized, then sampled as a TIN whose vertices are on
the sphere.
+ * Without limits, the 4 × 2 knot spans are divided 8 times, less the
triangles collapsed at the poles.
+ */
+ @Test
+ public void testSphere() {
+ final Sphere sphere = F.createSphere(F.createDataPoints(CRS3D, 1, 2,
3), 2);
+ final TIN tin = assertInstanceOf(TIN.class, sphere.discretize(null,
null));
+ assertEquals(Representation.DISCRETE, tin.getRepresentation());
+ assertEquals(32 * 16 * 2 - 2 * 32, tin.getNumPatches());
+ for (final double[] p : vertices(tin)) {
+ assertEquals(2, Math.sqrt(square(p[0] - 1) + square(p[1] - 2) +
square(p[2] - 3)), 1E-12);
+ }
+ }
+
+ /**
+ * The offset limits the distance between the sphere and the middles of
the triangle edges,
+ * and the spacing limits the length of the edges.
+ */
+ @Test
+ public void testSurfaceLimits() {
+ final Sphere sphere = F.createSphere(F.createDataPoints(CRS3D, 0, 0,
0), 1);
+ final double offset = 0.001;
+ final TIN fine = assertInstanceOf(TIN.class, sphere.discretize(null,
Quantities.create(offset, Units.UNITY)));
+ for (final Triangle triangle : triangles(fine)) {
+ final DataPoints points =
triangle.getExteriorRing().getDataPoints();
+ for (int i = 0; i < 3; i++) {
+ final double[] a = points.getPosition(i).toArrayDouble();
+ final double[] b = points.getPosition(i + 1).toArrayDouble();
+ final double[] middle = {(a[0] + b[0]) / 2, (a[1] + b[1]) / 2,
(a[2] + b[2]) / 2};
+ assertTrue(1 - Math.sqrt(square(middle[0]) + square(middle[1])
+ square(middle[2])) <= offset * 1.01,
+ "Edge farther than the offset from the sphere.");
+ }
+ }
+ final TIN spaced = assertInstanceOf(TIN.class,
sphere.discretize(Quantities.create(0.2, Units.UNITY), null));
+ for (final Triangle triangle : triangles(spaced)) {
+ final DataPoints points =
triangle.getExteriorRing().getDataPoints();
+ for (int i = 0; i < 3; i++) {
+ final double[] a = points.getPosition(i).toArrayDouble();
+ final double[] b = points.getPosition(i + 1).toArrayDouble();
+ assertTrue(Math.sqrt(square(a[0] - b[0]) + square(a[1] - b[1])
+ square(a[2] - b[2])) <= 0.2,
+ "Edge longer than the spacing.");
+ }
+ }
+ }
+
+ /**
+ * A closed cylinder becomes one TIN for each of its three surfaces, and a
box becomes a polyhedron.
+ */
+ @Test
+ public void testCylinderAndBox() {
+ final Cylinder cylinder = F.createCylinder(F.createDataPoints(CRS3D,
0,0,0, 0,0,3));
+ final GeometryCollection<?> patches =
assertInstanceOf(GeometryCollection.class, cylinder.discretize(null, null));
+ assertEquals(3, patches.getNumGeometries());
+ for (final Geometry patch : patches) {
+ assertInstanceOf(TIN.class, patch);
+ }
+ assertInstanceOf(Polyhedron.class, new BBox(CRS3D, 0,0,0,
1,2,3).discretize(null, null));
+ }
+
+ private static double square(final double x) {
+ return x * x;
+ }
+
+ private static List<Triangle> triangles(final TIN tin) {
+ final List<Triangle> triangles = new ArrayList<>();
+ for (int i = 0; i < tin.getNumPatches(); i++) {
+ triangles.add(tin.getPatchN(i));
+ }
+ return triangles;
+ }
+
+ private static List<double[]> vertices(final TIN tin) {
+ final List<double[]> positions = new ArrayList<>();
+ for (final Triangle triangle : triangles(tin)) {
+ final DataPoints points =
triangle.getExteriorRing().getDataPoints();
+ for (int i = 0; i < points.size(); i++) {
+ positions.add(points.getPosition(i).toArrayDouble());
+ }
+ }
+ return positions;
+ }
+
/**
* A geometry without discrete form causes an exception.
*/
diff --git
a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/ParametrizeTest.java
b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/ParametrizeTest.java
index 740b3f3e31..da00a2ec6b 100644
---
a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/ParametrizeTest.java
+++
b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/ParametrizeTest.java
@@ -16,18 +16,30 @@
*/
package org.apache.sis.geometries.operation;
+import java.util.ArrayList;
+import java.util.List;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.apache.sis.geometries.BBox;
+import org.apache.sis.geometries.Geometries;
import org.apache.sis.geometries.Geometry;
import org.apache.sis.geometries.GeometryCollection;
import org.apache.sis.geometries.GeometryFactory;
+import org.apache.sis.geometries.OBBox;
import org.apache.sis.geometries.Prism;
import org.apache.sis.geometries.Representation;
import org.apache.sis.geometries.curve.CircularString;
import org.apache.sis.geometries.curve.LineString;
import org.apache.sis.geometries.solid.Polyhedron;
+import org.apache.sis.geometries.surface.Capsule;
+import org.apache.sis.geometries.surface.Cylinder;
+import org.apache.sis.geometries.surface.Ellipsoid;
+import org.apache.sis.geometries.surface.NurbSurface;
import org.apache.sis.geometries.surface.Polygon;
import org.apache.sis.geometries.surface.PolyhedralSurface;
+import org.apache.sis.geometries.surface.Sphere;
+import org.apache.sis.maths.DataType;
+import org.apache.sis.maths.Vector;
+import org.apache.sis.maths.Vectors;
import org.apache.sis.measure.NumberRange;
import org.apache.sis.referencing.CommonCRS;
@@ -45,8 +57,15 @@ public class ParametrizeTest {
private static final CoordinateReferenceSystem CRS2D =
CommonCRS.WGS84.normalizedGeographic();
+ private static final CoordinateReferenceSystem CRS3D =
Geometries.getUndefinedCRS(3);
+
private static final GeometryFactory F = GeometryFactory.DEFAULT;
+ /**
+ * Tolerance on positions which are exact in theory.
+ */
+ private static final double TOLERANCE = 1E-12;
+
private static final NumberRange<Double> RANGE = NumberRange.create(0.,
true, 3., true);
/**
@@ -88,12 +107,190 @@ public class ParametrizeTest {
assertSame(square, result.getGeometryN(1));
}
+ /**
+ * A sphere becomes a NURBS surface whose points are all at the radius
distance from the center,
+ * with an up-normal pointing outward.
+ */
+ @Test
+ public void testSphere() {
+ final Sphere sphere = F.createSphere(F.createDataPoints(CRS3D, 1, 2,
3), 2);
+ assertEquals(Representation.ANALYTIC, sphere.getRepresentation());
+ final NurbSurface nurbs = assertInstanceOf(NurbSurface.class,
sphere.parametrize());
+ assertEquals(Representation.PARAMETRIC, nurbs.getRepresentation());
+ for (final double[] p : samples(nurbs)) {
+ assertEquals(2, Math.sqrt(square(p[0] - 1) + square(p[1] - 2) +
square(p[2] - 3)), TOLERANCE);
+ }
+ assertOutward(nurbs, 0.1, 0.3, new double[] {1, 2, 3});
+ }
+
+ /**
+ * An ellipsoid becomes a NURBS surface whose points all satisfy the
ellipsoid equation.
+ */
+ @Test
+ public void testEllipsoid() {
+ final Ellipsoid ellipsoid =
F.createEllipsoid(F.createDataPoints(CRS3D, 8, 4, 2), 5, 1, 2);
+ assertEquals(Representation.ANALYTIC, ellipsoid.getRepresentation());
+ final NurbSurface nurbs = assertInstanceOf(NurbSurface.class,
ellipsoid.parametrize());
+ for (final double[] p : samples(nurbs)) {
+ assertEquals(1, square((p[0] - 8) / 5) + square(p[1] - 4) +
square((p[2] - 2) / 2), TOLERANCE);
+ }
+ assertOutward(nurbs, 0.6, 0.7, new double[] {8, 4, 2});
+ }
+
+ /**
+ * An open cone becomes its lateral surface, whose radius decreases
linearly from the bottom to the top.
+ */
+ @Test
+ public void testOpenCone() {
+ final Cylinder cone = F.createCylinder(F.createDataPoints(CRS3D,
0,0,0, 0,0,4));
+ cone.setClosed(false);
+ cone.setRadiusBottom(2);
+ cone.setRadiusTop(1);
+ final NurbSurface lateral = assertInstanceOf(NurbSurface.class,
cone.parametrize());
+ for (final double[] p : samples(lateral)) {
+ assertEquals(2 - p[2] / 4, Math.hypot(p[0], p[1]), TOLERANCE);
+ }
+ assertOutward(lateral, 0.3, 0.5, new double[] {0, 0, 2});
+ }
+
+ /**
+ * A closed cylinder becomes its lateral surface with a disk at each end,
all oriented outward,
+ * while a closed cone has no disk at its apex.
+ */
+ @Test
+ public void testClosedCylinder() {
+ final Cylinder cylinder = F.createCylinder(F.createDataPoints(CRS3D,
1,1,1, 1,1,4));
+ final GeometryCollection<?> patches =
assertInstanceOf(GeometryCollection.class, cylinder.parametrize());
+ assertEquals(3, patches.getNumGeometries());
+ final double[] inside = {1, 1, 2.5};
+ for (final Geometry patch : patches) {
+ assertOutward(assertInstanceOf(NurbSurface.class, patch), 0.3,
0.4, inside);
+ }
+ for (final double[] p : samples((NurbSurface)
patches.getGeometryN(0))) {
+ assertEquals(1, p[2], TOLERANCE);
+ assertTrue(Math.hypot(p[0] - 1, p[1] - 1) <= 1 + TOLERANCE);
+ }
+ cylinder.setRadiusTop(0);
+ assertEquals(2, ((GeometryCollection<?>)
cylinder.parametrize()).getNumGeometries());
+ }
+
+ /**
+ * A capsule of equal radii becomes a NURBS surface whose points are all
at the radius distance
+ * from the segment joining the two sphere centers.
+ */
+ @Test
+ public void testCapsule() {
+ final Capsule capsule = F.createCapsule(F.createDataPoints(CRS3D,
0,0,0, 0,0,3));
+ final NurbSurface nurbs = assertInstanceOf(NurbSurface.class,
capsule.parametrize());
+ for (final double[] p : samples(nurbs)) {
+ final double z = Math.clamp(p[2], 0, 3);
+ assertEquals(1, Math.sqrt(square(p[0]) + square(p[1]) +
square(p[2] - z)), TOLERANCE);
+ }
+ final double[] inside = {0, 0, 1.5};
+ for (final double v : new double[] {0.2, 0.5, 0.8}) {
+ assertOutward(nurbs, 0.3, v, inside);
+ }
+ }
+
+ /**
+ * A capsule of different radii becomes a NURBS surface whose points are
on one of the capping spheres
+ * or on the cone tangent to both, and never outside their convex hull.
+ */
+ @Test
+ public void testRoundCone() {
+ final double[] b = {0, 0, 0}, t = {2, 1, 3};
+ final double rb = 1.5, rt = 0.5;
+ final Capsule capsule = F.createCapsule(F.createDataPoints(CRS3D,
b[0], b[1], b[2], t[0], t[1], t[2]));
+ capsule.setRadiusBottom(rb);
+ capsule.setRadiusTop(rt);
+ final NurbSurface nurbs = assertInstanceOf(NurbSurface.class,
capsule.parametrize());
+ final double h = Math.sqrt(square(t[0]) + square(t[1]) + square(t[2]));
+ final double sin = (rb - rt) / h, cos = Math.sqrt(1 - sin * sin);
+ for (final double[] p : samples(nurbs)) {
+ final double z = (p[0] * t[0] + p[1] * t[1] + p[2] * t[2]) / h;
// Height along the axis.
+ final double rho = Math.sqrt(Math.max(0, square(p[0]) +
square(p[1]) + square(p[2]) - z * z));
+ final double toBottom = Math.sqrt(square(p[0]) + square(p[1]) +
square(p[2]));
+ final double toTop = Math.sqrt(square(p[0] - t[0]) + square(p[1] -
t[1]) + square(p[2] - t[2]));
+ final double cone = rho * cos + z * sin; // Equal to rb
on the tangent cone, smaller inside.
+ final double error = Math.min(Math.abs(cone - rb),
Math.min(Math.abs(toBottom - rb), Math.abs(toTop - rt)));
+ assertEquals(0, error, 1E-9, "Point on none of the capsule
parts.");
+ assertTrue(toBottom >= rb - 1E-9 && toTop >= rt - 1E-9 && cone <=
rb + 1E-9, "Point not on the convex hull.");
+ }
+ final double[] inside = {1, 0.5, 1.5};
+ for (final double v : new double[] {0.1, 0.5, 0.9}) {
+ assertOutward(nurbs, 0.7, v, inside);
+ }
+ }
+
+ /**
+ * A capsule whose bottom sphere contains the top one is the bottom sphere.
+ */
+ @Test
+ public void testCapsuleContainingSphere() {
+ final Capsule capsule = F.createCapsule(F.createDataPoints(CRS3D,
0,0,0, 0,0,1));
+ capsule.setRadiusBottom(3);
+ final NurbSurface nurbs = assertInstanceOf(NurbSurface.class,
capsule.parametrize());
+ for (final double[] p : samples(nurbs)) {
+ assertEquals(3, Math.sqrt(square(p[0]) + square(p[1]) +
square(p[2])), TOLERANCE);
+ }
+ }
+
+ /**
+ * A box becomes a polygon in 2 dimensions and a polyhedron in 3
dimensions.
+ */
+ @Test
+ public void testBoxes() {
+ assertInstanceOf(Polygon.class, new BBox(CRS2D, 0,0,
10,10).parametrize());
+ assertInstanceOf(Polyhedron.class, new BBox(CRS3D, 0,0,0,
1,2,3).parametrize());
+ final OBBox oriented = new OBBox(CRS3D);
+ oriented.setCenter(Vector.of(1, 2, 3));
+ oriented.setXAxis(Vector.of(1, 1, 0));
+ oriented.setYAxis(Vector.of(-1, 1, 0));
+ oriented.setZAxis(Vector.of(0, 0, 2));
+ assertInstanceOf(Polyhedron.class, oriented.parametrize());
+ }
+
/**
* A geometry without known exact parametric form causes an exception.
*/
@Test
public void testUnsupported() {
- final BBox box = new BBox(CRS2D, 0,0, 10,10);
- assertThrows(UnsupportedOperationException.class, box::parametrize);
+ final Vector<?> origin = Vectors.create(new double[] {0, 0},
DataType.DOUBLE);
+ final Vector<?> direction = Vectors.create(new double[] {1, 0},
DataType.DOUBLE);
+ final Geometry ray = F.createRay(CRS2D, origin, direction);
+ assertThrows(UnsupportedOperationException.class, ray::parametrize);
+ }
+
+ private static double square(final double x) {
+ return x * x;
+ }
+
+ /**
+ * Returns the positions of the given surface on a 21 × 21 grid of its
parameter domain.
+ */
+ private static List<double[]> samples(final NurbSurface surface) {
+ final List<double[]> positions = new ArrayList<>();
+ for (int i = 0; i <= 20; i++) {
+ for (int j = 0; j <= 20; j++) {
+ positions.add(surface.getSurface(i / 20.0, j /
20.0).toArrayDouble());
+ }
+ }
+ return positions;
+ }
+
+ /**
+ * Asserts that the up-normal of the surface at the given parameters
points away from the given inside position.
+ * The normal is the cross product of the partial derivatives, estimated
by finite differences.
+ */
+ private static void assertOutward(final NurbSurface surface, final double
u, final double v, final double[] inside) {
+ final double h = 1E-6;
+ final double[] p = surface.getSurface(u, v).toArrayDouble();
+ final double[] pu = surface.getSurface(u + h, v).toArrayDouble();
+ final double[] pv = surface.getSurface(u, v + h).toArrayDouble();
+ final double[] du = {pu[0] - p[0], pu[1] - p[1], pu[2] - p[2]};
+ final double[] dv = {pv[0] - p[0], pv[1] - p[1], pv[2] - p[2]};
+ final double[] n = {du[1]*dv[2] - du[2]*dv[1], du[2]*dv[0] -
du[0]*dv[2], du[0]*dv[1] - du[1]*dv[0]};
+ final double dot = n[0] * (p[0] - inside[0]) + n[1] * (p[1] -
inside[1]) + n[2] * (p[2] - inside[2]);
+ assertTrue(dot > 0, "The up-normal shall point outward.");
}
}
diff --git
a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/TessellateTest.java
b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/TessellateTest.java
index a31f3b1b45..e154d34ad9 100644
---
a/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/TessellateTest.java
+++
b/incubator/src/org.apache.sis.geometry/test/org/apache/sis/geometries/operation/TessellateTest.java
@@ -27,13 +27,18 @@ import org.apache.sis.geometries.DataPoints;
import org.apache.sis.geometries.DataPointsType;
import org.apache.sis.geometries.GeometryCollection;
import org.apache.sis.geometries.Empty;
+import org.apache.sis.geometries.Geometries;
+import org.apache.sis.geometries.OBBox;
import org.apache.sis.geometries.Prism;
import org.apache.sis.geometries.Representation;
import org.apache.sis.geometries.curve.CircularString;
import org.apache.sis.geometries.curve.LineString;
import org.apache.sis.geometries.curve.LinearRing;
+import org.apache.sis.geometries.surface.Capsule;
import org.apache.sis.geometries.surface.CurvePolygon;
import org.apache.sis.geometries.surface.Polygon;
+import org.apache.sis.geometries.surface.Sphere;
+import org.apache.sis.maths.Vector;
import org.apache.sis.geometries.solid.Polyhedron;
import org.apache.sis.geometries.solid.polyhedron.Hexahedron;
import org.apache.sis.geometries.solid.polyhedron.Icosahedron;
@@ -445,6 +450,52 @@ public class TessellateTest {
assertEquals(Math.PI * 25, trianglesArea((MeshPrimitive) result), 0.1);
}
+ /**
+ * A sphere goes through its parametric and discrete forms before becoming
triangles on the sphere.
+ */
+ @Test
+ public void testSphere() {
+ final CoordinateReferenceSystem crs = Geometries.getUndefinedCRS(3);
+ final Sphere sphere =
GeometryFactory.DEFAULT.createSphere(GeometryFactory.DEFAULT.createDataPoints(crs,
0, 0, 0), 3);
+ final MeshPrimitive mesh =
assertInstanceOf(MeshPrimitive.Triangles.class, sphere.tessellate(null, null));
+ final double[] c = mesh.getPositions().toArrayDouble();
+ assertTrue(c.length > 0);
+ for (int i = 0; i < c.length; i += 3) {
+ assertEquals(3, Math.sqrt(c[i]*c[i] + c[i+1]*c[i+1] +
c[i+2]*c[i+2]), 1E-12);
+ }
+ }
+
+ /**
+ * A capsule goes through its parametric and discrete forms before
becoming triangles
+ * at the radius distance from its axis segment.
+ */
+ @Test
+ public void testCapsule() {
+ final GeometryFactory f = GeometryFactory.DEFAULT;
+ final Capsule capsule =
f.createCapsule(f.createDataPoints(Geometries.getUndefinedCRS(3), 0,0,0,
0,0,3));
+ final MeshPrimitive mesh =
assertInstanceOf(MeshPrimitive.Triangles.class, capsule.tessellate(null, null));
+ final double[] c = mesh.getPositions().toArrayDouble();
+ assertTrue(c.length > 0);
+ for (int i = 0; i < c.length; i += 3) {
+ final double z = Math.clamp(c[i+2], 0, 3);
+ assertEquals(1, Math.sqrt(c[i]*c[i] + c[i+1]*c[i+1] + (c[i+2] -
z)*(c[i+2] - z)), 1E-12);
+ }
+ }
+
+ /**
+ * An oriented box becomes a polyhedron, then two triangles per face.
+ */
+ @Test
+ public void testOrientedBox() {
+ final OBBox box = new OBBox(Geometries.getUndefinedCRS(3));
+ box.setCenter(Vector.of(1, 2, 3));
+ box.setXAxis(Vector.of(1, 1, 0));
+ box.setYAxis(Vector.of(-1, 1, 0));
+ box.setZAxis(Vector.of(0, 0, 2));
+ final MeshPrimitive mesh =
assertInstanceOf(MeshPrimitive.Triangles.class, box.tessellate(null, null));
+ assertEquals(36, mesh.getIndex().getLength(), "Expected 2 triangles
per face.");
+ }
+
/**
* An empty geometry is returned unchanged.
*/