1 /*
   2  * Copyright (c) 2011, 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.opengl;
  27 
  28 import java.awt.AWTException;
  29 import java.awt.BufferCapabilities;
  30 import java.awt.Color;
  31 import java.awt.Component;
  32 import java.awt.Graphics;
  33 import java.awt.Graphics2D;
  34 import java.awt.Image;
  35 import java.awt.ImageCapabilities;
  36 import java.awt.Transparency;
  37 import java.awt.color.ColorSpace;
  38 import java.awt.image.BufferedImage;
  39 import java.awt.image.ColorModel;
  40 import java.awt.image.DataBuffer;
  41 import java.awt.image.DirectColorModel;
  42 import java.awt.image.VolatileImage;
  43 import java.awt.image.WritableRaster;
  44 
  45 import sun.awt.CGraphicsConfig;
  46 import sun.awt.CGraphicsDevice;
  47 import sun.awt.image.OffScreenImage;
  48 import sun.awt.image.SunVolatileImage;
  49 import sun.awt.image.SurfaceManager;
  50 import sun.java2d.Disposer;
  51 import sun.java2d.DisposerRecord;
  52 import sun.java2d.SunGraphics2D;
  53 import sun.java2d.Surface;
  54 import sun.java2d.SurfaceData;
  55 import sun.java2d.opengl.OGLContext.OGLContextCaps;
  56 import sun.java2d.pipe.hw.AccelSurface;
  57 import sun.java2d.pipe.hw.AccelTypedVolatileImage;
  58 import sun.java2d.pipe.hw.ContextCapabilities;
  59 import static sun.java2d.opengl.OGLSurfaceData.*;
  60 import static sun.java2d.opengl.OGLContext.OGLContextCaps.*;
  61 import sun.java2d.opengl.CGLSurfaceData.CGLVSyncOffScreenSurfaceData;
  62 import sun.java2d.pipe.hw.AccelDeviceEventListener;
  63 import sun.java2d.pipe.hw.AccelDeviceEventNotifier;
  64 
  65 import sun.lwawt.macosx.CPlatformView;
  66 
  67 public class CGLGraphicsConfig extends CGraphicsConfig
  68     implements OGLGraphicsConfig
  69 {
  70     //private static final int kOpenGLSwapInterval = RuntimeOptions.getCurrentOptions().OpenGLSwapInterval;
  71     private static final int kOpenGLSwapInterval = 0; // TODO
  72     protected static boolean cglAvailable;
  73     private static ImageCapabilities imageCaps = new CGLImageCaps();
  74 
  75     private int pixfmt;
  76     private BufferCapabilities bufferCaps;
  77     private long pConfigInfo;
  78     private ContextCapabilities oglCaps;
  79     private OGLContext context;
  80     private Object disposerReferent = new Object();
  81 
  82     public static native int getDefaultPixFmt(int screennum);
  83     private static native boolean initCGL();
  84     private static native long getCGLConfigInfo(int screennum, int visualnum,
  85                                                 int swapInterval);
  86     private static native int getOGLCapabilities(long configInfo);
  87 
  88     static {
  89         cglAvailable = initCGL();
  90     }
  91 
  92     protected CGLGraphicsConfig(CGraphicsDevice device, int pixfmt,
  93                                 long configInfo, ContextCapabilities oglCaps)
  94     {
  95         super(device);
  96 
  97         this.pixfmt = pixfmt;
  98         this.pConfigInfo = configInfo;
  99         this.oglCaps = oglCaps;
 100         context = new OGLContext(OGLRenderQueue.getInstance(), this);
 101 
 102         // add a record to the Disposer so that we destroy the native
 103         // CGLGraphicsConfigInfo data when this object goes away
 104         Disposer.addRecord(disposerReferent,
 105                            new CGLGCDisposerRecord(pConfigInfo));
 106     }
 107 
 108     @Override
 109     public Object getProxyKey() {
 110         return this;
 111     }
 112 
 113     @Override
 114     public SurfaceData createManagedSurface(int w, int h, int transparency) {
 115         return CGLSurfaceData.createData(this, w, h,
 116                                          getColorModel(transparency),
 117                                          null,
 118                                          OGLSurfaceData.TEXTURE);
 119     }
 120 
 121     public static CGLGraphicsConfig getConfig(CGraphicsDevice device,
 122                                               int pixfmt)
 123     {
 124         if (!cglAvailable) {
 125             return null;
 126         }
 127 
 128         long cfginfo = 0;
 129         final String ids[] = new String[1];
 130         OGLRenderQueue rq = OGLRenderQueue.getInstance();
 131         rq.lock();
 132         try {
 133             // getCGLConfigInfo() creates and destroys temporary
 134             // surfaces/contexts, so we should first invalidate the current
 135             // Java-level context and flush the queue...
 136             OGLContext.invalidateCurrentContext();
 137 
 138             cfginfo = getCGLConfigInfo(device.getCoreGraphicsScreen(), pixfmt,
 139                                        kOpenGLSwapInterval);
 140 
 141             OGLContext.setScratchSurface(cfginfo);
 142             rq.flushAndInvokeNow(new Runnable() {
 143                 public void run() {
 144                     ids[0] = OGLContext.getOGLIdString();
 145                 }
 146             });
 147         } finally {
 148             rq.unlock();
 149         }
 150         if (cfginfo == 0) {
 151             return null;
 152         }
 153 
 154         int oglCaps = getOGLCapabilities(cfginfo);
 155         ContextCapabilities caps = new OGLContextCaps(oglCaps, ids[0]);
 156 
 157         return new CGLGraphicsConfig(device, pixfmt, cfginfo, caps);
 158     }
 159 
 160     public static boolean isCGLAvailable() {
 161         return cglAvailable;
 162     }
 163 
 164     /**
 165      * Returns true if the provided capability bit is present for this config.
 166      * See OGLContext.java for a list of supported capabilities.
 167      */
 168     public final boolean isCapPresent(int cap) {
 169         return ((oglCaps.getCaps() & cap) != 0);
 170     }
 171 
 172     public final long getNativeConfigInfo() {
 173         return pConfigInfo;
 174     }
 175 
 176     /**
 177      * {@inheritDoc}
 178      *
 179      * @see sun.java2d.pipe.hw.BufferedContextProvider#getContext
 180      */
 181     public final OGLContext getContext() {
 182         return context;
 183     }
 184 
 185     @Override
 186     public BufferedImage createCompatibleImage(int width, int height) {
 187         ColorModel model = new DirectColorModel(24, 0xff0000, 0xff00, 0xff);
 188         WritableRaster
 189             raster = model.createCompatibleWritableRaster(width, height);
 190         return new BufferedImage(model, raster, model.isAlphaPremultiplied(),
 191                                  null);
 192     }
 193 
 194     @Override
 195     public ColorModel getColorModel(int transparency) {
 196         switch (transparency) {
 197         case Transparency.OPAQUE:
 198             // REMIND: once the ColorModel spec is changed, this should be
 199             //         an opaque premultiplied DCM...
 200             return new DirectColorModel(24, 0xff0000, 0xff00, 0xff);
 201         case Transparency.BITMASK:
 202             return new DirectColorModel(25, 0xff0000, 0xff00, 0xff, 0x1000000);
 203         case Transparency.TRANSLUCENT:
 204             ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
 205             return new DirectColorModel(cs, 32,
 206                                         0xff0000, 0xff00, 0xff, 0xff000000,
 207                                         true, DataBuffer.TYPE_INT);
 208         default:
 209             return null;
 210         }
 211     }
 212 
 213     public boolean isDoubleBuffered() {
 214         return isCapPresent(CAPS_DOUBLEBUFFERED);
 215     }
 216 
 217     private static class CGLGCDisposerRecord implements DisposerRecord {
 218         private long pCfgInfo;
 219         public CGLGCDisposerRecord(long pCfgInfo) {
 220             this.pCfgInfo = pCfgInfo;
 221         }
 222         public void dispose() {
 223             if (pCfgInfo != 0) {
 224                 OGLRenderQueue.disposeGraphicsConfig(pCfgInfo);
 225                 pCfgInfo = 0;
 226             }
 227         }
 228     }
 229 
 230     // TODO: CGraphicsConfig doesn't implement displayChanged() yet
 231     //@Override
 232     public synchronized void displayChanged() {
 233         //super.displayChanged();
 234 
 235         // the context could hold a reference to a CGLSurfaceData, which in
 236         // turn has a reference back to this CGLGraphicsConfig, so in order
 237         // for this instance to be disposed we need to break the connection
 238         OGLRenderQueue rq = OGLRenderQueue.getInstance();
 239         rq.lock();
 240         try {
 241             OGLContext.invalidateCurrentContext();
 242         } finally {
 243             rq.unlock();
 244         }
 245     }
 246 
 247     @Override
 248     public String toString() {
 249         int screen = getDevice().getCoreGraphicsScreen();
 250         return ("CGLGraphicsConfig[dev="+screen+",pixfmt="+pixfmt+"]");
 251     }
 252 
 253 
 254     /**
 255      * The following methods are invoked from ComponentModel.java rather
 256      * than having the Mac OS X-dependent implementations hardcoded in that
 257      * class.  This way the appropriate actions are taken based on the peer's
 258      * GraphicsConfig, whether it is a CGraphicsConfig or a
 259      * CGLGraphicsConfig.
 260      */
 261 
 262     /**
 263      * Creates a new SurfaceData that will be associated with the given
 264      * LWWindowPeer.
 265      */
 266     @Override
 267     public SurfaceData createSurfaceData(CPlatformView pView) {
 268         return CGLSurfaceData.createData(pView);
 269     }
 270 
 271     /**
 272      * Creates a new SurfaceData that will be associated with the given
 273      * CGLLayer.
 274      */
 275     @Override
 276     public SurfaceData createSurfaceData(CGLLayer layer) {
 277         return CGLSurfaceData.createData(layer);
 278     }
 279 
 280     /**
 281      * Creates a new hidden-acceleration image of the given width and height
 282      * that is associated with the target Component.
 283      */
 284     @Override
 285     public Image createAcceleratedImage(Component target,
 286                                         int width, int height)
 287     {
 288         ColorModel model = getColorModel(Transparency.OPAQUE);
 289         WritableRaster wr =
 290             model.createCompatibleWritableRaster(width, height);
 291         return new OffScreenImage(target, model, wr,
 292                                   model.isAlphaPremultiplied());
 293     }
 294 
 295     /**
 296      * The following methods correspond to the multibuffering methods in
 297      * CWindowPeer.java...
 298      */
 299 
 300     /**
 301      * Attempts to create a OGL-based backbuffer for the given peer.  If
 302      * the requested configuration is not natively supported, an AWTException
 303      * is thrown.  Otherwise, if the backbuffer creation is successful, a
 304      * value of 1 is returned.
 305      */
 306     @Override
 307     public long createBackBuffer(CPlatformView pView,
 308                                  int numBuffers, BufferCapabilities caps)
 309         throws AWTException
 310     {
 311         if (numBuffers > 2) {
 312             throw new AWTException(
 313                 "Only double or single buffering is supported");
 314         }
 315         BufferCapabilities configCaps = getBufferCapabilities();
 316         if (!configCaps.isPageFlipping()) {
 317             throw new AWTException("Page flipping is not supported");
 318         }
 319         if (caps.getFlipContents() == BufferCapabilities.FlipContents.PRIOR) {
 320             throw new AWTException("FlipContents.PRIOR is not supported");
 321         }
 322 
 323         // non-zero return value means backbuffer creation was successful
 324         // (checked in CPlatformWindow.flip(), etc.)
 325         return 1;
 326     }
 327 
 328     /**
 329      * Destroys the backbuffer object represented by the given handle value.
 330      */
 331     @Override
 332     public void destroyBackBuffer(long backBuffer) {
 333     }
 334 
 335     /**
 336      * Creates a VolatileImage that essentially wraps the target Component's
 337      * backbuffer (the provided backbuffer handle is essentially ignored).
 338      */
 339     @Override
 340     public VolatileImage createBackBufferImage(Component target,
 341                                                long backBuffer)
 342     {
 343         return new SunVolatileImage(target,
 344                                     target.getWidth(), target.getHeight(),
 345                                     Boolean.TRUE);
 346     }
 347 
 348     /**
 349      * Performs the native OGL flip operation for the given target Component.
 350      */
 351     @Override
 352     public void flip(CPlatformView pView,
 353                      Component target, VolatileImage xBackBuffer,
 354                      int x1, int y1, int x2, int y2,
 355                      BufferCapabilities.FlipContents flipAction)
 356     {
 357         if (flipAction == BufferCapabilities.FlipContents.COPIED) {
 358             SurfaceManager vsm = SurfaceManager.getManager(xBackBuffer);
 359             SurfaceData sd = vsm.getPrimarySurfaceData();
 360 
 361             if (sd instanceof CGLVSyncOffScreenSurfaceData) {
 362                 CGLVSyncOffScreenSurfaceData vsd =
 363                     (CGLVSyncOffScreenSurfaceData)sd;
 364                 SurfaceData bbsd = vsd.getFlipSurface();
 365                 Graphics2D bbg =
 366                     new SunGraphics2D(bbsd, Color.black, Color.white, null);
 367                 try {
 368                     bbg.drawImage(xBackBuffer, 0, 0, null);
 369                 } finally {
 370                     bbg.dispose();
 371                 }
 372             } else {
 373                 pView.drawImageOnPeer(xBackBuffer, x1, y1, x2, y2);
 374                 return;
 375             }
 376         } else if (flipAction == BufferCapabilities.FlipContents.PRIOR) {
 377             // not supported by CGL...
 378             return;
 379         }
 380 
 381         OGLSurfaceData.swapBuffers(pView.getAWTView());
 382 
 383         if (flipAction == BufferCapabilities.FlipContents.BACKGROUND) {
 384             Graphics g = xBackBuffer.getGraphics();
 385             try {
 386                 g.setColor(target.getBackground());
 387                 g.fillRect(0, 0,
 388                            xBackBuffer.getWidth(),
 389                            xBackBuffer.getHeight());
 390             } finally {
 391                 g.dispose();
 392             }
 393         }
 394     }
 395 
 396     private static class CGLBufferCaps extends BufferCapabilities {
 397         public CGLBufferCaps(boolean dblBuf) {
 398             super(imageCaps, imageCaps,
 399                   dblBuf ? FlipContents.UNDEFINED : null);
 400         }
 401     }
 402 
 403     @Override
 404     public BufferCapabilities getBufferCapabilities() {
 405         if (bufferCaps == null) {
 406             bufferCaps = new CGLBufferCaps(isDoubleBuffered());
 407         }
 408         return bufferCaps;
 409     }
 410 
 411     private static class CGLImageCaps extends ImageCapabilities {
 412         private CGLImageCaps() {
 413             super(true);
 414         }
 415         public boolean isTrueVolatile() {
 416             return true;
 417         }
 418     }
 419 
 420     @Override
 421     public ImageCapabilities getImageCapabilities() {
 422         return imageCaps;
 423     }
 424 
 425     /**
 426      * {@inheritDoc}
 427      *
 428      * @see sun.java2d.pipe.hw.AccelGraphicsConfig#createCompatibleVolatileImage
 429      */
 430     public VolatileImage
 431         createCompatibleVolatileImage(int width, int height,
 432                                       int transparency, int type)
 433     {
 434         if (type == FLIP_BACKBUFFER || type == WINDOW || type == UNDEFINED ||
 435             transparency == Transparency.BITMASK)
 436         {
 437             return null;
 438         }
 439 
 440         if (type == FBOBJECT) {
 441             if (!isCapPresent(CAPS_EXT_FBOBJECT)) {
 442                 return null;
 443             }
 444         } else if (type == PBUFFER) {
 445             boolean isOpaque = transparency == Transparency.OPAQUE;
 446             if (!isOpaque && !isCapPresent(CAPS_STORED_ALPHA)) {
 447                 return null;
 448             }
 449         }
 450 
 451         SunVolatileImage vi = new AccelTypedVolatileImage(this, width, height,
 452                                                           transparency, type);
 453         Surface sd = vi.getDestSurface();
 454         if (!(sd instanceof AccelSurface) ||
 455             ((AccelSurface)sd).getType() != type)
 456         {
 457             vi.flush();
 458             vi = null;
 459         }
 460 
 461         return vi;
 462     }
 463 
 464     /**
 465      * {@inheritDoc}
 466      *
 467      * @see sun.java2d.pipe.hw.AccelGraphicsConfig#getContextCapabilities
 468      */
 469     public ContextCapabilities getContextCapabilities() {
 470         return oglCaps;
 471     }
 472 
 473     public void addDeviceEventListener(AccelDeviceEventListener l) {
 474         int screen = getDevice().getCoreGraphicsScreen();
 475         AccelDeviceEventNotifier.addListener(l, screen);
 476     }
 477 
 478     public void removeDeviceEventListener(AccelDeviceEventListener l) {
 479         AccelDeviceEventNotifier.removeListener(l);
 480     }
 481 }