1 /*
   2  * Copyright (c) 2003, 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 #ifndef HEADLESS
  27 
  28 #include <stdlib.h>
  29 #include <math.h>
  30 #include <jlong.h>
  31 
  32 #include "sun_java2d_opengl_OGLTextRenderer.h"
  33 
  34 #include "SurfaceData.h"
  35 #include "OGLContext.h"
  36 #include "OGLSurfaceData.h"
  37 #include "OGLRenderQueue.h"
  38 #include "OGLTextRenderer.h"
  39 #include "OGLVertexCache.h"
  40 #include "AccelGlyphCache.h"
  41 #include "fontscalerdefs.h"
  42 
  43 /**
  44  * The following constants define the inner and outer bounds of the
  45  * accelerated glyph cache.
  46  */
  47 #define OGLTR_CACHE_WIDTH       512
  48 #define OGLTR_CACHE_HEIGHT      512
  49 #define OGLTR_CACHE_CELL_WIDTH  16
  50 #define OGLTR_CACHE_CELL_HEIGHT 16
  51 
  52 /**
  53  * The current "glyph mode" state.  This variable is used to track the
  54  * codepath used to render a particular glyph.  This variable is reset to
  55  * MODE_NOT_INITED at the beginning of every call to OGLTR_DrawGlyphList().
  56  * As each glyph is rendered, the glyphMode variable is updated to reflect
  57  * the current mode, so if the current mode is the same as the mode used
  58  * to render the previous glyph, we can avoid doing costly setup operations
  59  * each time.
  60  */
  61 typedef enum {
  62     MODE_NOT_INITED,
  63     MODE_USE_CACHE_GRAY,
  64     MODE_USE_CACHE_LCD,
  65     MODE_NO_CACHE_GRAY,
  66     MODE_NO_CACHE_LCD
  67 } GlyphMode;
  68 static GlyphMode glyphMode = MODE_NOT_INITED;
  69 
  70 /**
  71  * This enum indicates the current state of the hardware glyph cache.
  72  * Initially the CacheStatus is set to CACHE_NOT_INITED, and then it is
  73  * set to either GRAY or LCD when the glyph cache is initialized.
  74  */
  75 typedef enum {
  76     CACHE_NOT_INITED,
  77     CACHE_GRAY,
  78     CACHE_LCD
  79 } CacheStatus;
  80 static CacheStatus cacheStatus = CACHE_NOT_INITED;
  81 
  82 /**
  83  * This is the one glyph cache.  Once it is initialized as either GRAY or
  84  * LCD, it stays in that mode for the duration of the application.  It should
  85  * be safe to use this one glyph cache for all screens in a multimon
  86  * environment, since the glyph cache texture is shared between all contexts,
  87  * and (in theory) OpenGL drivers should be smart enough to manage that
  88  * texture across all screens.
  89  */
  90 static GlyphCacheInfo *glyphCache = NULL;
  91 
  92 /**
  93  * The handle to the LCD text fragment program object.
  94  */
  95 static GLhandleARB lcdTextProgram = 0;
  96 
  97 /**
  98  * The size of one of the gamma LUT textures in any one dimension along
  99  * the edge, in texels.
 100  */
 101 #define LUT_EDGE 16
 102 
 103 /**
 104  * These are the texture object handles for the gamma and inverse gamma
 105  * lookup tables.
 106  */
 107 static GLuint gammaLutTextureID = 0;
 108 static GLuint invGammaLutTextureID = 0;
 109 
 110 /**
 111  * This value tracks the previous LCD contrast setting, so if the contrast
 112  * value hasn't changed since the last time the lookup tables were
 113  * generated (not very common), then we can skip updating the tables.
 114  */
 115 static jint lastLCDContrast = -1;
 116 
 117 /**
 118  * This value tracks the previous LCD rgbOrder setting, so if the rgbOrder
 119  * value has changed since the last time, it indicates that we need to
 120  * invalidate the cache, which may already store glyph images in the reverse
 121  * order.  Note that in most real world applications this value will not
 122  * change over the course of the application, but tests like Font2DTest
 123  * allow for changing the ordering at runtime, so we need to handle that case.
 124  */
 125 static jboolean lastRGBOrder = JNI_TRUE;
 126 
 127 /**
 128  * This constant defines the size of the tile to use in the
 129  * OGLTR_DrawLCDGlyphNoCache() method.  See below for more on why we
 130  * restrict this value to a particular size.
 131  */
 132 #define OGLTR_NOCACHE_TILE_SIZE 32
 133 
 134 /**
 135  * These constants define the size of the "cached destination" texture.
 136  * This texture is only used when rendering LCD-optimized text, as that
 137  * codepath needs direct access to the destination.  There is no way to
 138  * access the framebuffer directly from an OpenGL shader, so we need to first
 139  * copy the destination region corresponding to a particular glyph into
 140  * this cached texture, and then that texture will be accessed inside the
 141  * shader.  Copying the destination into this cached texture can be a very
 142  * expensive operation (accounting for about half the rendering time for
 143  * LCD text), so to mitigate this cost we try to bulk read a horizontal
 144  * region of the destination at a time.  (These values are empirically
 145  * derived for the common case where text runs horizontally.)
 146  *
 147  * Note: It is assumed in various calculations below that:
 148  *     (OGLTR_CACHED_DEST_WIDTH  >= OGLTR_CACHE_CELL_WIDTH)  &&
 149  *     (OGLTR_CACHED_DEST_WIDTH  >= OGLTR_NOCACHE_TILE_SIZE) &&
 150  *     (OGLTR_CACHED_DEST_HEIGHT >= OGLTR_CACHE_CELL_HEIGHT) &&
 151  *     (OGLTR_CACHED_DEST_HEIGHT >= OGLTR_NOCACHE_TILE_SIZE)
 152  */
 153 #define OGLTR_CACHED_DEST_WIDTH  512
 154 #define OGLTR_CACHED_DEST_HEIGHT 32
 155 
 156 /**
 157  * The handle to the "cached destination" texture object.
 158  */
 159 static GLuint cachedDestTextureID = 0;
 160 
 161 /**
 162  * The current bounds of the "cached destination" texture, in destination
 163  * coordinate space.  The width/height of these bounds will not exceed the
 164  * OGLTR_CACHED_DEST_WIDTH/HEIGHT values defined above.  These bounds are
 165  * only considered valid when the isCachedDestValid flag is JNI_TRUE.
 166  */
 167 static SurfaceDataBounds cachedDestBounds;
 168 
 169 /**
 170  * This flag indicates whether the "cached destination" texture contains
 171  * valid data.  This flag is reset to JNI_FALSE at the beginning of every
 172  * call to OGLTR_DrawGlyphList().  Once we copy valid destination data
 173  * into the cached texture, this flag is set to JNI_TRUE.  This way, we can
 174  * limit the number of times we need to copy destination data, which is a
 175  * very costly operation.
 176  */
 177 static jboolean isCachedDestValid = JNI_FALSE;
 178 
 179 /**
 180  * The bounds of the previously rendered LCD glyph, in destination
 181  * coordinate space.  We use these bounds to determine whether the glyph
 182  * currently being rendered overlaps the previously rendered glyph (i.e.
 183  * its bounding box intersects that of the previously rendered glyph).  If
 184  * so, we need to re-read the destination area associated with that previous
 185  * glyph so that we can correctly blend with the actual destination data.
 186  */
 187 static SurfaceDataBounds previousGlyphBounds;
 188 
 189 /**
 190  * Initializes the one glyph cache (texture and data structure).
 191  * If lcdCache is JNI_TRUE, the texture will contain RGB data,
 192  * otherwise we will simply store the grayscale/monochrome glyph images
 193  * as intensity values (which work well with the GL_MODULATE function).
 194  */
 195 static jboolean
 196 OGLTR_InitGlyphCache(jboolean lcdCache)
 197 {
 198     GlyphCacheInfo *gcinfo;
 199     GLclampf priority = 1.0f;
 200     GLenum internalFormat = lcdCache ? GL_RGB8 : GL_INTENSITY8;
 201     GLenum pixelFormat = lcdCache ? GL_RGB : GL_LUMINANCE;
 202 
 203     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_InitGlyphCache");
 204 
 205     // init glyph cache data structure
 206     gcinfo = AccelGlyphCache_Init(OGLTR_CACHE_WIDTH,
 207                                   OGLTR_CACHE_HEIGHT,
 208                                   OGLTR_CACHE_CELL_WIDTH,
 209                                   OGLTR_CACHE_CELL_HEIGHT,
 210                                   OGLVertexCache_FlushVertexCache);
 211     if (gcinfo == NULL) {
 212         J2dRlsTraceLn(J2D_TRACE_ERROR,
 213                       "OGLTR_InitGlyphCache: could not init OGL glyph cache");
 214         return JNI_FALSE;
 215     }
 216 
 217     // init cache texture object
 218     j2d_glGenTextures(1, &gcinfo->cacheID);
 219     j2d_glBindTexture(GL_TEXTURE_2D, gcinfo->cacheID);
 220     j2d_glPrioritizeTextures(1, &gcinfo->cacheID, &priority);
 221     j2d_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
 222     j2d_glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 223 
 224     j2d_glTexImage2D(GL_TEXTURE_2D, 0, internalFormat,
 225                      OGLTR_CACHE_WIDTH, OGLTR_CACHE_HEIGHT, 0,
 226                      pixelFormat, GL_UNSIGNED_BYTE, NULL);
 227 
 228     cacheStatus = (lcdCache ? CACHE_LCD : CACHE_GRAY);
 229     glyphCache = gcinfo;
 230 
 231     return JNI_TRUE;
 232 }
 233 
 234 /**
 235  * Adds the given glyph to the glyph cache (texture and data structure)
 236  * associated with the given OGLContext.
 237  */
 238 static void
 239 OGLTR_AddToGlyphCache(GlyphInfo *glyph, jboolean rgbOrder)
 240 {
 241     GLenum pixelFormat;
 242     CacheCellInfo *ccinfo;
 243 
 244     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_AddToGlyphCache");
 245 
 246     if ((glyphCache == NULL) || (glyph->image == NULL)) {
 247         return;
 248     }
 249 
 250     if (cacheStatus == CACHE_LCD) {
 251         pixelFormat = rgbOrder ? GL_RGB : GL_BGR;
 252     } else {
 253         pixelFormat = GL_LUMINANCE;
 254     }
 255 
 256     AccelGlyphCache_AddGlyph(glyphCache, glyph);
 257     ccinfo = (CacheCellInfo *) glyph->cellInfo;
 258 
 259     if (ccinfo != NULL) {
 260         // store glyph image in texture cell
 261         j2d_glTexSubImage2D(GL_TEXTURE_2D, 0,
 262                             ccinfo->x, ccinfo->y,
 263                             glyph->width, glyph->height,
 264                             pixelFormat, GL_UNSIGNED_BYTE, glyph->image);
 265     }
 266 }
 267 
 268 /**
 269  * This is the GLSL fragment shader source code for rendering LCD-optimized
 270  * text.  Do not be frightened; it is much easier to understand than the
 271  * equivalent ASM-like fragment program!
 272  *
 273  * The "uniform" variables at the top are initialized once the program is
 274  * linked, and are updated at runtime as needed (e.g. when the source color
 275  * changes, we will modify the "src_adj" value in OGLTR_UpdateLCDTextColor()).
 276  *
 277  * The "main" function is executed for each "fragment" (or pixel) in the
 278  * glyph image.  We have determined that the pow() function can be quite
 279  * slow and it only operates on scalar values, not vectors as we require.
 280  * So instead we build two 3D textures containing gamma (and inverse gamma)
 281  * lookup tables that allow us to approximate a component-wise pow() function
 282  * with a single 3D texture lookup.  This approach is at least 2x faster
 283  * than the equivalent pow() calls.
 284  *
 285  * The variables involved in the equation can be expressed as follows:
 286  *
 287  *   Cs = Color component of the source (foreground color) [0.0, 1.0]
 288  *   Cd = Color component of the destination (background color) [0.0, 1.0]
 289  *   Cr = Color component to be written to the destination [0.0, 1.0]
 290  *   Ag = Glyph alpha (aka intensity or coverage) [0.0, 1.0]
 291  *   Ga = Gamma adjustment in the range [1.0, 2.5]
 292  *   (^ means raised to the power)
 293  *
 294  * And here is the theoretical equation approximated by this shader:
 295  *
 296  *            Cr = (Ag*(Cs^Ga) + (1-Ag)*(Cd^Ga)) ^ (1/Ga)
 297  */
 298 static const char *lcdTextShaderSource =
 299     "uniform vec3 src_adj;"
 300     "uniform sampler2D glyph_tex;"
 301     "uniform sampler2D dst_tex;"
 302     "uniform sampler3D invgamma_tex;"
 303     "uniform sampler3D gamma_tex;"
 304     ""
 305     "void main(void)"
 306     "{"
 307          // load the RGB value from the glyph image at the current texcoord
 308     "    vec3 glyph_clr = vec3(texture2D(glyph_tex, gl_TexCoord[0].st));"
 309     "    if (glyph_clr == vec3(0.0)) {"
 310              // zero coverage, so skip this fragment
 311     "        discard;"
 312     "    }"
 313          // load the RGB value from the corresponding destination pixel
 314     "    vec3 dst_clr = vec3(texture2D(dst_tex, gl_TexCoord[1].st));"
 315          // gamma adjust the dest color using the invgamma LUT
 316     "    vec3 dst_adj = vec3(texture3D(invgamma_tex, dst_clr.stp));"
 317          // linearly interpolate the three color values
 318     "    vec3 result = mix(dst_adj, src_adj, glyph_clr);"
 319          // gamma re-adjust the resulting color (alpha is always set to 1.0)
 320     "    gl_FragColor = vec4(vec3(texture3D(gamma_tex, result.stp)), 1.0);"
 321     "}";
 322 
 323 /**
 324  * Compiles and links the LCD text shader program.  If successful, this
 325  * function returns a handle to the newly created shader program; otherwise
 326  * returns 0.
 327  */
 328 static GLhandleARB
 329 OGLTR_CreateLCDTextProgram()
 330 {
 331     GLhandleARB lcdTextProgram;
 332     GLint loc;
 333 
 334     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_CreateLCDTextProgram");
 335 
 336     lcdTextProgram = OGLContext_CreateFragmentProgram(lcdTextShaderSource);
 337     if (lcdTextProgram == 0) {
 338         J2dRlsTraceLn(J2D_TRACE_ERROR,
 339                       "OGLTR_CreateLCDTextProgram: error creating program");
 340         return 0;
 341     }
 342 
 343     // "use" the program object temporarily so that we can set the uniforms
 344     j2d_glUseProgramObjectARB(lcdTextProgram);
 345 
 346     // set the "uniform" values
 347     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "glyph_tex");
 348     j2d_glUniform1iARB(loc, 0); // texture unit 0
 349     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "dst_tex");
 350     j2d_glUniform1iARB(loc, 1); // texture unit 1
 351     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "invgamma_tex");
 352     j2d_glUniform1iARB(loc, 2); // texture unit 2
 353     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "gamma_tex");
 354     j2d_glUniform1iARB(loc, 3); // texture unit 3
 355 
 356     // "unuse" the program object; it will be re-bound later as needed
 357     j2d_glUseProgramObjectARB(0);
 358 
 359     return lcdTextProgram;
 360 }
 361 
 362 /**
 363  * Initializes a 3D texture object for use as a three-dimensional gamma
 364  * lookup table.  Note that the wrap mode is initialized to GL_LINEAR so
 365  * that the table will interpolate adjacent values when the index falls
 366  * somewhere in between.
 367  */
 368 static GLuint
 369 OGLTR_InitGammaLutTexture()
 370 {
 371     GLuint lutTextureID;
 372 
 373     j2d_glGenTextures(1, &lutTextureID);
 374     j2d_glBindTexture(GL_TEXTURE_3D, lutTextureID);
 375     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 376     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 377     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 378     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 379     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
 380 
 381     return lutTextureID;
 382 }
 383 
 384 /**
 385  * Updates the lookup table in the given texture object with the float
 386  * values in the given system memory buffer.  Note that we could use
 387  * glTexSubImage3D() when updating the texture after its first
 388  * initialization, but since we're updating the entire table (with
 389  * power-of-two dimensions) and this is a relatively rare event, we'll
 390  * just stick with glTexImage3D().
 391  */
 392 static void
 393 OGLTR_UpdateGammaLutTexture(GLuint texID, GLfloat *lut, jint size)
 394 {
 395     j2d_glBindTexture(GL_TEXTURE_3D, texID);
 396     j2d_glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB8,
 397                      size, size, size, 0, GL_RGB, GL_FLOAT, lut);
 398 }
 399 
 400 /**
 401  * (Re)Initializes the gamma lookup table textures.
 402  *
 403  * The given contrast value is an int in the range [100, 250] which we will
 404  * then scale to fit in the range [1.0, 2.5].  We create two LUTs, one
 405  * that essentially calculates pow(x, gamma) and the other calculates
 406  * pow(x, 1/gamma).  These values are replicated in all three dimensions, so
 407  * given a single 3D texture coordinate (typically this will be a triplet
 408  * in the form (r,g,b)), the 3D texture lookup will return an RGB triplet:
 409  *
 410  *     (pow(r,g), pow(y,g), pow(z,g)
 411  *
 412  * where g is either gamma or 1/gamma, depending on the table.
 413  */
 414 static jboolean
 415 OGLTR_UpdateLCDTextContrast(jint contrast)
 416 {
 417     double gamma = ((double)contrast) / 100.0;
 418     double ig = gamma;
 419     double g = 1.0 / ig;
 420     GLfloat lut[LUT_EDGE][LUT_EDGE][LUT_EDGE][3];
 421     GLfloat invlut[LUT_EDGE][LUT_EDGE][LUT_EDGE][3];
 422     int min = 0;
 423     int max = LUT_EDGE - 1;
 424     int x, y, z;
 425 
 426     J2dTraceLn1(J2D_TRACE_INFO,
 427                 "OGLTR_UpdateLCDTextContrast: contrast=%d", contrast);
 428 
 429     for (z = min; z <= max; z++) {
 430         double zval = ((double)z) / max;
 431         GLfloat gz = (GLfloat)pow(zval, g);
 432         GLfloat igz = (GLfloat)pow(zval, ig);
 433 
 434         for (y = min; y <= max; y++) {
 435             double yval = ((double)y) / max;
 436             GLfloat gy = (GLfloat)pow(yval, g);
 437             GLfloat igy = (GLfloat)pow(yval, ig);
 438 
 439             for (x = min; x <= max; x++) {
 440                 double xval = ((double)x) / max;
 441                 GLfloat gx = (GLfloat)pow(xval, g);
 442                 GLfloat igx = (GLfloat)pow(xval, ig);
 443 
 444                 lut[z][y][x][0] = gx;
 445                 lut[z][y][x][1] = gy;
 446                 lut[z][y][x][2] = gz;
 447 
 448                 invlut[z][y][x][0] = igx;
 449                 invlut[z][y][x][1] = igy;
 450                 invlut[z][y][x][2] = igz;
 451             }
 452         }
 453     }
 454 
 455     if (gammaLutTextureID == 0) {
 456         gammaLutTextureID = OGLTR_InitGammaLutTexture();
 457     }
 458     OGLTR_UpdateGammaLutTexture(gammaLutTextureID, (GLfloat *)lut, LUT_EDGE);
 459 
 460     if (invGammaLutTextureID == 0) {
 461         invGammaLutTextureID = OGLTR_InitGammaLutTexture();
 462     }
 463     OGLTR_UpdateGammaLutTexture(invGammaLutTextureID,
 464                                 (GLfloat *)invlut, LUT_EDGE);
 465 
 466     return JNI_TRUE;
 467 }
 468 
 469 /**
 470  * Updates the current gamma-adjusted source color ("src_adj") of the LCD
 471  * text shader program.  Note that we could calculate this value in the
 472  * shader (e.g. just as we do for "dst_adj"), but would be unnecessary work
 473  * (and a measurable performance hit, maybe around 5%) since this value is
 474  * constant over the entire glyph list.  So instead we just calculate the
 475  * gamma-adjusted value once and update the uniform parameter of the LCD
 476  * shader as needed.
 477  */
 478 static jboolean
 479 OGLTR_UpdateLCDTextColor(jint contrast)
 480 {
 481     double gamma = ((double)contrast) / 100.0;
 482     GLfloat radj, gadj, badj;
 483     GLfloat clr[4];
 484     GLint loc;
 485 
 486     J2dTraceLn1(J2D_TRACE_INFO,
 487                 "OGLTR_UpdateLCDTextColor: contrast=%d", contrast);
 488 
 489     /*
 490      * Note: Ideally we would update the "src_adj" uniform parameter only
 491      * when there is a change in the source color.  Fortunately, the cost
 492      * of querying the current OpenGL color state and updating the uniform
 493      * value is quite small, and in the common case we only need to do this
 494      * once per GlyphList, so we gain little from trying to optimize too
 495      * eagerly here.
 496      */
 497 
 498     // get the current OpenGL primary color state
 499     j2d_glGetFloatv(GL_CURRENT_COLOR, clr);
 500 
 501     // gamma adjust the primary color
 502     radj = (GLfloat)pow(clr[0], gamma);
 503     gadj = (GLfloat)pow(clr[1], gamma);
 504     badj = (GLfloat)pow(clr[2], gamma);
 505 
 506     // update the "src_adj" parameter of the shader program with this value
 507     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "src_adj");
 508     j2d_glUniform3fARB(loc, radj, gadj, badj);
 509 
 510     return JNI_TRUE;
 511 }
 512 
 513 /**
 514  * Enables the LCD text shader and updates any related state, such as the
 515  * gamma lookup table textures.
 516  */
 517 static jboolean
 518 OGLTR_EnableLCDGlyphModeState(GLuint glyphTextureID, jint contrast)
 519 {
 520     // bind the texture containing glyph data to texture unit 0
 521     j2d_glActiveTextureARB(GL_TEXTURE0_ARB);
 522     j2d_glBindTexture(GL_TEXTURE_2D, glyphTextureID);
 523 
 524     // bind the texture tile containing destination data to texture unit 1
 525     j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
 526     if (cachedDestTextureID == 0) {
 527         cachedDestTextureID =
 528             OGLContext_CreateBlitTexture(GL_RGB8, GL_RGB,
 529                                          OGLTR_CACHED_DEST_WIDTH,
 530                                          OGLTR_CACHED_DEST_HEIGHT);
 531         if (cachedDestTextureID == 0) {
 532             return JNI_FALSE;
 533         }
 534     }
 535     j2d_glBindTexture(GL_TEXTURE_2D, cachedDestTextureID);
 536 
 537     // note that GL_TEXTURE_2D was already enabled for texture unit 0,
 538     // but we need to explicitly enable it for texture unit 1
 539     j2d_glEnable(GL_TEXTURE_2D);
 540 
 541     // create the LCD text shader, if necessary
 542     if (lcdTextProgram == 0) {
 543         lcdTextProgram = OGLTR_CreateLCDTextProgram();
 544         if (lcdTextProgram == 0) {
 545             return JNI_FALSE;
 546         }
 547     }
 548 
 549     // enable the LCD text shader
 550     j2d_glUseProgramObjectARB(lcdTextProgram);
 551 
 552     // update the current contrast settings, if necessary
 553     if (lastLCDContrast != contrast) {
 554         if (!OGLTR_UpdateLCDTextContrast(contrast)) {
 555             return JNI_FALSE;
 556         }
 557         lastLCDContrast = contrast;
 558     }
 559 
 560     // update the current color settings
 561     if (!OGLTR_UpdateLCDTextColor(contrast)) {
 562         return JNI_FALSE;
 563     }
 564 
 565     // bind the gamma LUT textures
 566     j2d_glActiveTextureARB(GL_TEXTURE2_ARB);
 567     j2d_glBindTexture(GL_TEXTURE_3D, invGammaLutTextureID);
 568     j2d_glEnable(GL_TEXTURE_3D);
 569     j2d_glActiveTextureARB(GL_TEXTURE3_ARB);
 570     j2d_glBindTexture(GL_TEXTURE_3D, gammaLutTextureID);
 571     j2d_glEnable(GL_TEXTURE_3D);
 572 
 573     return JNI_TRUE;
 574 }
 575 
 576 void
 577 OGLTR_EnableGlyphVertexCache(OGLContext *oglc)
 578 {
 579     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_EnableGlyphVertexCache");
 580 
 581     if (!OGLVertexCache_InitVertexCache(oglc)) {
 582         return;
 583     }
 584 
 585     if (glyphCache == NULL) {
 586         if (!OGLTR_InitGlyphCache(JNI_FALSE)) {
 587             return;
 588         }
 589     }
 590 
 591     j2d_glEnable(GL_TEXTURE_2D);
 592     j2d_glBindTexture(GL_TEXTURE_2D, glyphCache->cacheID);
 593     j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 594 
 595     // for grayscale/monochrome text, the current OpenGL source color
 596     // is modulated with the glyph image as part of the texture
 597     // application stage, so we use GL_MODULATE here
 598     OGLC_UPDATE_TEXTURE_FUNCTION(oglc, GL_MODULATE);
 599 }
 600 
 601 void
 602 OGLTR_DisableGlyphVertexCache(OGLContext *oglc)
 603 {
 604     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_DisableGlyphVertexCache");
 605 
 606     OGLVertexCache_FlushVertexCache();
 607     OGLVertexCache_RestoreColorState(oglc);
 608 
 609     j2d_glDisable(GL_TEXTURE_2D);
 610     j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
 611     j2d_glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
 612     j2d_glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
 613     j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
 614 }
 615 
 616 /**
 617  * Disables any pending state associated with the current "glyph mode".
 618  */
 619 static void
 620 OGLTR_DisableGlyphModeState()
 621 {
 622     switch (glyphMode) {
 623     case MODE_NO_CACHE_LCD:
 624         j2d_glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
 625         j2d_glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
 626         /* FALLTHROUGH */
 627 
 628     case MODE_USE_CACHE_LCD:
 629         j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
 630         j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
 631         j2d_glUseProgramObjectARB(0);
 632         j2d_glActiveTextureARB(GL_TEXTURE3_ARB);
 633         j2d_glDisable(GL_TEXTURE_3D);
 634         j2d_glActiveTextureARB(GL_TEXTURE2_ARB);
 635         j2d_glDisable(GL_TEXTURE_3D);
 636         j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
 637         j2d_glDisable(GL_TEXTURE_2D);
 638         j2d_glActiveTextureARB(GL_TEXTURE0_ARB);
 639         break;
 640 
 641     case MODE_NO_CACHE_GRAY:
 642     case MODE_USE_CACHE_GRAY:
 643     case MODE_NOT_INITED:
 644     default:
 645         break;
 646     }
 647 }
 648 
 649 static jboolean
 650 OGLTR_DrawGrayscaleGlyphViaCache(OGLContext *oglc,
 651                                  GlyphInfo *ginfo, jint x, jint y)
 652 {
 653     CacheCellInfo *cell;
 654     jfloat x1, y1, x2, y2;
 655 
 656     if (glyphMode != MODE_USE_CACHE_GRAY) {
 657         OGLTR_DisableGlyphModeState();
 658         CHECK_PREVIOUS_OP(OGL_STATE_GLYPH_OP);
 659         glyphMode = MODE_USE_CACHE_GRAY;
 660     }
 661 
 662     if (ginfo->cellInfo == NULL) {
 663         // attempt to add glyph to accelerated glyph cache
 664         OGLTR_AddToGlyphCache(ginfo, JNI_FALSE);
 665 
 666         if (ginfo->cellInfo == NULL) {
 667             // we'll just no-op in the rare case that the cell is NULL
 668             return JNI_TRUE;
 669         }
 670     }
 671 
 672     cell = (CacheCellInfo *) (ginfo->cellInfo);
 673     cell->timesRendered++;
 674 
 675     x1 = (jfloat)x;
 676     y1 = (jfloat)y;
 677     x2 = x1 + ginfo->width;
 678     y2 = y1 + ginfo->height;
 679 
 680     OGLVertexCache_AddGlyphQuad(oglc,
 681                                 cell->tx1, cell->ty1,
 682                                 cell->tx2, cell->ty2,
 683                                 x1, y1, x2, y2);
 684 
 685     return JNI_TRUE;
 686 }
 687 
 688 /**
 689  * Evaluates to true if the rectangle defined by gx1/gy1/gx2/gy2 is
 690  * inside outerBounds.
 691  */
 692 #define INSIDE(gx1, gy1, gx2, gy2, outerBounds) \
 693     (((gx1) >= outerBounds.x1) && ((gy1) >= outerBounds.y1) && \
 694      ((gx2) <= outerBounds.x2) && ((gy2) <= outerBounds.y2))
 695 
 696 /**
 697  * Evaluates to true if the rectangle defined by gx1/gy1/gx2/gy2 intersects
 698  * the rectangle defined by bounds.
 699  */
 700 #define INTERSECTS(gx1, gy1, gx2, gy2, bounds) \
 701     ((bounds.x2 > (gx1)) && (bounds.y2 > (gy1)) && \
 702      (bounds.x1 < (gx2)) && (bounds.y1 < (gy2)))
 703 
 704 /**
 705  * This method checks to see if the given LCD glyph bounds fall within the
 706  * cached destination texture bounds.  If so, this method can return
 707  * immediately.  If not, this method will copy a chunk of framebuffer data
 708  * into the cached destination texture and then update the current cached
 709  * destination bounds before returning.
 710  */
 711 static void
 712 OGLTR_UpdateCachedDestination(OGLSDOps *dstOps, GlyphInfo *ginfo,
 713                               jint gx1, jint gy1, jint gx2, jint gy2,
 714                               jint glyphIndex, jint totalGlyphs)
 715 {
 716     jint dx1, dy1, dx2, dy2;
 717     jint dx1adj, dy1adj;
 718 
 719     if (isCachedDestValid && INSIDE(gx1, gy1, gx2, gy2, cachedDestBounds)) {
 720         // glyph is already within the cached destination bounds; no need
 721         // to read back the entire destination region again, but we do
 722         // need to see if the current glyph overlaps the previous glyph...
 723 
 724         if (INTERSECTS(gx1, gy1, gx2, gy2, previousGlyphBounds)) {
 725             // the current glyph overlaps the destination region touched
 726             // by the previous glyph, so now we need to read back the part
 727             // of the destination corresponding to the previous glyph
 728             dx1 = previousGlyphBounds.x1;
 729             dy1 = previousGlyphBounds.y1;
 730             dx2 = previousGlyphBounds.x2;
 731             dy2 = previousGlyphBounds.y2;
 732 
 733             // this accounts for lower-left origin of the destination region
 734             dx1adj = dstOps->xOffset + dx1;
 735             dy1adj = dstOps->yOffset + dstOps->height - dy2;
 736 
 737             // copy destination into subregion of cached texture tile:
 738             //   dx1-cachedDestBounds.x1 == +xoffset from left side of texture
 739             //   cachedDestBounds.y2-dy2 == +yoffset from bottom of texture
 740             j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
 741             j2d_glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
 742                                     dx1 - cachedDestBounds.x1,
 743                                     cachedDestBounds.y2 - dy2,
 744                                     dx1adj, dy1adj,
 745                                     dx2-dx1, dy2-dy1);
 746         }
 747     } else {
 748         jint remainingWidth;
 749 
 750         // destination region is not valid, so we need to read back a
 751         // chunk of the destination into our cached texture
 752 
 753         // position the upper-left corner of the destination region on the
 754         // "top" line of glyph list
 755         // REMIND: this isn't ideal; it would be better if we had some idea
 756         //         of the bounding box of the whole glyph list (this is
 757         //         do-able, but would require iterating through the whole
 758         //         list up front, which may present its own problems)
 759         dx1 = gx1;
 760         dy1 = gy1;
 761 
 762         if (ginfo->advanceX > 0) {
 763             // estimate the width based on our current position in the glyph
 764             // list and using the x advance of the current glyph (this is just
 765             // a quick and dirty heuristic; if this is a "thin" glyph image,
 766             // then we're likely to underestimate, and if it's "thick" then we
 767             // may end up reading back more than we need to)
 768             remainingWidth =
 769                 (jint)(ginfo->advanceX * (totalGlyphs - glyphIndex));
 770             if (remainingWidth > OGLTR_CACHED_DEST_WIDTH) {
 771                 remainingWidth = OGLTR_CACHED_DEST_WIDTH;
 772             } else if (remainingWidth < ginfo->width) {
 773                 // in some cases, the x-advance may be slightly smaller
 774                 // than the actual width of the glyph; if so, adjust our
 775                 // estimate so that we can accommodate the entire glyph
 776                 remainingWidth = ginfo->width;
 777             }
 778         } else {
 779             // a negative advance is possible when rendering rotated text,
 780             // in which case it is difficult to estimate an appropriate
 781             // region for readback, so we will pick a region that
 782             // encompasses just the current glyph
 783             remainingWidth = ginfo->width;
 784         }
 785         dx2 = dx1 + remainingWidth;
 786 
 787         // estimate the height (this is another sloppy heuristic; we'll
 788         // make the cached destination region tall enough to encompass most
 789         // glyphs that are small enough to fit in the glyph cache, and then
 790         // we add a little something extra to account for descenders
 791         dy2 = dy1 + OGLTR_CACHE_CELL_HEIGHT + 2;
 792 
 793         // this accounts for lower-left origin of the destination region
 794         dx1adj = dstOps->xOffset + dx1;
 795         dy1adj = dstOps->yOffset + dstOps->height - dy2;
 796 
 797         // copy destination into cached texture tile (the lower-left corner
 798         // of the destination region will be positioned at the lower-left
 799         // corner (0,0) of the texture)
 800         j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
 801         j2d_glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
 802                                 0, 0, dx1adj, dy1adj,
 803                                 dx2-dx1, dy2-dy1);
 804 
 805         // update the cached bounds and mark it valid
 806         cachedDestBounds.x1 = dx1;
 807         cachedDestBounds.y1 = dy1;
 808         cachedDestBounds.x2 = dx2;
 809         cachedDestBounds.y2 = dy2;
 810         isCachedDestValid = JNI_TRUE;
 811     }
 812 
 813     // always update the previous glyph bounds
 814     previousGlyphBounds.x1 = gx1;
 815     previousGlyphBounds.y1 = gy1;
 816     previousGlyphBounds.x2 = gx2;
 817     previousGlyphBounds.y2 = gy2;
 818 }
 819 
 820 static jboolean
 821 OGLTR_DrawLCDGlyphViaCache(OGLContext *oglc, OGLSDOps *dstOps,
 822                            GlyphInfo *ginfo, jint x, jint y,
 823                            jint glyphIndex, jint totalGlyphs,
 824                            jboolean rgbOrder, jint contrast)
 825 {
 826     CacheCellInfo *cell;
 827     jint dx1, dy1, dx2, dy2;
 828     jfloat dtx1, dty1, dtx2, dty2;
 829 
 830     if (glyphMode != MODE_USE_CACHE_LCD) {
 831         OGLTR_DisableGlyphModeState();
 832         CHECK_PREVIOUS_OP(GL_TEXTURE_2D);
 833         j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 834 
 835         if (glyphCache == NULL) {
 836             if (!OGLTR_InitGlyphCache(JNI_TRUE)) {
 837                 return JNI_FALSE;
 838             }
 839         }
 840 
 841         if (rgbOrder != lastRGBOrder) {
 842             // need to invalidate the cache in this case; see comments
 843             // for lastRGBOrder above
 844             AccelGlyphCache_Invalidate(glyphCache);
 845             lastRGBOrder = rgbOrder;
 846         }
 847 
 848         if (!OGLTR_EnableLCDGlyphModeState(glyphCache->cacheID, contrast)) {
 849             return JNI_FALSE;
 850         }
 851 
 852         // when a fragment shader is enabled, the texture function state is
 853         // ignored, so the following line is not needed...
 854         // OGLC_UPDATE_TEXTURE_FUNCTION(oglc, GL_MODULATE);
 855 
 856         glyphMode = MODE_USE_CACHE_LCD;
 857     }
 858 
 859     if (ginfo->cellInfo == NULL) {
 860         // rowBytes will always be a multiple of 3, so the following is safe
 861         j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, ginfo->rowBytes / 3);
 862 
 863         // make sure the glyph cache texture is bound to texture unit 0
 864         j2d_glActiveTextureARB(GL_TEXTURE0_ARB);
 865 
 866         // attempt to add glyph to accelerated glyph cache
 867         OGLTR_AddToGlyphCache(ginfo, rgbOrder);
 868 
 869         if (ginfo->cellInfo == NULL) {
 870             // we'll just no-op in the rare case that the cell is NULL
 871             return JNI_TRUE;
 872         }
 873     }
 874 
 875     cell = (CacheCellInfo *) (ginfo->cellInfo);
 876     cell->timesRendered++;
 877 
 878     // location of the glyph in the destination's coordinate space
 879     dx1 = x;
 880     dy1 = y;
 881     dx2 = dx1 + ginfo->width;
 882     dy2 = dy1 + ginfo->height;
 883 
 884     // copy destination into second cached texture, if necessary
 885     OGLTR_UpdateCachedDestination(dstOps, ginfo,
 886                                   dx1, dy1, dx2, dy2,
 887                                   glyphIndex, totalGlyphs);
 888 
 889     // texture coordinates of the destination tile
 890     dtx1 = ((jfloat)(dx1 - cachedDestBounds.x1)) / OGLTR_CACHED_DEST_WIDTH;
 891     dty1 = ((jfloat)(cachedDestBounds.y2 - dy1)) / OGLTR_CACHED_DEST_HEIGHT;
 892     dtx2 = ((jfloat)(dx2 - cachedDestBounds.x1)) / OGLTR_CACHED_DEST_WIDTH;
 893     dty2 = ((jfloat)(cachedDestBounds.y2 - dy2)) / OGLTR_CACHED_DEST_HEIGHT;
 894 
 895     // render composed texture to the destination surface
 896     j2d_glBegin(GL_QUADS);
 897     j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, cell->tx1, cell->ty1);
 898     j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx1, dty1);
 899     j2d_glVertex2i(dx1, dy1);
 900     j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, cell->tx2, cell->ty1);
 901     j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx2, dty1);
 902     j2d_glVertex2i(dx2, dy1);
 903     j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, cell->tx2, cell->ty2);
 904     j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx2, dty2);
 905     j2d_glVertex2i(dx2, dy2);
 906     j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, cell->tx1, cell->ty2);
 907     j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx1, dty2);
 908     j2d_glVertex2i(dx1, dy2);
 909     j2d_glEnd();
 910 
 911     return JNI_TRUE;
 912 }
 913 
 914 static jboolean
 915 OGLTR_DrawGrayscaleGlyphNoCache(OGLContext *oglc,
 916                                 GlyphInfo *ginfo, jint x, jint y)
 917 {
 918     jint tw, th;
 919     jint sx, sy, sw, sh;
 920     jint x0;
 921     jint w = ginfo->width;
 922     jint h = ginfo->height;
 923 
 924     if (glyphMode != MODE_NO_CACHE_GRAY) {
 925         OGLTR_DisableGlyphModeState();
 926         CHECK_PREVIOUS_OP(OGL_STATE_MASK_OP);
 927         glyphMode = MODE_NO_CACHE_GRAY;
 928     }
 929 
 930     x0 = x;
 931     tw = OGLVC_MASK_CACHE_TILE_WIDTH;
 932     th = OGLVC_MASK_CACHE_TILE_HEIGHT;
 933 
 934     for (sy = 0; sy < h; sy += th, y += th) {
 935         x = x0;
 936         sh = ((sy + th) > h) ? (h - sy) : th;
 937 
 938         for (sx = 0; sx < w; sx += tw, x += tw) {
 939             sw = ((sx + tw) > w) ? (w - sx) : tw;
 940 
 941             OGLVertexCache_AddMaskQuad(oglc,
 942                                        sx, sy, x, y, sw, sh,
 943                                        w, ginfo->image);
 944         }
 945     }
 946 
 947     return JNI_TRUE;
 948 }
 949 
 950 static jboolean
 951 OGLTR_DrawLCDGlyphNoCache(OGLContext *oglc, OGLSDOps *dstOps,
 952                           GlyphInfo *ginfo, jint x, jint y,
 953                           jint rowBytesOffset,
 954                           jboolean rgbOrder, jint contrast)
 955 {
 956     GLfloat tx1, ty1, tx2, ty2;
 957     GLfloat dtx1, dty1, dtx2, dty2;
 958     jint tw, th;
 959     jint sx, sy, sw, sh, dxadj, dyadj;
 960     jint x0;
 961     jint w = ginfo->width;
 962     jint h = ginfo->height;
 963     GLenum pixelFormat = rgbOrder ? GL_RGB : GL_BGR;
 964 
 965     if (glyphMode != MODE_NO_CACHE_LCD) {
 966         OGLTR_DisableGlyphModeState();
 967         CHECK_PREVIOUS_OP(GL_TEXTURE_2D);
 968         j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 969 
 970         if (oglc->blitTextureID == 0) {
 971             if (!OGLContext_InitBlitTileTexture(oglc)) {
 972                 return JNI_FALSE;
 973             }
 974         }
 975 
 976         if (!OGLTR_EnableLCDGlyphModeState(oglc->blitTextureID, contrast)) {
 977             return JNI_FALSE;
 978         }
 979 
 980         // when a fragment shader is enabled, the texture function state is
 981         // ignored, so the following line is not needed...
 982         // OGLC_UPDATE_TEXTURE_FUNCTION(oglc, GL_MODULATE);
 983 
 984         glyphMode = MODE_NO_CACHE_LCD;
 985     }
 986 
 987     // rowBytes will always be a multiple of 3, so the following is safe
 988     j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, ginfo->rowBytes / 3);
 989 
 990     x0 = x;
 991     tx1 = 0.0f;
 992     ty1 = 0.0f;
 993     dtx1 = 0.0f;
 994     dty2 = 0.0f;
 995     tw = OGLTR_NOCACHE_TILE_SIZE;
 996     th = OGLTR_NOCACHE_TILE_SIZE;
 997 
 998     for (sy = 0; sy < h; sy += th, y += th) {
 999         x = x0;
1000         sh = ((sy + th) > h) ? (h - sy) : th;
1001 
1002         for (sx = 0; sx < w; sx += tw, x += tw) {
1003             sw = ((sx + tw) > w) ? (w - sx) : tw;
1004 
1005             // update the source pointer offsets
1006             j2d_glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
1007             j2d_glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
1008 
1009             // copy LCD mask into glyph texture tile
1010             j2d_glActiveTextureARB(GL_TEXTURE0_ARB);
1011             j2d_glTexSubImage2D(GL_TEXTURE_2D, 0,
1012                                 0, 0, sw, sh,
1013                                 pixelFormat, GL_UNSIGNED_BYTE,
1014                                 ginfo->image + rowBytesOffset);
1015 
1016             // update the lower-right glyph texture coordinates
1017             tx2 = ((GLfloat)sw) / OGLC_BLIT_TILE_SIZE;
1018             ty2 = ((GLfloat)sh) / OGLC_BLIT_TILE_SIZE;
1019 
1020             // this accounts for lower-left origin of the destination region
1021             dxadj = dstOps->xOffset + x;
1022             dyadj = dstOps->yOffset + dstOps->height - (y + sh);
1023 
1024             // copy destination into cached texture tile (the lower-left
1025             // corner of the destination region will be positioned at the
1026             // lower-left corner (0,0) of the texture)
1027             j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
1028             j2d_glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
1029                                     0, 0,
1030                                     dxadj, dyadj,
1031                                     sw, sh);
1032 
1033             // update the remaining destination texture coordinates
1034             dtx2 = ((GLfloat)sw) / OGLTR_CACHED_DEST_WIDTH;
1035             dty1 = ((GLfloat)sh) / OGLTR_CACHED_DEST_HEIGHT;
1036 
1037             // render composed texture to the destination surface
1038             j2d_glBegin(GL_QUADS);
1039             j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, tx1, ty1);
1040             j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx1, dty1);
1041             j2d_glVertex2i(x, y);
1042             j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, tx2, ty1);
1043             j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx2, dty1);
1044             j2d_glVertex2i(x + sw, y);
1045             j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, tx2, ty2);
1046             j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx2, dty2);
1047             j2d_glVertex2i(x + sw, y + sh);
1048             j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, tx1, ty2);
1049             j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx1, dty2);
1050             j2d_glVertex2i(x, y + sh);
1051             j2d_glEnd();
1052         }
1053     }
1054 
1055     return JNI_TRUE;
1056 }
1057 
1058 // see DrawGlyphList.c for more on this macro...
1059 #define FLOOR_ASSIGN(l, r) \
1060     if ((r)<0) (l) = ((int)floor(r)); else (l) = ((int)(r))
1061 
1062 void
1063 OGLTR_DrawGlyphList(JNIEnv *env, OGLContext *oglc, OGLSDOps *dstOps,
1064                     jint totalGlyphs, jboolean usePositions,
1065                     jboolean subPixPos, jboolean rgbOrder, jint lcdContrast,
1066                     jfloat glyphListOrigX, jfloat glyphListOrigY,
1067                     unsigned char *images, unsigned char *positions)
1068 {
1069     int glyphCounter;
1070 
1071     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_DrawGlyphList");
1072 
1073     RETURN_IF_NULL(oglc);
1074     RETURN_IF_NULL(dstOps);
1075     RETURN_IF_NULL(images);
1076     if (usePositions) {
1077         RETURN_IF_NULL(positions);
1078     }
1079 
1080     glyphMode = MODE_NOT_INITED;
1081     isCachedDestValid = JNI_FALSE;
1082 
1083     for (glyphCounter = 0; glyphCounter < totalGlyphs; glyphCounter++) {
1084         jint x, y;
1085         jfloat glyphx, glyphy;
1086         jboolean grayscale, ok;
1087         GlyphInfo *ginfo = (GlyphInfo *)jlong_to_ptr(NEXT_LONG(images));
1088 
1089         if (ginfo == NULL) {
1090             // this shouldn't happen, but if it does we'll just break out...
1091             J2dRlsTraceLn(J2D_TRACE_ERROR,
1092                           "OGLTR_DrawGlyphList: glyph info is null");
1093             break;
1094         }
1095 
1096         grayscale = (ginfo->rowBytes == ginfo->width);
1097 
1098         if (usePositions) {
1099             jfloat posx = NEXT_FLOAT(positions);
1100             jfloat posy = NEXT_FLOAT(positions);
1101             glyphx = glyphListOrigX + posx + ginfo->topLeftX;
1102             glyphy = glyphListOrigY + posy + ginfo->topLeftY;
1103             FLOOR_ASSIGN(x, glyphx);
1104             FLOOR_ASSIGN(y, glyphy);
1105         } else {
1106             glyphx = glyphListOrigX + ginfo->topLeftX;
1107             glyphy = glyphListOrigY + ginfo->topLeftY;
1108             FLOOR_ASSIGN(x, glyphx);
1109             FLOOR_ASSIGN(y, glyphy);
1110             glyphListOrigX += ginfo->advanceX;
1111             glyphListOrigY += ginfo->advanceY;
1112         }
1113 
1114         if (ginfo->image == NULL) {
1115             continue;
1116         }
1117 
1118         if (grayscale) {
1119             // grayscale or monochrome glyph data
1120             if (cacheStatus != CACHE_LCD &&
1121                 ginfo->width <= OGLTR_CACHE_CELL_WIDTH &&
1122                 ginfo->height <= OGLTR_CACHE_CELL_HEIGHT)
1123             {
1124                 ok = OGLTR_DrawGrayscaleGlyphViaCache(oglc, ginfo, x, y);
1125             } else {
1126                 ok = OGLTR_DrawGrayscaleGlyphNoCache(oglc, ginfo, x, y);
1127             }
1128         } else {
1129             // LCD-optimized glyph data
1130             jint rowBytesOffset = 0;
1131 
1132             if (subPixPos) {
1133                 jint frac = (jint)((glyphx - x) * 3);
1134                 if (frac != 0) {
1135                     rowBytesOffset = 3 - frac;
1136                     x += 1;
1137                 }
1138             }
1139 
1140             if (rowBytesOffset == 0 &&
1141                 cacheStatus != CACHE_GRAY &&
1142                 ginfo->width <= OGLTR_CACHE_CELL_WIDTH &&
1143                 ginfo->height <= OGLTR_CACHE_CELL_HEIGHT)
1144             {
1145                 ok = OGLTR_DrawLCDGlyphViaCache(oglc, dstOps,
1146                                                 ginfo, x, y,
1147                                                 glyphCounter, totalGlyphs,
1148                                                 rgbOrder, lcdContrast);
1149             } else {
1150                 ok = OGLTR_DrawLCDGlyphNoCache(oglc, dstOps,
1151                                                ginfo, x, y,
1152                                                rowBytesOffset,
1153                                                rgbOrder, lcdContrast);
1154             }
1155         }
1156 
1157         if (!ok) {
1158             break;
1159         }
1160     }
1161 
1162     OGLTR_DisableGlyphModeState();
1163 }
1164 
1165 JNIEXPORT void JNICALL
1166 Java_sun_java2d_opengl_OGLTextRenderer_drawGlyphList
1167     (JNIEnv *env, jobject self,
1168      jint numGlyphs, jboolean usePositions,
1169      jboolean subPixPos, jboolean rgbOrder, jint lcdContrast,
1170      jfloat glyphListOrigX, jfloat glyphListOrigY,
1171      jlongArray imgArray, jfloatArray posArray)
1172 {
1173     unsigned char *images;
1174 
1175     J2dTraceLn(J2D_TRACE_INFO, "OGLTextRenderer_drawGlyphList");
1176 
1177     images = (unsigned char *)
1178         (*env)->GetPrimitiveArrayCritical(env, imgArray, NULL);
1179     if (images != NULL) {
1180         OGLContext *oglc = OGLRenderQueue_GetCurrentContext();
1181         OGLSDOps *dstOps = OGLRenderQueue_GetCurrentDestination();
1182 
1183         if (usePositions) {
1184             unsigned char *positions = (unsigned char *)
1185                 (*env)->GetPrimitiveArrayCritical(env, posArray, NULL);
1186             if (positions != NULL) {
1187                 OGLTR_DrawGlyphList(env, oglc, dstOps,
1188                                     numGlyphs, usePositions,
1189                                     subPixPos, rgbOrder, lcdContrast,
1190                                     glyphListOrigX, glyphListOrigY,
1191                                     images, positions);
1192                 (*env)->ReleasePrimitiveArrayCritical(env, posArray,
1193                                                       positions, JNI_ABORT);
1194             }
1195         } else {
1196             OGLTR_DrawGlyphList(env, oglc, dstOps,
1197                                 numGlyphs, usePositions,
1198                                 subPixPos, rgbOrder, lcdContrast,
1199                                 glyphListOrigX, glyphListOrigY,
1200                                 images, NULL);
1201         }
1202 
1203         // 6358147: reset current state, and ensure rendering is
1204         // flushed to dest
1205         if (oglc != NULL) {
1206             RESET_PREVIOUS_OP();
1207             j2d_glFlush();
1208         }
1209 
1210         (*env)->ReleasePrimitiveArrayCritical(env, imgArray,
1211                                               images, JNI_ABORT);
1212     }
1213 }
1214 
1215 #endif /* !HEADLESS */
--- EOF ---