1 /*
   2  * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.java2d.pipe;
  27 
  28 import java.awt.Shape;
  29 import java.awt.BasicStroke;
  30 import java.awt.geom.PathIterator;
  31 import java.awt.geom.AffineTransform;
  32 
  33 import java.security.PrivilegedAction;
  34 import java.security.AccessController;
  35 import sun.security.action.GetPropertyAction;
  36 
  37 import sun.awt.geom.PathConsumer2D;
  38 
  39 /**
  40  * This class abstracts a number of features for which the Java 2D
  41  * implementation relies on proprietary licensed software libraries.
  42  * Access to those features is now achieved by retrieving the singleton
  43  * instance of this class and calling the appropriate methods on it.
  44  * The 3 primary features abstracted here include:
  45  * <dl>
  46  * <dt>Shape createStrokedShape(Shape, [BasicStroke attributes]);
  47  * <dd>This method implements the functionality of the method of the
  48  * same name on the {@link BasicStroke} class.
  49  * <dt>void strokeTo(Shape, [rendering parameters], PathConsumer2D);
  50  * <dd>This method performs widening of the source path on the fly
  51  * and sends the results to the given {@link PathConsumer2D} object.
  52  * This procedure avoids having to create an intermediate Shape
  53  * object to hold the results of the {@code createStrokedShape} method.
  54  * The main user of this method is the Java 2D non-antialiasing renderer.
  55  * <dt>AATileGenerator getAATileGenerator(Shape, [rendering parameters]);
  56  * <dd>This method returns an object which can iterate over the
  57  * specified bounding box and produce tiles of coverage values for
  58  * antialiased rendering.  The details of the operation of the
  59  * {@link AATileGenerator} object are explained in its class comments.
  60  * </dl>
  61  * Additionally, the following informational method supplies important
  62  * data about the implementation.
  63  * <dl>
  64  * <dt>float getMinimumAAPenSize()
  65  * <dd>This method provides information on how small the BasicStroke
  66  * line width can get before dropouts occur.  Rendering with a BasicStroke
  67  * is defined to never allow the line to have breaks, gaps, or dropouts
  68  * even if the width is set to 0.0f, so this information allows the
  69  * {@link SunGraphics2D} class to detect the "thin line" case and set
  70  * the rendering attributes accordingly.
  71  * </dl>
  72  * At startup the runtime will load a single instance of this class.
  73  * It searches the classpath for a registered provider of this API
  74  * and returns either the last one it finds, or the instance whose
  75  * class name matches the value supplied in the System property
  76  * {@code sun.java2d.renderer}.
  77  * Additionally, a runtime System property flag can be set to trace
  78  * all calls to methods on the {@code RenderingEngine} in use by
  79  * setting the sun.java2d.renderer.trace property to any non-null value.
  80  * <p>
  81  * Parts of the system that need to use any of the above features should
  82  * call {@code RenderingEngine.getInstance()} to obtain the properly
  83  * registered (and possibly trace-enabled) version of the RenderingEngine.
  84  */
  85 public abstract class RenderingEngine {
  86     private static RenderingEngine reImpl;
  87 
  88     /**
  89      * Returns an instance of {@code RenderingEngine} as determined
  90      * by the installation environment and runtime flags.
  91      * <p>
  92      * A specific instance of the {@code RenderingEngine} can be
  93      * chosen by specifying the runtime flag:
  94      * <pre>
  95      *     java -Dsun.java2d.renderer=&lt;classname&gt;
  96      * </pre>
  97      *
  98      * If no specific {@code RenderingEngine} is specified on the command
  99      * or Ductus renderer is specified, it will first attempt loading the
 100      * sun.dc.DuctusRenderingEngine class using Class.forName, if that
 101      * is not found, then it will look for Pisces.
 102      * <p>
 103      * Runtime tracing of the actions of the {@code RenderingEngine}
 104      * can be enabled by specifying the runtime flag:
 105      * <pre>
 106      *     java -Dsun.java2d.renderer.trace=&lt;any string&gt;
 107      * </pre>
 108      * @return an instance of {@code RenderingEngine}
 109      * @since 1.7
 110      */
 111     public static synchronized RenderingEngine getInstance() {
 112         if (reImpl != null) {
 113             return reImpl;
 114         }
 115 
 116         /* Look first for ductus or an app-override renderer,
 117          * if not specified or present, then look for pisces.
 118          */
 119         final String ductusREClass = "sun.dc.DuctusRenderingEngine";
 120         final String piscesREClass = "sun.java2d.pisces.PiscesRenderingEngine";
 121         GetPropertyAction gpa =
 122             new GetPropertyAction("sun.java2d.renderer", ductusREClass);
 123         String reClass = AccessController.doPrivileged(gpa);
 124         try {
 125             Class<?> cls = Class.forName(reClass);
 126             reImpl = (RenderingEngine) cls.newInstance();
 127         } catch (ReflectiveOperationException ignored0) {
 128             try {
 129                 Class<?> cls = Class.forName(piscesREClass);
 130                 reImpl = (RenderingEngine) cls.newInstance();
 131             } catch (ReflectiveOperationException ignored1) {
 132             }
 133         }
 134 
 135         if (reImpl == null) {
 136             throw new InternalError("No RenderingEngine module found");
 137         }
 138 
 139         gpa = new GetPropertyAction("sun.java2d.renderer.trace");
 140         String reTrace = AccessController.doPrivileged(gpa);
 141         if (reTrace != null) {
 142             reImpl = new Tracer(reImpl);
 143         }
 144 
 145         return reImpl;
 146     }
 147 
 148     /**
 149      * Create a widened path as specified by the parameters.
 150      * <p>
 151      * The specified {@code src} {@link Shape} is widened according
 152      * to the specified attribute parameters as per the
 153      * {@link BasicStroke} specification.
 154      *
 155      * @param src the source path to be widened
 156      * @param width the width of the widened path as per {@code BasicStroke}
 157      * @param caps the end cap decorations as per {@code BasicStroke}
 158      * @param join the segment join decorations as per {@code BasicStroke}
 159      * @param miterlimit the miter limit as per {@code BasicStroke}
 160      * @param dashes the dash length array as per {@code BasicStroke}
 161      * @param dashphase the initial dash phase as per {@code BasicStroke}
 162      * @return the widened path stored in a new {@code Shape} object
 163      * @since 1.7
 164      */
 165     public abstract Shape createStrokedShape(Shape src,
 166                                              float width,
 167                                              int caps,
 168                                              int join,
 169                                              float miterlimit,
 170                                              float dashes[],
 171                                              float dashphase);
 172 
 173     /**
 174      * Sends the geometry for a widened path as specified by the parameters
 175      * to the specified consumer.
 176      * <p>
 177      * The specified {@code src} {@link Shape} is widened according
 178      * to the parameters specified by the {@link BasicStroke} object.
 179      * Adjustments are made to the path as appropriate for the
 180      * {@link VALUE_STROKE_NORMALIZE} hint if the {@code normalize}
 181      * boolean parameter is true.
 182      * Adjustments are made to the path as appropriate for the
 183      * {@link VALUE_ANTIALIAS_ON} hint if the {@code antialias}
 184      * boolean parameter is true.
 185      * <p>
 186      * The geometry of the widened path is forwarded to the indicated
 187      * {@link PathConsumer2D} object as it is calculated.
 188      *
 189      * @param src the source path to be widened
 190      * @param bs the {@code BasicSroke} object specifying the
 191      *           decorations to be applied to the widened path
 192      * @param normalize indicates whether stroke normalization should
 193      *                  be applied
 194      * @param antialias indicates whether or not adjustments appropriate
 195      *                  to antialiased rendering should be applied
 196      * @param consumer the {@code PathConsumer2D} instance to forward
 197      *                 the widened geometry to
 198      * @since 1.7
 199      */
 200     public abstract void strokeTo(Shape src,
 201                                   AffineTransform at,
 202                                   BasicStroke bs,
 203                                   boolean thin,
 204                                   boolean normalize,
 205                                   boolean antialias,
 206                                   PathConsumer2D consumer);
 207 
 208     /**
 209      * Construct an antialiased tile generator for the given shape with
 210      * the given rendering attributes and store the bounds of the tile
 211      * iteration in the bbox parameter.
 212      * The {@code at} parameter specifies a transform that should affect
 213      * both the shape and the {@code BasicStroke} attributes.
 214      * The {@code clip} parameter specifies the current clip in effect
 215      * in device coordinates and can be used to prune the data for the
 216      * operation, but the renderer is not required to perform any
 217      * clipping.
 218      * If the {@code BasicStroke} parameter is null then the shape
 219      * should be filled as is, otherwise the attributes of the
 220      * {@code BasicStroke} should be used to specify a draw operation.
 221      * The {@code thin} parameter indicates whether or not the
 222      * transformed {@code BasicStroke} represents coordinates smaller
 223      * than the minimum resolution of the antialiasing rasterizer as
 224      * specified by the {@code getMinimumAAPenWidth()} method.
 225      * <p>
 226      * Upon returning, this method will fill the {@code bbox} parameter
 227      * with 4 values indicating the bounds of the iteration of the
 228      * tile generator.
 229      * The iteration order of the tiles will be as specified by the
 230      * pseudo-code:
 231      * <pre>
 232      *     for (y = bbox[1]; y < bbox[3]; y += tileheight) {
 233      *         for (x = bbox[0]; x < bbox[2]; x += tilewidth) {
 234      *         }
 235      *     }
 236      * </pre>
 237      * If there is no output to be rendered, this method may return
 238      * null.
 239      *
 240      * @param s the shape to be rendered (fill or draw)
 241      * @param at the transform to be applied to the shape and the
 242      *           stroke attributes
 243      * @param clip the current clip in effect in device coordinates
 244      * @param bs if non-null, a {@code BasicStroke} whose attributes
 245      *           should be applied to this operation
 246      * @param thin true if the transformed stroke attributes are smaller
 247      *             than the minimum dropout pen width
 248      * @param normalize true if the {@code VALUE_STROKE_NORMALIZE}
 249      *                  {@code RenderingHint} is in effect
 250      * @param bbox returns the bounds of the iteration
 251      * @return the {@code AATileGenerator} instance to be consulted
 252      *         for tile coverages, or null if there is no output to render
 253      * @since 1.7
 254      */
 255     public abstract AATileGenerator getAATileGenerator(Shape s,
 256                                                        AffineTransform at,
 257                                                        Region clip,
 258                                                        BasicStroke bs,
 259                                                        boolean thin,
 260                                                        boolean normalize,
 261                                                        int bbox[]);
 262 
 263     /**
 264      * Construct an antialiased tile generator for the given parallelogram
 265      * store the bounds of the tile iteration in the bbox parameter.
 266      * The parallelogram is specified as a starting point and 2 delta
 267      * vectors that indicate the slopes of the 2 pairs of sides of the
 268      * parallelogram.
 269      * The 4 corners of the parallelogram are defined by the 4 points:
 270      * <ul>
 271      * <li> {@code x}, {@code y}
 272      * <li> {@code x+dx1}, {@code y+dy1}
 273      * <li> {@code x+dx1+dx2}, {@code y+dy1+dy2}
 274      * <li> {@code x+dx2}, {@code y+dy2}
 275      * </ul>
 276      * The {@code lw1} and {@code lw2} parameters provide a specification
 277      * for an optionally stroked parallelogram if they are positive numbers.
 278      * The {@code lw1} parameter is the ratio of the length of the {@code dx1},
 279      * {@code dx2} delta vector to half of the line width in that same
 280      * direction.
 281      * The {@code lw2} parameter provides the same ratio for the other delta
 282      * vector.
 283      * If {@code lw1} and {@code lw2} are both greater than zero, then
 284      * the parallelogram figure is doubled by both expanding and contracting
 285      * each delta vector by its corresponding {@code lw} value.
 286      * If either (@code lw1) or {@code lw2} are also greater than 1, then
 287      * the inner (contracted) parallelogram disappears and the figure is
 288      * simply a single expanded parallelogram.
 289      * The {@code clip} parameter specifies the current clip in effect
 290      * in device coordinates and can be used to prune the data for the
 291      * operation, but the renderer is not required to perform any
 292      * clipping.
 293      * <p>
 294      * Upon returning, this method will fill the {@code bbox} parameter
 295      * with 4 values indicating the bounds of the iteration of the
 296      * tile generator.
 297      * The iteration order of the tiles will be as specified by the
 298      * pseudo-code:
 299      * <pre>
 300      *     for (y = bbox[1]; y < bbox[3]; y += tileheight) {
 301      *         for (x = bbox[0]; x < bbox[2]; x += tilewidth) {
 302      *         }
 303      *     }
 304      * </pre>
 305      * If there is no output to be rendered, this method may return
 306      * null.
 307      *
 308      * @param x the X coordinate of the first corner of the parallelogram
 309      * @param y the Y coordinate of the first corner of the parallelogram
 310      * @param dx1 the X coordinate delta of the first leg of the parallelogram
 311      * @param dy1 the Y coordinate delta of the first leg of the parallelogram
 312      * @param dx2 the X coordinate delta of the second leg of the parallelogram
 313      * @param dy2 the Y coordinate delta of the second leg of the parallelogram
 314      * @param lw1 the line width ratio for the first leg of the parallelogram
 315      * @param lw2 the line width ratio for the second leg of the parallelogram
 316      * @param clip the current clip in effect in device coordinates
 317      * @param bbox returns the bounds of the iteration
 318      * @return the {@code AATileGenerator} instance to be consulted
 319      *         for tile coverages, or null if there is no output to render
 320      * @since 1.7
 321      */
 322     public abstract AATileGenerator getAATileGenerator(double x, double y,
 323                                                        double dx1, double dy1,
 324                                                        double dx2, double dy2,
 325                                                        double lw1, double lw2,
 326                                                        Region clip,
 327                                                        int bbox[]);
 328 
 329     /**
 330      * Returns the minimum pen width that the antialiasing rasterizer
 331      * can represent without dropouts occurring.
 332      * @since 1.7
 333      */
 334     public abstract float getMinimumAAPenSize();
 335 
 336     /**
 337      * Utility method to feed a {@link PathConsumer2D} object from a
 338      * given {@link PathIterator}.
 339      * This method deals with the details of running the iterator and
 340      * feeding the consumer a segment at a time.
 341      */
 342     public static void feedConsumer(PathIterator pi, PathConsumer2D consumer) {
 343         float coords[] = new float[6];
 344         while (!pi.isDone()) {
 345             switch (pi.currentSegment(coords)) {
 346             case PathIterator.SEG_MOVETO:
 347                 consumer.moveTo(coords[0], coords[1]);
 348                 break;
 349             case PathIterator.SEG_LINETO:
 350                 consumer.lineTo(coords[0], coords[1]);
 351                 break;
 352             case PathIterator.SEG_QUADTO:
 353                 consumer.quadTo(coords[0], coords[1],
 354                                 coords[2], coords[3]);
 355                 break;
 356             case PathIterator.SEG_CUBICTO:
 357                 consumer.curveTo(coords[0], coords[1],
 358                                  coords[2], coords[3],
 359                                  coords[4], coords[5]);
 360                 break;
 361             case PathIterator.SEG_CLOSE:
 362                 consumer.closePath();
 363                 break;
 364             }
 365             pi.next();
 366         }
 367     }
 368 
 369     static class Tracer extends RenderingEngine {
 370         RenderingEngine target;
 371         String name;
 372 
 373         public Tracer(RenderingEngine target) {
 374             this.target = target;
 375             name = target.getClass().getName();
 376         }
 377 
 378         public Shape createStrokedShape(Shape src,
 379                                         float width,
 380                                         int caps,
 381                                         int join,
 382                                         float miterlimit,
 383                                         float dashes[],
 384                                         float dashphase)
 385         {
 386             System.out.println(name+".createStrokedShape("+
 387                                src.getClass().getName()+", "+
 388                                "width = "+width+", "+
 389                                "caps = "+caps+", "+
 390                                "join = "+join+", "+
 391                                "miter = "+miterlimit+", "+
 392                                "dashes = "+dashes+", "+
 393                                "dashphase = "+dashphase+")");
 394             return target.createStrokedShape(src,
 395                                              width, caps, join, miterlimit,
 396                                              dashes, dashphase);
 397         }
 398 
 399         public void strokeTo(Shape src,
 400                              AffineTransform at,
 401                              BasicStroke bs,
 402                              boolean thin,
 403                              boolean normalize,
 404                              boolean antialias,
 405                              PathConsumer2D consumer)
 406         {
 407             System.out.println(name+".strokeTo("+
 408                                src.getClass().getName()+", "+
 409                                at+", "+
 410                                bs+", "+
 411                                (thin ? "thin" : "wide")+", "+
 412                                (normalize ? "normalized" : "pure")+", "+
 413                                (antialias ? "AA" : "non-AA")+", "+
 414                                consumer.getClass().getName()+")");
 415             target.strokeTo(src, at, bs, thin, normalize, antialias, consumer);
 416         }
 417 
 418         public float getMinimumAAPenSize() {
 419             System.out.println(name+".getMinimumAAPenSize()");
 420             return target.getMinimumAAPenSize();
 421         }
 422 
 423         public AATileGenerator getAATileGenerator(Shape s,
 424                                                   AffineTransform at,
 425                                                   Region clip,
 426                                                   BasicStroke bs,
 427                                                   boolean thin,
 428                                                   boolean normalize,
 429                                                   int bbox[])
 430         {
 431             System.out.println(name+".getAATileGenerator("+
 432                                s.getClass().getName()+", "+
 433                                at+", "+
 434                                clip+", "+
 435                                bs+", "+
 436                                (thin ? "thin" : "wide")+", "+
 437                                (normalize ? "normalized" : "pure")+")");
 438             return target.getAATileGenerator(s, at, clip,
 439                                              bs, thin, normalize,
 440                                              bbox);
 441         }
 442         public AATileGenerator getAATileGenerator(double x, double y,
 443                                                   double dx1, double dy1,
 444                                                   double dx2, double dy2,
 445                                                   double lw1, double lw2,
 446                                                   Region clip,
 447                                                   int bbox[])
 448         {
 449             System.out.println(name+".getAATileGenerator("+
 450                                x+", "+y+", "+
 451                                dx1+", "+dy1+", "+
 452                                dx2+", "+dy2+", "+
 453                                lw1+", "+lw2+", "+
 454                                clip+")");
 455             return target.getAATileGenerator(x, y,
 456                                              dx1, dy1,
 457                                              dx2, dy2,
 458                                              lw1, lw2,
 459                                              clip, bbox);
 460         }
 461     }
 462 }