View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  package org.hipparchus.samples.geometry;
23  
24  import java.awt.BorderLayout;
25  import java.awt.Color;
26  import java.awt.Component;
27  import java.awt.geom.Point2D;
28  import java.util.ArrayList;
29  import java.util.List;
30  
31  import javax.swing.BorderFactory;
32  import javax.swing.JButton;
33  import javax.swing.JComponent;
34  import javax.swing.JPanel;
35  import javax.swing.JSplitPane;
36  
37  import org.hipparchus.geometry.enclosing.Encloser;
38  import org.hipparchus.geometry.enclosing.EnclosingBall;
39  import org.hipparchus.geometry.enclosing.WelzlEncloser;
40  import org.hipparchus.geometry.euclidean.twod.DiskGenerator;
41  import org.hipparchus.geometry.euclidean.twod.Euclidean2D;
42  import org.hipparchus.geometry.euclidean.twod.Segment;
43  import org.hipparchus.geometry.euclidean.twod.Vector2D;
44  import org.hipparchus.geometry.euclidean.twod.hull.ConvexHull2D;
45  import org.hipparchus.geometry.euclidean.twod.hull.ConvexHullGenerator2D;
46  import org.hipparchus.geometry.euclidean.twod.hull.MonotoneChain;
47  import org.hipparchus.random.MersenneTwister;
48  import org.hipparchus.random.RandomGenerator;
49  import org.hipparchus.samples.ExampleUtils;
50  import org.hipparchus.samples.ExampleUtils.ExampleFrame;
51  import org.hipparchus.util.FastMath;
52  import org.hipparchus.util.SinCos;
53  import org.piccolo2d.PCamera;
54  import org.piccolo2d.PCanvas;
55  import org.piccolo2d.PNode;
56  import org.piccolo2d.event.PBasicInputEventHandler;
57  import org.piccolo2d.event.PInputEvent;
58  import org.piccolo2d.event.PMouseWheelZoomEventHandler;
59  import org.piccolo2d.nodes.PPath;
60  import org.piccolo2d.nodes.PText;
61  
62  /**
63   * Simple example illustrating some parts of the geometry package.
64   *
65   * TODO:
66   *  - select tolerance level
67   *  - allow editing of the point set
68   */
69  //CHECKSTYLE: stop HideUtilityClassConstructor
70  public class GeometryExample {
71  
72      /** Tooltip. */
73      private static final String TOOLTIP = "tooltip";
74  
75      /** Empty constructor.
76       * <p>
77       * This constructor is not strictly necessary, but it prevents spurious
78       * javadoc warnings with JDK 18 and later.
79       * </p>
80       * @since 3.0
81       */
82      public GeometryExample() { // NOPMD - unnecessary constructor added intentionally to make javadoc happy
83          // nothing to do
84      }
85  
86      /** Create a list of random points.
87       * @param size number of points
88       * @return random points
89       */
90      public static List<Vector2D> createRandomPoints(int size) {
91          RandomGenerator random = new MersenneTwister();
92  
93          // create the cloud container
94          List<Vector2D> points = new ArrayList<>(size);
95          // fill the cloud with a random distribution of points
96          for (int i = 0; i < size; i++) {
97              points.add(new Vector2D(FastMath.round(random.nextDouble() * 400 + 100),
98                      FastMath.round(random.nextDouble() * 400 + 100)));
99          }
100 
101         return points;
102     }
103 
104     /** Create a circle sprite.
105      * @param samples number of points
106      * @return vectors describing the sprite
107      */
108     public static List<Vector2D> createCircle(int samples) {
109         List<Vector2D> points = new ArrayList<>();
110         final Vector2D center = new Vector2D(300, 300);
111         double range = 2.0 * FastMath.PI;
112         double step = range / (samples + 1);
113         for (double angle = 0; angle < range; angle += step) {
114             Vector2D circle = buildVector(angle);
115             points.add(circle.scalarMultiply(200).add(center));
116         }
117 
118         return points;
119     }
120 
121     /** Create a cross sprite.
122      * @return vectors describing the sprite
123      */
124     public static List<Vector2D> createCross() {
125         List<Vector2D> points = new ArrayList<>();
126 
127         for (int i = 100; i < 500; i += 10) {
128             points.add(new Vector2D(300, i));
129             points.add(new Vector2D(i, 300));
130         }
131 
132         return points;
133     }
134 
135     /** Create a canvas
136      * @return canvas
137      */
138     public static PCanvas createCanvas() {
139         final PCanvas canvas = new PCanvas();
140         final PCamera camera = canvas.getCamera();
141 
142         final PText tooltipNode = new PText();
143         tooltipNode.setPickable(false);
144         camera.addChild(tooltipNode);
145 
146         camera.addInputEventListener(new PBasicInputEventHandler() {
147             public void mouseMoved(final PInputEvent event) {
148                 updateToolTip(event);
149             }
150 
151             public void mouseDragged(final PInputEvent event) {
152                 updateToolTip(event);
153             }
154 
155             public void updateToolTip(final PInputEvent event) {
156                 final PNode n = event.getPickedNode();
157                 final Object object = (Object) n.getAttribute(TOOLTIP);
158                 if (object != null) {
159                     final String tooltipString = object.toString();
160                     final Point2D p = event.getCanvasPosition();
161 
162                     event.getPath().canvasToLocal(p, camera);
163 
164                     tooltipNode.setText(tooltipString);
165                     tooltipNode.setOffset(p.getX() + 8, p.getY() - 8);
166                 } else {
167                     tooltipNode.setText(null);
168                 }
169             }
170         });
171 
172         // uninstall default zoom event handler
173         canvas.removeInputEventListener(canvas.getZoomEventHandler());
174 
175         // install mouse wheel zoom event handler
176         final PMouseWheelZoomEventHandler mouseWheelZoomEventHandler = new PMouseWheelZoomEventHandler();
177         canvas.addInputEventListener(mouseWheelZoomEventHandler);
178 
179         return canvas;
180     }
181 
182     /**
183      * Build the 2D vector corresponding to the given angle.
184      * @param alpha angle
185      * @return the corresponding 2D vector
186      */
187     private static Vector2D buildVector(final double alpha) {
188         final SinCos sc = FastMath.sinCos(alpha);
189         return new Vector2D(sc.cos(), sc.sin());
190     }
191 
192     /** Main frame for geometry examples.
193      */
194     @SuppressWarnings("serial")
195     public static class Display extends ExampleFrame {
196 
197         /** Points to plot. */
198         private List<Vector2D> points;
199 
200         /** Canvas for plotting. */
201         private PCanvas canvas;
202 
203         /** Container. */
204         private JComponent container;
205 
206         /** Simple constructor.
207          */
208         public Display() {
209             setTitle("Hipparchus: Geometry Examples");
210             setSize(800, 700);
211 
212             container = new JPanel(new BorderLayout());
213             canvas = createCanvas();
214             container.add(canvas);
215             container.setBorder(BorderFactory.createLineBorder(Color.black, 1));
216 
217             JComponent controlPanel = new JPanel();
218             JButton random = new JButton("Randomize");
219             controlPanel.add(random);
220 
221             //                @Override
222             random.addActionListener(e -> {
223                                 canvas.getLayer().removeAllChildren();
224 
225                                 points = createRandomPoints(1000);
226                                 paintConvexHull();
227                             });
228 
229             JButton circle = new JButton("Circle");
230             controlPanel.add(circle);
231 
232             //                @Override
233             circle.addActionListener(e -> {
234                                 canvas.getLayer().removeAllChildren();
235 
236                                 points = createCircle(100);
237                                 paintConvexHull();
238                             });
239 
240             JButton cross = new JButton("Cross");
241             controlPanel.add(cross);
242 
243             //                @Override
244             cross.addActionListener(e -> {
245                                 canvas.getLayer().removeAllChildren();
246 
247                                 points = createCross();
248                                 paintConvexHull();
249                             });
250 
251             JSplitPane splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, container,
252                                                   controlPanel);
253             splitpane.setDividerLocation(600);
254 
255             add(splitpane);
256 
257             points = createRandomPoints(1000);
258             paintConvexHull();
259         }
260 
261         /** {@inheritDoc} */
262         @Override
263         public Component getMainPanel() {
264             return container;
265         }
266 
267         /** Paint a convex hull.
268          */
269         public void paintConvexHull() {
270             PNode pointSet = new PNode();
271             for (Vector2D point : points) {
272                 final PNode node = PPath.createEllipse(point.getX() - 1, point.getY() - 1, 2, 2);
273                 node.addAttribute(TOOLTIP, point);
274                 node.setPaint(Color.gray);
275                 pointSet.addChild(node);
276             }
277 
278             canvas.getLayer().addChild(pointSet);
279 
280             ConvexHullGenerator2D generator = new MonotoneChain(true, 1e-6);
281             ConvexHull2D hull = generator.generate(points); //AklToussaintHeuristic.reducePoints(points));
282 
283             PNode hullNode = new PNode();
284             for (Vector2D vertex : hull.getVertices()) {
285                 final PPath node = PPath.createEllipse(vertex.getX() - 1, vertex.getY() - 1, 2, 2);
286                 node.addAttribute(TOOLTIP, vertex);
287                 node.setPaint(Color.red);
288                 node.setStrokePaint(Color.red);
289                 hullNode.addChild(node);
290             }
291 
292             for (Segment line : hull.getLineSegments()) {
293                 final PPath node = PPath.createLine(line.getStart().getX(), line.getStart().getY(),
294                                                     line.getEnd().getX(), line.getEnd().getY());
295                 node.setPickable(false);
296                 node.setPaint(Color.red);
297                 node.setStrokePaint(Color.red);
298                 hullNode.addChild(node);
299             }
300 
301             canvas.getLayer().addChild(hullNode);
302 
303             Encloser<Euclidean2D, Vector2D> encloser =
304                     new WelzlEncloser<>(1e-10, new DiskGenerator());
305             EnclosingBall<Euclidean2D, Vector2D> ball = encloser.enclose(points);
306 
307             final double radius = ball.getRadius();
308             PPath ballCenter =
309                     PPath.createEllipse(ball.getCenter().getX() - 1, ball.getCenter().getY() - 1, 2, 2);
310             ballCenter.setStrokePaint(Color.blue);
311             ballCenter.setPaint(Color.blue);
312             canvas.getLayer().addChild(0, ballCenter);
313 
314             PPath ballNode =
315                     PPath.createEllipse(ball.getCenter().getX() - radius, ball.getCenter().getY() - radius,
316                                         radius * 2, radius * 2);
317             ballNode.setTransparency(1.0f);
318             ballNode.setStrokePaint(Color.blue);
319             canvas.getLayer().addChild(0, ballNode);
320         }
321     }
322 
323     /** Main entry point.
324      * @param argv program arguments (unused here)
325      */
326     public static void main(final String[] argv) {
327         ExampleUtils.showExampleFrame(new Display());
328     }
329 
330 }