aboutsummaryrefslogtreecommitdiffstats
path: root/src/classes/com/sun/opengl/utils/Texture.java
blob: a21facb6544cc48f38d188c0961d922f16b81d0b (plain)
1
2
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
/*
 * Copyright (c) 2005 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
 * MICROSYSTEMS, 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.
 */

package com.sun.opengl.utils;

import javax.media.opengl.*;
import com.sun.opengl.impl.*;

/**
 * Represents an OpenGL texture object. Contains convenience routines
 * for enabling/disabling OpenGL texture state, binding this texture,
 * and computing texture coordinates for both the entire image as well
 * as a sub-image. 
 * 
 * <br> REMIND: document GL_TEXTURE_2D/GL_TEXTURE_RECTANGLE_ARB issues...
 * <br> REMIND: translucent images will have premultiplied comps by default...
 *
 * @author Chris Campbell
 * @author Kenneth Russell
 */
public class Texture {
  /** The GL target type. */
  private int target;
  /** The GL texture ID. */
  private int texID;
  /** The width of the texture. */
  private int texWidth;
  /** The height of the texture. */
  private int texHeight;
  /** The width of the image. */
  private int imgWidth;
  /** The height of the image. */
  private int imgHeight;
  /** Indicates whether the TextureData requires a vertical flip of
      the texture coords. */
  private boolean mustFlipVertically;

  /** The texture coordinates corresponding to the entire texture
      image. */
  private TextureCoords coords;

  private static final boolean DEBUG = Debug.debug("Texture");

  // For now make Texture constructor package-private to limit the
  // number of public APIs we commit to
  Texture(TextureData data) throws GLException {
    GL gl = getCurrentGL();

    imgWidth = data.getWidth();
    imgHeight = data.getHeight();
    mustFlipVertically = data.getMustFlipVertically();

    if ((isPowerOfTwo(imgWidth) && isPowerOfTwo(imgHeight)) ||
        gl.isExtensionAvailable("GL_ARB_texture_non_power_of_two")) {
      if (DEBUG) {
        if (isPowerOfTwo(imgWidth) && isPowerOfTwo(imgHeight)) {
          System.err.println("Power-of-two texture");
        } else {
          System.err.println("Using GL_ARB_texture_non_power_of_two");
        }
      }

      texWidth = imgWidth;
      texHeight = imgHeight;
      target = GL.GL_TEXTURE_2D;
    } else if (gl.isExtensionAvailable("GL_ARB_texture_rectangle")) {
      if (DEBUG) {
        System.err.println("Using GL_ARB_texture_rectangle");
      }

      texWidth = imgWidth;
      texHeight = imgHeight;
      target = GL.GL_TEXTURE_RECTANGLE_ARB;
    } else {
      if (DEBUG) {
        System.err.println("Expanding texture to power-of-two dimensions");
      }

      if (data.getBorder() != 0) {
        throw new RuntimeException("Scaling up a non-power-of-two texture which has a border won't work");
      }
      texWidth = nextPowerOfTwo(imgWidth);
      texHeight = nextPowerOfTwo(imgHeight);
      target = GL.GL_TEXTURE_2D;
    }

    // REMIND: let the user specify these, optionally
    int minFilter = GL.GL_LINEAR;
    int magFilter = GL.GL_LINEAR;
    int wrapMode = GL.GL_CLAMP_TO_EDGE;

    texID = createTextureID(gl); 
    setImageSize(imgWidth, imgHeight);
    gl.glBindTexture(target, texID);
    gl.glTexImage2D(target, 0, data.getInternalFormat(),
                    texWidth, texHeight, data.getBorder(),
                    data.getPixelFormat(), data.getPixelType(), null);

    // REMIND: figure out what to do for GL_TEXTURE_RECTANGLE_ARB
    if (target == GL.GL_TEXTURE_2D) {
      gl.glTexParameteri(target, GL.GL_TEXTURE_MIN_FILTER, minFilter);
      gl.glTexParameteri(target, GL.GL_TEXTURE_MAG_FILTER, magFilter);
      gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_S, wrapMode);
      gl.glTexParameteri(target, GL.GL_TEXTURE_WRAP_T, wrapMode);
    }

    updateSubImage(data, 0, 0);
  }

  /**
   * Enables this texture's target (e.g., GL_TEXTURE_2D) in the
   * current GL context's state.
   *
   * @throws GLException if no OpenGL context was current or if any
   * OpenGL-related errors occurred
   */
  public void enable() throws GLException {
    getCurrentGL().glEnable(target); 
  }

  /**
   * Disables this texture's target (e.g., GL_TEXTURE_2D) in the
   * current GL context's state.
   *
   * @throws GLException if no OpenGL context was current or if any
   * OpenGL-related errors occurred
   */
  public void disable() throws GLException {
    getCurrentGL().glDisable(target); 
  }

  /**
   * Binds this texture to the current GL context.
   *
   * @throws GLException if no OpenGL context was current or if any
   * OpenGL-related errors occurred
   */
  public void bind() throws GLException {
    getCurrentGL().glBindTexture(target, texID); 
  }

  /**
   * Disposes the native resources used by this texture object.
   *
   * @throws GLException if no OpenGL context was current or if any
   * OpenGL-related errors occurred
   */
  public void dispose() throws GLException {
    getCurrentGL().glDeleteTextures(1, new int[] {texID}, 0);
  }

  /**
   * Returns the OpenGL "target" of this texture.
   *
   * @return the OpenGL target of this texture
   * @see javax.media.opengl.GL#GL_TEXTURE_2D
   * @see javax.media.opengl.GL#GL_TEXTURE_RECTANGLE_ARB
   */
  public int getTarget() {
    return target;
  }

  /**
   * Returns the width of the texture.  Note that the texture width will
   * be greater than or equal to the width of the image contained within.
   *
   * @return the width of the texture
   */
  public int getWidth() {
    return texWidth;
  }
    
  /**
   * Returns the height of the texture.  Note that the texture height will
   * be greater than or equal to the height of the image contained within.
   *
   * @return the height of the texture
   */
  public int getHeight() {
    return texHeight;
  }   
    
  /** 
   * Returns the width of the image contained within this texture.
   *
   * @return the width of the image
   */
  public int getImageWidth() {
    return imgWidth;
  }

  /**
   * Returns the height of the image contained within this texture.
   *
   * @return the height of the image
   */
  public int getImageHeight() {
    return imgHeight;
  }

  /**
   * Returns the set of texture coordinates corresponding to the
   * entire image. If the TextureData indicated that the texture
   * coordinates must be flipped vertically, the returned
   * TextureCoords will take that into account.
   * 
   * @return the texture coordinates corresponding to the entire image
   */
  public TextureCoords getImageTexCoords() {
    return coords;
  }

  /**
   * Returns the set of texture coordinates corresponding to the
   * specified sub-image. The (x1, y1) and (x2, y2) points are
   * specified in terms of pixels starting from the lower-left of the
   * image. (x1, y1) should specify the lower-left corner of the
   * sub-image and (x2, y2) the upper-right corner of the sub-image.
   * If the TextureData indicated that the texture coordinates must be
   * flipped vertically, the returned TextureCoords will take that
   * into account; this should not be handled by the end user in the
   * specification of the y1 and y2 coordinates.
   * 
   * @return the texture coordinates corresponding to the specified sub-image
   */
  public TextureCoords getSubImageTexCoords(int x1, int y1, int x2, int y2) {
    if (target == GL.GL_TEXTURE_RECTANGLE_ARB) {
      if (mustFlipVertically) {
        return new TextureCoords(x1, texHeight - y1, x2, texHeight - y2);
      } else {
        return new TextureCoords(x1, y1, x2, y2);
      }
    } else {
      float tx1 = (float)x1 / (float)texWidth;
      float ty1 = (float)y1 / (float)texHeight;
      float tx2 = (float)x2 / (float)texWidth;
      float ty2 = (float)y2 / (float)texHeight;
      if (mustFlipVertically) {
        return new TextureCoords(tx1, 1.0f - ty1, tx2, 1.0f - ty2);
      } else {
        return new TextureCoords(tx1, ty1, tx2, ty2);
      }
    }
  }


  /**
   * Updates a subregion of the content area of this texture using the
   * data in the given image.
   *
   * @param data the image data to be uploaded to this texture
   * @param x the x offset (in pixels) relative to the lower-left corner
   * of this texture
   * @param y the y offset (in pixels) relative to the lower-left corner
   * of this texture
   *
   * @throws GLException if no OpenGL context was current or if any
   * OpenGL-related errors occurred
   */
  public void updateSubImage(TextureData data, int x, int y) throws GLException {
    GL gl = getCurrentGL();
    bind();
    if (data.isDataCompressed()) {
      // FIXME: should test availability of appropriate texture
      // compression extension here
      gl.glCompressedTexSubImage2D(target, data.getMipmapLevel(),
                                   x, y, data.getWidth(), data.getHeight(),
                                   data.getInternalFormat(), data.getBuffer().remaining(),
                                   data.getBuffer());
    } else {
      int[] align = new int[1];
      gl.glGetIntegerv(GL.GL_UNPACK_ALIGNMENT, align, 0); // save alignment
      gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, data.getAlignment());

      gl.glTexSubImage2D(target, data.getMipmapLevel(),
                         x, y, data.getWidth(), data.getHeight(),
                         data.getPixelFormat(), data.getPixelType(),
                         data.getBuffer());
      gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, align[0]); // restore align
    }
  }

  //----------------------------------------------------------------------
  // Internals only below this point
  //

  /**
   * Returns the current GL object. Throws GLException if no OpenGL
   * context was current.
   */
  private static GL getCurrentGL() throws GLException {
    GLContext context = GLContext.getCurrent();
    if (context == null) {
      throw new GLException("No OpenGL context current on current thread");
    }
    return context.getGL();
  }

  /**
   * Returns true if the given value is a power of two.
   *
   * @return true if the given value is a power of two, false otherwise
   */
  private static boolean isPowerOfTwo(int val) {
    return ((val & (val - 1)) == 0);
  }

  /**
   * Returns the nearest power of two that is larger than the given value.
   * If the given value is already a power of two, this method will simply
   * return that value.
   *
   * @param val the value
   * @return the next power of two
   */
  private static int nextPowerOfTwo(int val) {
    int ret = 1;
    while (ret < val) {
      ret <<= 1;
    }
    return ret;
  }

  /**
   * Updates the actual image dimensions; usually only called from
   * <code>updateImage</code>.
   */
  private void setImageSize(int width, int height) {
    imgWidth = width;
    imgHeight = height;
    if (target == GL.GL_TEXTURE_RECTANGLE_ARB) {
      if (mustFlipVertically) {
        coords = new TextureCoords(0, imgHeight, imgWidth, 0);
      } else {
        coords = new TextureCoords(0, 0, imgWidth, imgHeight);
      }
    } else {
      if (mustFlipVertically) {
        coords = new TextureCoords(0, (float) imgHeight / (float) texHeight,
                                   (float) imgWidth / (float) texWidth, 0);
      } else {
        coords = new TextureCoords(0, 0,
                                   (float) imgWidth / (float) texWidth,
                                   (float) imgHeight / (float) texHeight);
      }
    }
  }

  /**
   * Creates a new texture ID.
   *
   * @param gl the GL object associated with the current OpenGL context
   * @return a new texture ID
   */
  private static int createTextureID(GL gl) {
    int[] tmp = new int[1];
    gl.glGenTextures(1, tmp, 0);
    return tmp[0];
  }
}