aboutsummaryrefslogtreecommitdiffstats
3' href='#n3'>3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
/*
 * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 * - Redistribution of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
 * MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
 * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
 * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
 * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that this software is not designed or intended for use
 * in the design, construction, operation or maintenance of any nuclear
 * facility.
 * 
 * Sun gratefully acknowledges that this software was originally authored
 * and developed by Kenneth Bradley Russell and Christopher John Kline.
 */

package net.java.games.jogl.impl.windows;

import net.java.games.jogl.*;
import net.java.games.jogl.impl.*;

public class WindowsPbufferGLContext extends WindowsGLContext {
  private static final boolean DEBUG = false;

  private int  initWidth;
  private int  initHeight;

  private long buffer; // pbuffer handle
  private int  width;
  private int  height;

  // FIXME: kept around because we create the OpenGL context lazily to
  // better integrate with the WindowsGLContext framework
  private long parentHglrc;

  private static final int MAX_PFORMATS = 256;
  private static final int MAX_ATTRIBS  = 256;

  // State for render-to-texture and render-to-texture-rectangle support
  private boolean created;
  private boolean rtt;       // render-to-texture?
  private boolean hasRTT;    // render-to-texture extension available?
  private boolean rect;      // render-to-texture-rectangle?
  private int textureTarget; // e.g. GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE_NV
  private int texture;       // actual texture object

  public WindowsPbufferGLContext(GLCapabilities capabilities, int initialWidth, int initialHeight) {
    super(null, capabilities, null, null);
    this.initWidth  = initialWidth;
    this.initHeight = initialHeight;
    if (initWidth <= 0 || initHeight <= 0) {
      throw new GLException("Initial width and height of pbuffer must be positive (were (" +
			    initWidth + ", " + initHeight + "))");
    }
  }

  public boolean canCreatePbufferContext() {
    return false;
  }

  public GLContext createPbufferContext(GLCapabilities capabilities,
                                        int initialWidth,
                                        int initialHeight) {
    throw new GLException("Not supported");
  }

  public void bindPbufferToTexture() {
    if (!rtt) {
      throw new GLException("Shouldn't try to bind a pbuffer to a texture if render-to-texture hasn't been " +
                            "specified in its GLCapabilities");
    }
    GL gl = getGL();
    gl.glBindTexture(textureTarget, texture);
    if (rtt && hasRTT) {
      if (!gl.wglBindTexImageARB(buffer, GL.WGL_FRONT_LEFT_ARB)) {
        throw new GLException("Binding of pbuffer to texture failed: " + wglGetLastError());
      }
    }
    // Note that if the render-to-texture extension is not supported,
    // we perform a glCopyTexImage2D in swapBuffers().
  }

  public void releasePbufferFromTexture() {
    if (!rtt) {
      throw new GLException("Shouldn't try to bind a pbuffer to a texture if render-to-texture hasn't been " +
                            "specified in its GLCapabilities");
    }
    if (rtt && hasRTT) {
      GL gl = getGL();
      if (!gl.wglReleaseTexImageARB(buffer, GL.WGL_FRONT_LEFT_ARB)) {
        throw new GLException("Releasing of pbuffer from texture failed: " + wglGetLastError());
      }
    }
  }

  public void createPbuffer(long parentHdc, long parentHglrc) {
    GL gl = getGL();
    // Must initally grab OpenGL function pointers while parent's
    // context is current because otherwise we don't have the wgl
    // extensions available to us
    resetGLFunctionAvailability();
    
    int[]   iattributes = new int  [2*MAX_ATTRIBS];
    float[] fattributes = new float[2*MAX_ATTRIBS];
    int nfattribs = 0;
    int niattribs = 0;

    rtt              = capabilities.getOffscreenRenderToTexture();
    rect             = capabilities.getOffscreenRenderToTextureRectangle();
    boolean useFloat = capabilities.getOffscreenFloatingPointBuffers();
    
    // Since we are trying to create a pbuffer, the pixel format we
    // request (and subsequently use) must be "p-buffer capable".
    iattributes[niattribs++] = GL.WGL_DRAW_TO_PBUFFER_ARB;
    iattributes[niattribs++] = GL.GL_TRUE;

    if (!rtt) {
      // Currently we don't support non-truecolor visuals in the
      // GLCapabilities, so we don't offer the option of making
      // color-index pbuffers.
      iattributes[niattribs++] = GL.WGL_PIXEL_TYPE_ARB;
      iattributes[niattribs++] = GL.WGL_TYPE_RGBA_ARB;
    }

    iattributes[niattribs++] = GL.WGL_DOUBLE_BUFFER_ARB;
    if (capabilities.getDoubleBuffered()) {
      iattributes[niattribs++] = GL.GL_TRUE;
    } else {
      iattributes[niattribs++] = GL.GL_FALSE;
    }

    iattributes[niattribs++] = GL.WGL_DEPTH_BITS_ARB;
    iattributes[niattribs++] = capabilities.getDepthBits();

    iattributes[niattribs++] = GL.WGL_RED_BITS_ARB;
    iattributes[niattribs++] = capabilities.getRedBits();

    iattributes[niattribs++] = GL.WGL_GREEN_BITS_ARB;
    iattributes[niattribs++] = capabilities.getGreenBits();

    iattributes[niattribs++] = GL.WGL_BLUE_BITS_ARB;
    iattributes[niattribs++] = capabilities.getBlueBits();

    iattributes[niattribs++] = GL.WGL_ALPHA_BITS_ARB;
    iattributes[niattribs++] = capabilities.getAlphaBits();

    iattributes[niattribs++] = GL.WGL_STENCIL_BITS_ARB;
    if (capabilities.getStencilBits() > 0) {
      iattributes[niattribs++] = GL.GL_TRUE;
    } else {
      iattributes[niattribs++] = GL.GL_FALSE;
    }

    if (capabilities.getAccumRedBits()   > 0 ||
        capabilities.getAccumGreenBits() > 0 ||
        capabilities.getAccumBlueBits()  > 0) {
      iattributes[niattribs++] = GL.WGL_ACCUM_BITS_ARB;
      iattributes[niattribs++] = GL.GL_TRUE;
    }

    // FIXME: using NVidia-specific extensions and enums, as well as
    // confusing render-to-texture with render-to-texture-rectangle
    if (useFloat) {
      iattributes[niattribs++] = GL.WGL_FLOAT_COMPONENTS_NV;
      iattributes[niattribs++] = GL.GL_TRUE;
    }

    if (rtt) {
      if (useFloat) {
        iattributes[niattribs++] = GL.WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV;
        iattributes[niattribs++] = GL.GL_TRUE;
      } else {
        iattributes[niattribs++] = rect ? GL.WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV : GL.WGL_BIND_TO_TEXTURE_RGB_ARB;
        iattributes[niattribs++] = GL.GL_TRUE;
      }
    }

    iattributes[niattribs++] = GL.WGL_SUPPORT_OPENGL_ARB;
    iattributes[niattribs++] = GL.GL_TRUE;
    
    int[] pformats = new int[MAX_PFORMATS];
    int   nformats;
    int[] nformatsTmp = new int[1];
    if (!gl.wglChoosePixelFormatARB(parentHdc,
                                    iattributes,
                                    fattributes,
                                    MAX_PFORMATS,
                                    pformats, 
                                    nformatsTmp)) {
      throw new GLException("pbuffer creation error: wglChoosePixelFormatARB() failed");
    }
    nformats = nformatsTmp[0];
    if (nformats <= 0) {
      throw new GLException("pbuffer creation error: Couldn't find a suitable pixel format");
    }

    if (DEBUG) {
      System.err.println("" + nformats + " suitable pixel formats found");
      // query pixel format
      iattributes[0] = GL.WGL_RED_BITS_ARB;
      iattributes[1] = GL.WGL_GREEN_BITS_ARB;
      iattributes[2] = GL.WGL_BLUE_BITS_ARB;
      iattributes[3] = GL.WGL_ALPHA_BITS_ARB;
      iattributes[4] = GL.WGL_DEPTH_BITS_ARB;
      iattributes[5] = GL.WGL_FLOAT_COMPONENTS_NV;
      iattributes[6] = GL.WGL_SAMPLE_BUFFERS_EXT;
      iattributes[7] = GL.WGL_SAMPLES_EXT;
      int[] ivalues = new int[8];
      for (int i = 0; i < nformats; i++) {
        if (!gl.wglGetPixelFormatAttribivARB(parentHdc, pformats[i], 0, 8, iattributes, ivalues)) {
          throw new GLException("Error while querying pixel format " + pformats[i] +
                                "'s (index " + i + "'s) capabilities for debugging");
        }
        System.err.print("pixel format " + pformats[i] + " (index " + i + "): ");
        System.err.print( "r: " + ivalues[0]);
        System.err.print(" g: " + ivalues[1]);
        System.err.print(" b: " + ivalues[2]);
        System.err.print(" a: " + ivalues[3]);
        System.err.print(" depth: " + ivalues[4]);
        System.err.print(" multisample: " + ivalues[6]);
        System.err.print(" samples: " + ivalues[7]);
        if (ivalues[5] != 0) {
          System.err.print(" [float]");
        }
        System.err.println();
      }
    }

    int format = pformats[0];

    // Create the p-buffer.
    niattribs = 0;

    if (rtt) {
      iattributes[niattribs++]   = GL.WGL_TEXTURE_FORMAT_ARB;
      if (useFloat) {
        iattributes[niattribs++] = GL.WGL_TEXTURE_FLOAT_RGB_NV;
      } else {
        iattributes[niattribs++] = GL.WGL_TEXTURE_RGBA_ARB;
      }

      iattributes[niattribs++] = GL.WGL_TEXTURE_TARGET_ARB;
      iattributes[niattribs++] = rect ? GL.WGL_TEXTURE_RECTANGLE_NV : GL.WGL_TEXTURE_2D_ARB;

      iattributes[niattribs++] = GL.WGL_MIPMAP_TEXTURE_ARB;
      iattributes[niattribs++] = GL.GL_FALSE;

      iattributes[niattribs++] = GL.WGL_PBUFFER_LARGEST_ARB;
      iattributes[niattribs++] = GL.GL_FALSE;
    }

    iattributes[niattribs++] = 0;

    long tmpBuffer = gl.wglCreatePbufferARB(parentHdc, format, initWidth, initHeight, iattributes);
    if (tmpBuffer == 0) {
      throw new GLException("pbuffer creation error: wglCreatePbufferARB() failed: " + wglGetLastError());
    }

    // Get the device context.
    long tmpHdc = gl.wglGetPbufferDCARB(tmpBuffer);
    if (tmpHdc == 0) {
      throw new GLException("pbuffer creation error: wglGetPbufferDCARB() failed");
    }

    this.parentHglrc = parentHglrc;

    // Set up instance variables
    buffer = tmpBuffer;
    hdc    = tmpHdc;

    // Determine the actual width and height we were able to create.
    int[] tmp = new int[1];
    gl.wglQueryPbufferARB( buffer, GL.WGL_PBUFFER_WIDTH_ARB,  tmp );
    width = tmp[0];
    gl.wglQueryPbufferARB( buffer, GL.WGL_PBUFFER_HEIGHT_ARB, tmp );
    height = tmp[0];

    if (DEBUG) {
      System.err.println("Created pbuffer " + width + " x " + height);
    }
  }

  protected synchronized boolean makeCurrent(Runnable initAction) throws GLException {
    created = false;

    if (buffer == 0) {
      // pbuffer not instantiated yet
      return false;
    }

    boolean res = super.makeCurrent(initAction);
    if (created) {
      // Initialize render-to-texture support if requested
      rtt  = capabilities.getOffscreenRenderToTexture();
      rect = capabilities.getOffscreenRenderToTextureRectangle();

      if (rtt) {
        if (DEBUG) {
          System.err.println("Initializing render-to-texture support");
        }

        if (!gl.isExtensionAvailable("WGL_ARB_render_texture")) {
          System.err.println("WindowsPbufferGLContext: WARNING: WGL_ARB_render_texture extension not " +
                             "supported; implementing render_to_texture support using slow texture readback");
        } else {
          hasRTT = true;
          GL gl = getGL();

          if (rect && !gl.isExtensionAvailable("GL_NV_texture_rectangle")) {
            System.err.println("WindowsPbufferGLContext: WARNING: GL_NV_texture_rectangle extension not " +
                               "supported; skipping requested render_to_texture_rectangle support for pbuffer");
            rect = false;
          }
          if (rect) {
            if (DEBUG) {
              System.err.println("  Using render-to-texture-rectangle");
            }
            textureTarget = GL.GL_TEXTURE_RECTANGLE_NV;
          } else {
            if (DEBUG) {
              System.err.println("  Using vanilla render-to-texture");
            }
            textureTarget = GL.GL_TEXTURE_2D;
          }
          int[] tmp = new int[1];
          gl.glGenTextures(1, tmp);
          texture = tmp[0];
          gl.glBindTexture(textureTarget, texture);
          gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
          gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
          gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE);
          gl.glTexParameteri(textureTarget, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE);
          gl.glCopyTexImage2D(textureTarget, 0, GL.GL_RGB, 0, 0, width, height, 0);
        }
      }
    }
    return res;
  }

  public void handleModeSwitch(long parentHdc, long parentHglrc) {
    throw new GLException("Not yet implemented");
  }

  protected boolean isOffscreen() {
    // FIXME: currently the only caller of this won't cause proper
    // resizing of the pbuffer anyway.
    return false;
  }

  public int getOffscreenContextBufferedImageType() {
    throw new GLException("Should not call this");
  }

  public int getOffscreenContextReadBuffer() {
    throw new GLException("Should not call this");
  }

  public boolean offscreenImageNeedsVerticalFlip() {
    throw new GLException("Should not call this");
  }

  protected void create() {
    created = true;
    // Create a gl context for the p-buffer.
    hglrc = WGL.wglCreateContext(hdc);
    if (hglrc == 0) {
      throw new GLException("pbuffer creation error: wglCreateContext() failed");
    }

    // FIXME: provide option to not share display lists with subordinate pbuffer?
    if (!WGL.wglShareLists(parentHglrc, hglrc)) {
      throw new GLException("pbuffer: wglShareLists() failed");
    }
  }

  public void swapBuffers() throws GLException {
    // FIXME: do we need to do anything if the pbuffer is double-buffered?
    // For now, just grab the pixels for the render-to-texture support.
    if (rtt && !hasRTT) {
      if (DEBUG) {
        System.err.println("Copying pbuffer data to GL_TEXTURE_2D state");
      }

      GL gl = getGL();
      gl.glCopyTexSubImage2D(textureTarget, 0, 0, 0, 0, 0, width, height);
    }
  }

  private String wglGetLastError() {
    int err = WGL.GetLastError();
    String detail = null;
    switch (err) {
      case WGL.ERROR_INVALID_PIXEL_FORMAT: detail = "ERROR_INVALID_PIXEL_FORMAT";       break;
      case WGL.ERROR_NO_SYSTEM_RESOURCES:  detail = "ERROR_NO_SYSTEM_RESOURCES";        break;
      case WGL.ERROR_INVALID_DATA:         detail = "ERROR_INVALID_DATA";               break;
      case WGL.ERROR_PROC_NOT_FOUND:       detail = "ERROR_PROC_NOT_FOUND";             break;
      case WGL.ERROR_INVALID_WINDOW_HANDLE:detail = "ERROR_INVALID_WINDOW_HANDLE";      break;
      default:                             detail = "(Unknown error code " + err + ")"; break;
    }
    return detail;
  }
}