001/**
002 * PointString -- A collection of GeomPoint objects that make up a "string of points".
003 *
004 * Copyright (C) 2003-2025, by Joseph A. Huwaldt. All rights reserved.
005 *
006 * This library is free software; you can redistribute it and/or modify it under the terms
007 * of the GNU Lesser General Public License as published by the Free Software Foundation;
008 * either version 2.1 of the License, or (at your option) any later version.
009 *
010 * This library is distributed in the hope that it will be useful, but WITHOUT ANY
011 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
012 * PARTICULAR PURPOSE. See the GNU Library General Public License for more details.
013 *
014 * You should have received a copy of the GNU Lesser General Public License along with
015 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place -
016 * Suite 330, Boston, MA 02111-1307, USA. Or visit: http://www.gnu.org/licenses/lgpl.html
017 */
018package geomss.geom;
019
020import jahuwaldt.js.param.Parameter;
021import java.io.Serializable;
022import java.text.MessageFormat;
023import java.util.Collection;
024import java.util.Collections;
025import java.util.Comparator;
026import java.util.Iterator;
027import static java.util.Objects.requireNonNull;
028import javax.measure.converter.ConversionException;
029import javax.measure.quantity.Dimensionless;
030import javax.measure.quantity.Length;
031import javax.measure.unit.NonSI;
032import javax.measure.unit.SI;
033import javax.measure.unit.Unit;
034import javolution.context.ObjectFactory;
035import javolution.context.StackContext;
036import javolution.util.FastTable;
037import javolution.xml.XMLFormat;
038import javolution.xml.stream.XMLStreamException;
039
040/**
041 * A <code>PointString</code> is a collection of {@link GeomPoint} objects that make up a
042 * "string of points". Any number of points may be added to a string, but all points in a
043 * string must have the same dimensions.
044 * <p>
045 * WARNING: This list allows geometry to be stored in different units. If consistent units
046 * are required, then the user must specifically convert the list items.
047 * </p>
048 * <p> Modified by: Joseph A. Huwaldt </p>
049 * 
050 * @author Joseph A. Huwaldt, Date: March 5, 2003
051 * @version February 17, 2025
052 * 
053 * @param <E> The type of GeomPoint contained in this list of points.
054 */
055@SuppressWarnings({"serial", "CloneableImplementsClone"})
056public final class PointString<E extends GeomPoint> extends AbstractPointGeomList<PointString<E>,E> {
057
058    private FastTable<E> _list;
059
060    /**
061     * Return the list underlying this geometry list.
062     *
063     * @return The list underlying this geometry list.
064     */
065    @Override
066    protected FastTable<E> getList() {
067        return _list;
068    }
069
070    /**
071     * Returns a new, preallocated or recycled <code>PointString</code> instance
072     * (on the stack when executing in a <code>StackContext</code>), that can
073     * store a list of {@link GeomPoint} objects.
074     *
075     * @return A new PointString instance.
076     */
077    public static PointString newInstance() {
078        PointString list = FACTORY.object();
079        list._list = FastTable.newInstance();
080        return list;
081    }
082
083    /**
084     * Returns a new, preallocated or recycled <code>PointString</code> instance
085     * (on the stack when executing in a <code>StackContext</code>) with the
086     * specified name, that can store a list of {@link GeomPoint} objects.
087     *
088     * @param name The name to be assigned to this list (may be <code>null</code>).
089     * @return A new PointString instance with the specified name.
090     */
091    public static PointString newInstance(String name) {
092        PointString list = PointString.newInstance();
093        list.setName(name);
094        return list;
095    }
096
097    /**
098     * Return a PointString made up of the {@link GeomPoint} objects in the
099     * specified collection.
100     *
101     * @param <E> The type of GeomPoint contained in this list of points.
102     * @param name The name to be assigned to this list (may be <code>null</code>).
103     * @param elements A collection of points. May not be null.
104     * @return A new PointString instance made up of the specified points.
105     */
106    public static <E extends GeomPoint> PointString<E> valueOf(String name, Collection<E> elements) {
107        for (Object element : elements) {
108            requireNonNull(element, RESOURCES.getString("collectionElementsNullErr"));
109            if (!(element instanceof GeomPoint))
110                throw new ClassCastException(MessageFormat.format(
111                        RESOURCES.getString("listElementTypeErr"), "PointString", "GeomPoint"));
112        }
113
114        PointString<E> list = PointString.newInstance(name);
115        list.addAll(elements);
116        
117        return list;
118    }
119
120    /**
121     * Return a PointString made up of the {@link GeomPoint} objects in the specified
122     * array.
123     *
124     * @param <E>      The type of GeomPoint contained in this list of points.
125     * @param name     The name to be assigned to this list (may be <code>null</code>).
126     * @param elements An array of points. May not be null.
127     * @return A new PointString instance made up of the specified points.
128     */
129    public static <E extends GeomPoint> PointString<E> valueOf(String name, E... elements) {
130        requireNonNull(elements);
131        PointString<E> list = PointString.newInstance(name);
132        list.addAll(elements);
133
134        return list;
135    }
136
137    /**
138     * Return a PointString made up of the {@link GeomPoint} objects in the
139     * specified array.
140     *
141     * @param <E> The type of GeomPoint contained in this list of points.
142     * @param elements An array of points. May not be null.
143     * @return A new PointString instance made up of the specified points.
144     */
145    public static <E extends GeomPoint> PointString<E> valueOf(E... elements) {
146        return PointString.valueOf(null, elements);
147    }
148
149    /**
150     * Return the total number of points in this geometry element.
151     *
152     * @return The total number of points in this geometry element.
153     */
154    @Override
155    public int getNumberOfPoints() {
156        return size();
157    }
158    
159    /**
160     * Returns the range of elements in this list from the specified start and
161     * ending indexes.
162     *
163     * @param first index of the first element to return (0 returns the 1st
164     *  element, -1 returns the last, etc).
165     * @param last index of the last element to return (0 returns the 1st
166     *  element, -1 returns the last, etc).
167     * @return the list of elements in the given range from this list.
168     * @throws IndexOutOfBoundsException if the given index is out of range:
169     *  <code>index &ge; size()</code>
170     */
171    @Override
172    public PointString<E> getRange(int first, int last) {
173        first = normalizeIndex(first);
174        last = normalizeIndex(last);
175
176        PointString<E> list = PointString.newInstance();
177        for (int i=first; i <= last; ++i)
178            list.add(get(i));
179
180        return list;
181    }
182
183    /**
184     * Returns an new {@link PointString} with the elements in this list in
185     * reverse order.
186     *
187     * @return A new PointString with the elements in this string in reverse order.
188     */
189    @Override
190    public PointString<E> reverse() {
191        PointString<E> list = PointString.newInstance();
192        copyState(list);
193        int size = this.size();
194        for (int i=size-1; i >= 0; --i) {
195            list.add(get(i));
196        }
197        return list;
198    }
199
200    /**
201     * Returns a new {@link PointString} that is identical to this string but
202     * with every other point removed. The 1st point (index = 0) and last point
203     * (index = size()-1) are always retained. If there are less than 3 points
204     * in the string, then a new string is returned that contains the same
205     * points as this string.
206     *
207     * @return A new PointString identical to this one but with every other
208     *      point removed.
209     */
210    public PointString<E> thin() {
211        PointString<E> list = PointString.newInstance();
212        copyState(list);
213        
214        int size = size();
215        if (size < 3) {
216            list.addAll(this);
217            return list;
218        }
219        
220        int sizem1 = size - 1;
221        for (int i=0; i < sizem1; i += 2) {
222            list.add(get(i));
223        }
224        list.add(get(size-1));
225        
226        return list;
227    }
228    
229    /**
230     * Returns a new {@link PointString} that is identical to this string but
231     * with a new point linearly interpolated half-way between each of the
232     * existing points. If there are less than 2 points in the string, then a
233     * new string is returned that contains the same point as this string.
234     *
235     * @return A new PointString that is identical to this string but with a new
236     * point linearly interpolated half-way between each of the existing points.
237     */
238    public PointString enrich() {
239        PointString list = PointString.newInstance();
240        copyState(list);
241        
242        int size = size();
243        if (size < 2) {
244            list.add(get(0));
245            return list;
246        }
247        
248        GeomPoint p1 = get(0);
249        list.add(p1);
250        for (int i=1; i < size; ++i) {
251            GeomPoint p2 = get(i);
252            Point pa = p1.plus(p2).divide(2);   //  Calculate the average point.
253            list.add(pa);
254            list.add(p2);
255            p1 = p2;
256        }
257        
258        return list;
259    }
260    
261    /**
262     * Returns a new PointString that contains the points in this PointString with all
263     * duplicate points removed.
264     * 
265     * @param tol The tolerance for determining if the points in this PointString are approx. equal. 
266     * May not be null.
267     */
268    public PointString unique(Parameter<Length> tol) {
269        requireNonNull(tol);
270        PointString<GeomPoint> output = PointString.newInstance();
271        copyState(output);
272        output.addAll(_list);
273        for (int i = 0; i < output.size(); i++) {
274            for (int j = i + 1; j < output.size(); j++) {
275                if (output.get(i).isApproxEqual(output.get(j), tol)) {
276                    output.remove(j);
277                    --j;
278                }
279            }
280        }
281        return output;
282     }
283    
284    /**
285     * Returns the length of this PointString in terms of the sum of the distances between
286     * each consecutive point in the string.
287     *
288     * @return The length of the string: sum(point(i).distance(point(i-1))).
289     */
290    public Parameter<Length> length() {
291        StackContext.enter();
292        try {
293            int numPts = size();
294            Parameter d = Parameter.ZERO_LENGTH.to(get(0).getUnit());
295            for (int i = 1; i < numPts; ++i) {
296                Parameter<Length> dist = get(i).distance(get(i - 1));
297                if (!dist.isApproxZero())
298                    d = d.plus(dist);
299            }
300            return StackContext.outerCopy(d);
301        } finally {
302            StackContext.exit();
303        }
304    }
305
306    /**
307     * Calculate the average or centroid of all the points in this PointString.
308     *
309     * @return The average or centroid of all the points in this PointString.
310     */
311    public Point getAverage() {
312        return GeomUtil.averagePoints(this);
313    }
314    
315    /**
316     * Return <code>true</code> if this string of points is degenerate (i.e.: has length 
317     * less than the specified tolerance).
318     *
319     * @param tol The tolerance for determining if this string of points is degenerate. 
320     * May not be null.
321     * @return <code>true</code> if this string of points is degenerate
322     */
323    public boolean isDegenerate(Parameter<Length> tol) {
324        requireNonNull(tol);
325        Parameter<Length> cLength = length();
326        return cLength.compareTo(tol) <= 0;
327    }
328
329    /**
330     * Returns <code>true</code> if this string of points is a line to within the
331     * specified tolerance.
332     *
333     * @param tol The tolerance for determining if this string of points is a line.
334     * @return <code>true</code> if this string of points is a line
335     */
336    public boolean isLine(Parameter<Length> tol) {
337        //  Reference:  Piegl, L.A., Tiller, W., "Computing Offsets of NURBS Curves and Surfaces",
338        //              Computer Aided Design 31, 1999, pgs. 147-156.
339        requireNonNull(tol);
340
341        StackContext.enter();
342        try {
343            //  Extract the string end points.
344            GeomPoint p0 = get(0), p1 = get(-1);
345
346            //  If the end points are coincident, then it can't be a line.
347            Vector<Length> tv = p1.minus(p0).toGeomVector();
348            if (!tv.mag().isGreaterThan(tol))
349                return false;
350            
351            //  If there are only two non-coincident points, then it must be a line.
352            if (size() == 2)
353                return true;
354            
355            //  Get a unit vector for the potential line.
356            Vector<Dimensionless> uv = tv.toUnitVector();
357
358            //  Loop over all the points in the string.
359            Parameter c2 = tv.dot(tv);
360            int numPnts = size() - 1;
361            for (int i = 1; i < numPnts; ++i) {
362                GeomPoint pi = get(i);
363
364                //  Check distance of this point from infinite line p0-uv.
365                if (GeomUtil.pointLineDistance(pi, p0, uv).isGreaterThan(tol))
366                    return false;
367
368                //  See if the point falls in the segment p0 to p1.
369                Vector<Length> w = pi.minus(p0).toGeomVector();
370                Parameter c1 = w.dot(tv);
371                if (c1.getValue() < 0)
372                    return false;
373                if (c2.isLessThan(c1))
374                    return false;
375            }
376
377            //  Must be a straight line.
378            return true;
379
380        } finally {
381            StackContext.exit();
382        }
383    }
384
385    /**
386     * Generic/default tolerance for use in root finders, etc.
387     */
388    public static final double GTOL = 1e-6;
389
390    /**
391     * Return <code>true</code> if this string of points is planar or <code>false</code>
392     * if it is not.
393     *
394     * @param tol The geometric tolerance to use in determining if the string of points is
395     *            planar.
396     * @return <code>true</code> if this string of points is planar
397     */
398    public boolean isPlanar(Parameter<Length> tol) {
399        //  If the string is less than 3D, then it must be planar.
400        int numDims = getPhyDimension();
401        if (numDims <= 2)
402            return true;
403
404        //  If there are 3 or fewer points, then it must be planar.
405        int numPnts = size();
406        if (numPnts < 3)
407            return true;
408
409        StackContext.enter();
410        try {
411            //  Is this string of points degenerate?
412            if (isDegenerate(tol))
413                return true;
414
415            //  Is the string of points linear?
416            if (isLine(tol))
417                return true;
418
419            //  Extract 3 points from the string of points and form a plane form them.
420            GeomPoint p0 = get(0);
421            int idx1 = numPnts / 3;
422            if (idx1 == 0)
423                ++idx1;
424            int idx2 = 2 * numPnts / 3;
425            if (idx2 == idx1)
426                ++idx2;
427            GeomPoint p1 = get(idx1);
428            GeomPoint p2 = get(idx2);
429            Vector<Length> v1 = p1.minus(p0).toGeomVector();
430            Vector<Length> v2 = p2.minus(p0).toGeomVector();
431            Vector n = v1.cross(v2);
432            Vector<Dimensionless> nhat;
433            if (n.magValue() > GTOL) {
434                nhat = n.toUnitVector();
435                nhat.setOrigin(Point.newInstance(getPhyDimension()));
436
437            } else {
438                //  Try a different set of points on the string.
439                idx1 = numPnts / 4;
440                if (idx1 == 0)
441                    ++idx1;
442                idx2 = 3 * numPnts / 4;
443                if (idx2 == idx1)
444                    ++idx2;
445                p1 = get(idx1);
446                p2 = get(idx2);
447                v1 = p1.minus(p0).toGeomVector();
448                v2 = p2.minus(p0).toGeomVector();
449                n = v1.cross(v2);
450                if (n.magValue() > GTOL) {
451                    nhat = n.toUnitVector();
452                    nhat.setOrigin(Point.newInstance(getPhyDimension()));
453                } else {
454                    //  Points from input curve likely form a straight line.
455                    nhat = GeomUtil.calcYHat(p1.minus(p2).toGeomVector().toUnitVector());
456                    nhat = v2.cross(nhat).toUnitVector();
457                }
458            }
459
460            //  Loop over all the points in the point string
461            //  (except 1st, which was used to define the plane).
462            for (int i = 1; i < numPnts; ++i) {
463                GeomPoint pi = get(i);
464
465                //  Find deviation from a plane for each point by projecting a vector from p0 to pi
466                //  onto the normal for the arbitrarily chosen points on the curve.
467                //  If the projection is anything other than zero, the points are not
468                //  in the same plane.
469                Vector<Length> p1pi = pi.minus(p0).toGeomVector();
470                if (!p1pi.mag().isApproxZero()) {
471                    Parameter proj = p1pi.dot(nhat);
472                    if (proj.isLargerThan(tol))
473                        return false;
474                }
475            }
476        } finally {
477            StackContext.exit();
478        }
479
480        return true;
481    }
482  
483    /**
484     * Return a new {@link PointString} with the points in this list sorted into ascending
485     * order with respect to the specified coordinate dimension. This can also be used to
486     * remove duplicate points after the list has been sorted. To sort in descending
487     * order, use this method followed immediately by reverse() (e.g.: 
488     * <code>str.sort(Point.X,false,null).reverse();</code>).
489     *
490     * @param dim       The physical coordinate dimension to be sorted (e.g.: 0=X, 1=Y, etc).
491     * @param removeDup Duplicate points are removed from the output if this is true.
492     * @param tol       The tolerance for identifying duplicate points. If null is passed,
493     *                  then essentially exact equality is required (if removeDup is
494     *                  false, you may pass null).
495     * @return A new PointString with the points in this list sorted into ascending order
496     *         with respect to the specified coordinate dimension and possibly with
497     *         duplicate points removed.
498     */
499    public PointString<E> sort(int dim, boolean removeDup, Parameter<Length> tol) {
500        //  Create a new PointString and add the points to it.
501        PointString<E> str = PointString.newInstance();
502        str.addAll(this);
503        
504        //  Sort the new PointString
505        Collections.sort(str, new PntComparator(dim));
506        
507        //  Remove duplicates if requested.
508        if (removeDup) {
509            E old = null;
510            Iterator<E> it = str.iterator();
511            while (it.hasNext()) {
512                E p = it.next();
513                if (p.isApproxEqual(old, tol))
514                    it.remove();
515                old = p;
516            }
517        }
518        
519        return str;
520    }
521
522    /**
523     * A Comparator that compares the specified dimension of two points for order.
524     */
525    private class PntComparator implements Comparator<GeomPoint>, Serializable {
526        private final int _dim;
527
528        public PntComparator(int dim) {
529            _dim = dim;
530        }
531
532        @Override
533        public int compare(GeomPoint o1, GeomPoint o2) {
534            double v1 = o1.getValue(_dim);
535            double v2 = o2.getValue(_dim, o1.getUnit());
536            return Double.compare(v1, v2);
537        }
538    }
539
540    /**
541     *  Return the equivalent of this list converted to the specified number
542     *  of physical dimensions.  If the number of dimensions is greater than
543     *  this element, then zeros are added to the additional dimensions.
544     *  If the number of dimensions is less than this element, then
545     *  the extra dimensions are simply dropped (truncated).  If
546     *  the new dimensions are the same as the dimension of this element,
547     *  then this list is simply returned.
548     *
549     *  @param newDim  The dimension of the element to return.
550     *  @return The equivalent of this list converted to the new dimensions.
551     */
552    @Override
553    public PointString toDimension(int newDim) {
554        if (getPhyDimension() == newDim)
555            return this;
556        PointString newList = PointString.newInstance();
557        copyState(newList);
558        int size = this.size();
559        for (int i=0; i < size; ++i) {
560            E element = this.get(i);
561            newList.add(element.toDimension(newDim));
562        }
563        return newList;
564    }
565
566    /**
567     * Returns the equivalent to this list but with <I>all</I> the elements stated in the
568     * specified unit.
569     *
570     * @param unit the length unit of the list to be returned. May not be null.
571     * @return an equivalent to this list but stated in the specified unit.
572     * @throws ConversionException if the the input unit is not a length unit.
573     */
574    @Override
575    public PointString to(Unit<Length> unit) {
576        requireNonNull(unit);
577        PointString list = PointString.newInstance();
578        copyState(list);
579        int size = this.size();
580        for (int i = 0; i < size; ++i) {
581            E e = this.get(i);
582            list.add(e.to(unit));
583        }
584        return list;
585    }
586
587    /**
588     * Returns a copy of this <code>PointString</code> instance
589     * {@link javolution.context.AllocatorContext allocated} by the calling
590     * thread (possibly on the stack).
591     *
592     * @return an identical and independent copy of this object.
593     */
594    @Override
595    public PointString<E> copy() {
596        return copyOf(this);
597    }
598
599    /**
600     * Return a copy of this object with any transformations or subranges
601     * removed (applied).
602     *
603     * @return A copy of this object with any transformations or subranges
604     * removed (applied).
605     */
606    @Override
607    public PointString<E> copyToReal() {
608        PointString<E> newList = PointString.newInstance();
609        copyState(newList);
610        int size = this.size();
611        for (int i=0; i < size; ++i) {
612            E element = this.get(i);
613            newList.add((E)element.copyToReal());
614        }
615        return newList;
616    }
617    
618    /**
619     * Returns transformed version of this element. The returned object
620     * implements {@link GeomTransform} and contains transformed versions of the
621     * contents of this list as children.
622     *
623     * @param transform The transformation to apply to this geometry. May not be null.
624     * @return A new PointString that is identical to this one with the
625     *      specified transformation applied.
626     * @throws DimensionException if this element is not 3D.
627     */
628    @Override
629    public PointString getTransformed(GTransform transform) {
630        requireNonNull(transform);
631        PointString list = PointString.newInstance();
632        copyState(list);
633        int size = this.size();
634        for (int i=0; i < size; ++i) {
635            E element = this.get(i);
636            list.add(element.getTransformed(transform));
637        }
638        return list;
639    }
640
641    /**
642     * Replaces the {@link GeomPoint} at the specified position in this list with the
643     * specified element. Null elements are ignored. The input element must have the same
644     * physical dimensions as the other items in this list, or an exception is thrown.
645     *
646     * @param index   The index of the element to replace (0 returns the 1st element, -1
647     *                returns the last, -2 returns the 2nd from last, etc).
648     * @param element The element to be stored at the specified position. May not be null.
649     * @return The element previously at the specified position in this list.
650     * @throws java.lang.IndexOutOfBoundsException - if <code>index &gt; size()</code>
651     * @throws DimensionException if the input element's dimensions are different from
652     * this list's dimensions.
653     */
654    @Override
655    public E set(int index, E element) {
656        return super.set(index, requireNonNull(element));
657    }
658
659    /**
660     * Inserts the specified {@link GeomPoint} at the specified position in this list.
661     * Shifts the element currently at that position (if any) and any subsequent elements
662     * to the right (adds one to their indices). Null values are ignored. The input
663     * value must have the same physical dimensions as the other items in this list, or
664     * an exception is thrown.
665     * <p>
666     * Note: If this method is used concurrent access must be synchronized (the list is
667     * not thread-safe).
668     * </p>
669     *
670     * @param index the index at which the specified element is to be inserted. (0 returns
671     *              the 1st element, -1 returns the last, -2 returns the 2nd from last,
672     *              etc).
673     * @param value the element to be inserted. May not be null.
674     * @throws IndexOutOfBoundsException if <code>index &gt; size()</code>
675     * @throws DimensionException if the input value dimensions are different from
676     * this list's dimensions.
677     */
678    @Override
679    public void add(int index, E value) {
680        super.add(index, requireNonNull(value));
681    }
682
683    /**
684     * Inserts all of the {@link GeomPoint} objects in the specified collection into this
685     * list at the specified position. Shifts the element currently at that position (if
686     * any) and any subsequent elements to the right (increases their indices). The new
687     * elements will appear in this list in the order that they are returned by the
688     * specified collection's iterator. The behavior of this operation is unspecified if
689     * the specified collection is modified while the operation is in progress. Note that
690     * this will occur if the specified collection is this list, and it's nonempty.  The
691     * input elements must have the same physical dimensions as the other items in this
692     * list, or an exception is thrown.
693     *
694     * @param index index at which to insert first element from the specified collection.
695     * @param c     Elements to be inserted into this collection. May not be null.
696     * @return <code>true</code> if this collection changed as a result of the call
697     * @throws DimensionException if the input element's dimensions are different from
698     * this list's dimensions.
699     */
700    @Override
701    public boolean addAll(int index, Collection<? extends E> c) {
702        int thisSize = this.size();
703        for (Object element : c) {
704            requireNonNull(element, RESOURCES.getString("collectionElementsNullErr"));
705            if (!(element instanceof GeomPoint))
706                throw new ClassCastException(MessageFormat.format(
707                        RESOURCES.getString("listElementTypeErr"), "PointString", "GeomPoint"));
708            if (thisSize != 0) {
709                if (((GeomElement)element).getPhyDimension() != this.getPhyDimension())
710                    throw new DimensionException(RESOURCES.getString("dimensionErr"));
711            }
712        }
713        return super.addAll(index, c);
714    }
715
716    /**
717     * Holds the default XML representation for this object.
718     */
719    @SuppressWarnings("FieldNameHidesFieldInSuperclass")
720    protected static final XMLFormat<PointString> XML = new XMLFormat<PointString>(PointString.class) {
721
722        @Override
723        public PointString newInstance(Class<PointString> cls, XMLFormat.InputElement xml) throws XMLStreamException {
724            PointString obj = PointString.newInstance();
725            return obj;
726        }
727
728        @Override
729        public void read(XMLFormat.InputElement xml, PointString obj) throws XMLStreamException {
730            AbstractPointGeomList.XML.read(xml, obj);     // Call parent read.
731        }
732
733        @Override
734        public void write(PointString obj, XMLFormat.OutputElement xml) throws XMLStreamException {
735            AbstractPointGeomList.XML.write(obj, xml);    // Call parent write.
736        }
737    };
738
739    //////////////////////
740    // Factory Creation //
741    //////////////////////
742    private static final ObjectFactory<PointString> FACTORY = new ObjectFactory<PointString>() {
743        @Override
744        protected PointString create() {
745            return new PointString();
746        }
747        @Override
748        protected void cleanup(PointString obj) {
749            obj.reset();
750        }
751    };
752
753    /**
754     * Recycles a case instance immediately (on the stack when executing in a
755     * StackContext).
756     *
757     * @param instance The instance to be recycled immediately.
758     */
759    public static void recycle(PointString instance) {
760        FACTORY.recycle(instance);
761    }
762
763    /**
764     * Do not allow the default constructor to be used except by subclasses.
765     */
766    protected PointString() {}
767
768    private static <E2 extends GeomPoint> PointString<E2> copyOf(PointString<E2> original) {
769        PointString<E2> o = PointString.newInstance();
770        original.copyState(o);
771        int size = original.size();
772        for (int i=0; i < size; ++i) {
773            E2 element = original.get(i);
774            o.add((E2)element.copy());
775        }
776        return o;
777    }
778
779    /**
780     * Tests the methods in this class.
781     *
782     * @param args Command-line arguments (not used).
783     */
784    public static void main(String args[]) {
785        System.out.println("Testing PointString:");
786
787        Point p1 = Point.valueOf(1, 4, 6, NonSI.FOOT);
788        Point p2 = Point.valueOf(7, 2, 5, NonSI.FOOT);
789        Point p3 = Point.valueOf(10, 8, 3, NonSI.FOOT);
790        Point p4 = Point.valueOf(12, 11, 9, NonSI.FOOT);
791        PointString<Point> str1 = PointString.valueOf("A String", p1, p2, p3, p4);
792        str1.putUserData("Creator", "Joe Huwaldt");
793        str1.putUserData("Date", "June 18, 2013");
794        System.out.println("str1 = " + str1);
795        System.out.println("points = ");
796        for (GeomPoint point : str1) {
797            System.out.println(point);
798        }
799
800        Vector<Length> V = Vector.valueOf(SI.METER, 2, 0, 0);
801        PointString<?> str2 = str1.getTransformed(GTransform.newTranslation(V));
802        System.out.println("\nTranslate str1 by V = " + V);
803        System.out.println("str2 = " + str2);
804        System.out.println("points = ");
805        for (GeomPoint point : str2) {
806            System.out.println(point);
807        }
808
809        V = Vector.valueOf(NonSI.FOOT, 0,2,0);
810        PointString<?> str3 = str2.getTransformed(GTransform.newTranslation(V));
811        System.out.println("\nTranslate str2 by V = " + V);
812        System.out.println("str3 = " + str3);
813        System.out.println("points = ");
814        for (GeomPoint point : str3) {
815            System.out.println(point);
816        }
817
818        //  Write out XML data.
819        try {
820            System.out.println();
821
822            // Creates some useful aliases for class names.
823            javolution.xml.XMLBinding binding = new GeomXMLBinding();
824
825            javolution.xml.XMLObjectWriter writer = javolution.xml.XMLObjectWriter.newInstance(System.out);
826            writer.setIndentation("    ");
827            writer.setBinding(binding);
828            writer.write(str1, "PointString", PointString.class);
829            writer.flush();
830
831            System.out.println();
832        } catch (Exception e) {
833            e.printStackTrace();
834        }
835
836    }
837}
838
839