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_clr" 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 vec4 src_clr;"
 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 RGBA value from the corresponding destination pixel
 314     "    vec4 dst_clr = vec4(texture2D(dst_tex, gl_TexCoord[1].st));"
 315          // blend src and dst colors as SrcOverNoEa
 316     "    vec3 src_comp = vec3(src_clr.rgb + ((1.0 - src_clr.a) * dst_clr.rgb));"
 317          // gamma adjust the blended src color using the invgamma LUT
 318     "    vec3 src_adj = vec3(texture3D(invgamma_tex, src_comp));"
 319          // gamma adjust the dest color using the invgamma LUT
 320     "    vec3 dst_adj = vec3(texture3D(invgamma_tex, dst_clr.rgb));"
 321          // linearly interpolate the three color values
 322     "    vec3 result = mix(dst_adj, src_adj, glyph_clr);"
 323          // calculate the resulting alpha
 324     "    dst_clr.a = src_clr.a + (1.0 - src_clr.a) * dst_clr.a;"
 325          // gamma re-adjust the resulting color
 326     "    gl_FragColor = vec4(vec3(texture3D(gamma_tex, result.rgb)), dst_clr.a);"
 327     "}";
 328 
 329 /**
 330  * Compiles and links the LCD text shader program.  If successful, this
 331  * function returns a handle to the newly created shader program; otherwise
 332  * returns 0.
 333  */
 334 static GLhandleARB
 335 OGLTR_CreateLCDTextProgram()
 336 {
 337     GLhandleARB lcdTextProgram;
 338     GLint loc;
 339 
 340     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_CreateLCDTextProgram");
 341 
 342     lcdTextProgram = OGLContext_CreateFragmentProgram(lcdTextShaderSource);
 343     if (lcdTextProgram == 0) {
 344         J2dRlsTraceLn(J2D_TRACE_ERROR,
 345                       "OGLTR_CreateLCDTextProgram: error creating program");
 346         return 0;
 347     }
 348 
 349     // "use" the program object temporarily so that we can set the uniforms
 350     j2d_glUseProgramObjectARB(lcdTextProgram);
 351 
 352     // set the "uniform" values
 353     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "glyph_tex");
 354     j2d_glUniform1iARB(loc, 0); // texture unit 0
 355     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "dst_tex");
 356     j2d_glUniform1iARB(loc, 1); // texture unit 1
 357     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "invgamma_tex");
 358     j2d_glUniform1iARB(loc, 2); // texture unit 2
 359     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "gamma_tex");
 360     j2d_glUniform1iARB(loc, 3); // texture unit 3
 361 
 362     // "unuse" the program object; it will be re-bound later as needed
 363     j2d_glUseProgramObjectARB(0);
 364 
 365     return lcdTextProgram;
 366 }
 367 
 368 /**
 369  * Initializes a 3D texture object for use as a three-dimensional gamma
 370  * lookup table.  Note that the wrap mode is initialized to GL_LINEAR so
 371  * that the table will interpolate adjacent values when the index falls
 372  * somewhere in between.
 373  */
 374 static GLuint
 375 OGLTR_InitGammaLutTexture()
 376 {
 377     GLuint lutTextureID;
 378 
 379     j2d_glGenTextures(1, &lutTextureID);
 380     j2d_glBindTexture(GL_TEXTURE_3D, lutTextureID);
 381     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 382     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 383     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
 384     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
 385     j2d_glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
 386 
 387     return lutTextureID;
 388 }
 389 
 390 /**
 391  * Updates the lookup table in the given texture object with the float
 392  * values in the given system memory buffer.  Note that we could use
 393  * glTexSubImage3D() when updating the texture after its first
 394  * initialization, but since we're updating the entire table (with
 395  * power-of-two dimensions) and this is a relatively rare event, we'll
 396  * just stick with glTexImage3D().
 397  */
 398 static void
 399 OGLTR_UpdateGammaLutTexture(GLuint texID, GLfloat *lut, jint size)
 400 {
 401     j2d_glBindTexture(GL_TEXTURE_3D, texID);
 402     j2d_glTexImage3D(GL_TEXTURE_3D, 0, GL_RGB8,
 403                      size, size, size, 0, GL_RGB, GL_FLOAT, lut);
 404 }
 405 
 406 /**
 407  * (Re)Initializes the gamma lookup table textures.
 408  *
 409  * The given contrast value is an int in the range [100, 250] which we will
 410  * then scale to fit in the range [1.0, 2.5].  We create two LUTs, one
 411  * that essentially calculates pow(x, gamma) and the other calculates
 412  * pow(x, 1/gamma).  These values are replicated in all three dimensions, so
 413  * given a single 3D texture coordinate (typically this will be a triplet
 414  * in the form (r,g,b)), the 3D texture lookup will return an RGB triplet:
 415  *
 416  *     (pow(r,g), pow(y,g), pow(z,g)
 417  *
 418  * where g is either gamma or 1/gamma, depending on the table.
 419  */
 420 static jboolean
 421 OGLTR_UpdateLCDTextContrast(jint contrast)
 422 {
 423     double gamma = ((double)contrast) / 100.0;
 424     double ig = gamma;
 425     double g = 1.0 / ig;
 426     GLfloat lut[LUT_EDGE][LUT_EDGE][LUT_EDGE][3];
 427     GLfloat invlut[LUT_EDGE][LUT_EDGE][LUT_EDGE][3];
 428     int min = 0;
 429     int max = LUT_EDGE - 1;
 430     int x, y, z;
 431 
 432     J2dTraceLn1(J2D_TRACE_INFO,
 433                 "OGLTR_UpdateLCDTextContrast: contrast=%d", contrast);
 434 
 435     for (z = min; z <= max; z++) {
 436         double zval = ((double)z) / max;
 437         GLfloat gz = (GLfloat)pow(zval, g);
 438         GLfloat igz = (GLfloat)pow(zval, ig);
 439 
 440         for (y = min; y <= max; y++) {
 441             double yval = ((double)y) / max;
 442             GLfloat gy = (GLfloat)pow(yval, g);
 443             GLfloat igy = (GLfloat)pow(yval, ig);
 444 
 445             for (x = min; x <= max; x++) {
 446                 double xval = ((double)x) / max;
 447                 GLfloat gx = (GLfloat)pow(xval, g);
 448                 GLfloat igx = (GLfloat)pow(xval, ig);
 449 
 450                 lut[z][y][x][0] = gx;
 451                 lut[z][y][x][1] = gy;
 452                 lut[z][y][x][2] = gz;
 453 
 454                 invlut[z][y][x][0] = igx;
 455                 invlut[z][y][x][1] = igy;
 456                 invlut[z][y][x][2] = igz;
 457             }
 458         }
 459     }
 460 
 461     if (gammaLutTextureID == 0) {
 462         gammaLutTextureID = OGLTR_InitGammaLutTexture();
 463     }
 464     OGLTR_UpdateGammaLutTexture(gammaLutTextureID, (GLfloat *)lut, LUT_EDGE);
 465 
 466     if (invGammaLutTextureID == 0) {
 467         invGammaLutTextureID = OGLTR_InitGammaLutTexture();
 468     }
 469     OGLTR_UpdateGammaLutTexture(invGammaLutTextureID,
 470                                 (GLfloat *)invlut, LUT_EDGE);
 471 
 472     return JNI_TRUE;
 473 }
 474 
 475 /**
 476  * Updates the current source color ("src_clr") of the LCD text shader program.
 477  */
 478 static jboolean
 479 OGLTR_UpdateLCDTextColor(jint contrast)
 480 {
 481     double gamma = 100.0 / ((double)contrast);
 482     GLfloat clr[4];
 483     GLint loc;
 484 
 485     J2dTraceLn1(J2D_TRACE_INFO,
 486                 "OGLTR_UpdateLCDTextColor: contrast=%d", contrast);
 487 
 488     // get the current OpenGL primary color state
 489     j2d_glGetFloatv(GL_CURRENT_COLOR, clr);
 490 
 491     // update the "src_clr" parameter of the shader program with this value
 492     loc = j2d_glGetUniformLocationARB(lcdTextProgram, "src_clr");
 493     j2d_glUniform4fARB(loc, clr[0], clr[1], clr[2], clr[3]);
 494 
 495     return JNI_TRUE;
 496 }
 497 
 498 /**
 499  * Enables the LCD text shader and updates any related state, such as the
 500  * gamma lookup table textures.
 501  */
 502 static jboolean
 503 OGLTR_EnableLCDGlyphModeState(GLuint glyphTextureID, jint contrast)
 504 {
 505     // bind the texture containing glyph data to texture unit 0
 506     j2d_glActiveTextureARB(GL_TEXTURE0_ARB);
 507     j2d_glBindTexture(GL_TEXTURE_2D, glyphTextureID);
 508 
 509     // bind the texture tile containing destination data to texture unit 1
 510     j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
 511     if (cachedDestTextureID == 0) {
 512         cachedDestTextureID =
 513             OGLContext_CreateBlitTexture(GL_RGB8, GL_RGB,
 514                                          OGLTR_CACHED_DEST_WIDTH,
 515                                          OGLTR_CACHED_DEST_HEIGHT);
 516         if (cachedDestTextureID == 0) {
 517             return JNI_FALSE;
 518         }
 519     }
 520     j2d_glBindTexture(GL_TEXTURE_2D, cachedDestTextureID);
 521 
 522     // note that GL_TEXTURE_2D was already enabled for texture unit 0,
 523     // but we need to explicitly enable it for texture unit 1
 524     j2d_glEnable(GL_TEXTURE_2D);
 525 
 526     // create the LCD text shader, if necessary
 527     if (lcdTextProgram == 0) {
 528         lcdTextProgram = OGLTR_CreateLCDTextProgram();
 529         if (lcdTextProgram == 0) {
 530             return JNI_FALSE;
 531         }
 532     }
 533 
 534     // enable the LCD text shader
 535     j2d_glUseProgramObjectARB(lcdTextProgram);
 536 
 537     // update the current contrast settings, if necessary
 538     if (lastLCDContrast != contrast) {
 539         if (!OGLTR_UpdateLCDTextContrast(contrast)) {
 540             return JNI_FALSE;
 541         }
 542         lastLCDContrast = contrast;
 543     }
 544 
 545     // update the current color settings
 546     if (!OGLTR_UpdateLCDTextColor(contrast)) {
 547         return JNI_FALSE;
 548     }
 549 
 550     // bind the gamma LUT textures
 551     j2d_glActiveTextureARB(GL_TEXTURE2_ARB);
 552     j2d_glBindTexture(GL_TEXTURE_3D, invGammaLutTextureID);
 553     j2d_glEnable(GL_TEXTURE_3D);
 554     j2d_glActiveTextureARB(GL_TEXTURE3_ARB);
 555     j2d_glBindTexture(GL_TEXTURE_3D, gammaLutTextureID);
 556     j2d_glEnable(GL_TEXTURE_3D);
 557 
 558     return JNI_TRUE;
 559 }
 560 
 561 void
 562 OGLTR_EnableGlyphVertexCache(OGLContext *oglc)
 563 {
 564     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_EnableGlyphVertexCache");
 565 
 566     if (!OGLVertexCache_InitVertexCache(oglc)) {
 567         return;
 568     }
 569 
 570     if (glyphCache == NULL) {
 571         if (!OGLTR_InitGlyphCache(JNI_FALSE)) {
 572             return;
 573         }
 574     }
 575 
 576     j2d_glEnable(GL_TEXTURE_2D);
 577     j2d_glBindTexture(GL_TEXTURE_2D, glyphCache->cacheID);
 578     j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 579 
 580     // for grayscale/monochrome text, the current OpenGL source color
 581     // is modulated with the glyph image as part of the texture
 582     // application stage, so we use GL_MODULATE here
 583     OGLC_UPDATE_TEXTURE_FUNCTION(oglc, GL_MODULATE);
 584 }
 585 
 586 void
 587 OGLTR_DisableGlyphVertexCache(OGLContext *oglc)
 588 {
 589     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_DisableGlyphVertexCache");
 590 
 591     OGLVertexCache_FlushVertexCache();
 592     OGLVertexCache_RestoreColorState(oglc);
 593 
 594     j2d_glDisable(GL_TEXTURE_2D);
 595     j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
 596     j2d_glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
 597     j2d_glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
 598     j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
 599 }
 600 
 601 /**
 602  * Disables any pending state associated with the current "glyph mode".
 603  */
 604 static void
 605 OGLTR_DisableGlyphModeState()
 606 {
 607     switch (glyphMode) {
 608     case MODE_NO_CACHE_LCD:
 609         j2d_glPixelStorei(GL_UNPACK_SKIP_PIXELS, 0);
 610         j2d_glPixelStorei(GL_UNPACK_SKIP_ROWS, 0);
 611         /* FALLTHROUGH */
 612 
 613     case MODE_USE_CACHE_LCD:
 614         j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
 615         j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
 616         j2d_glUseProgramObjectARB(0);
 617         j2d_glActiveTextureARB(GL_TEXTURE3_ARB);
 618         j2d_glDisable(GL_TEXTURE_3D);
 619         j2d_glActiveTextureARB(GL_TEXTURE2_ARB);
 620         j2d_glDisable(GL_TEXTURE_3D);
 621         j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
 622         j2d_glDisable(GL_TEXTURE_2D);
 623         j2d_glActiveTextureARB(GL_TEXTURE0_ARB);
 624         break;
 625 
 626     case MODE_NO_CACHE_GRAY:
 627     case MODE_USE_CACHE_GRAY:
 628     case MODE_NOT_INITED:
 629     default:
 630         break;
 631     }
 632 }
 633 
 634 static jboolean
 635 OGLTR_DrawGrayscaleGlyphViaCache(OGLContext *oglc,
 636                                  GlyphInfo *ginfo, jint x, jint y)
 637 {
 638     CacheCellInfo *cell;
 639     jfloat x1, y1, x2, y2;
 640 
 641     if (glyphMode != MODE_USE_CACHE_GRAY) {
 642         OGLTR_DisableGlyphModeState();
 643         CHECK_PREVIOUS_OP(OGL_STATE_GLYPH_OP);
 644         glyphMode = MODE_USE_CACHE_GRAY;
 645     }
 646 
 647     if (ginfo->cellInfo == NULL) {
 648         // attempt to add glyph to accelerated glyph cache
 649         OGLTR_AddToGlyphCache(ginfo, JNI_FALSE);
 650 
 651         if (ginfo->cellInfo == NULL) {
 652             // we'll just no-op in the rare case that the cell is NULL
 653             return JNI_TRUE;
 654         }
 655     }
 656 
 657     cell = (CacheCellInfo *) (ginfo->cellInfo);
 658     cell->timesRendered++;
 659 
 660     x1 = (jfloat)x;
 661     y1 = (jfloat)y;
 662     x2 = x1 + ginfo->width;
 663     y2 = y1 + ginfo->height;
 664 
 665     OGLVertexCache_AddGlyphQuad(oglc,
 666                                 cell->tx1, cell->ty1,
 667                                 cell->tx2, cell->ty2,
 668                                 x1, y1, x2, y2);
 669 
 670     return JNI_TRUE;
 671 }
 672 
 673 /**
 674  * Evaluates to true if the rectangle defined by gx1/gy1/gx2/gy2 is
 675  * inside outerBounds.
 676  */
 677 #define INSIDE(gx1, gy1, gx2, gy2, outerBounds) \
 678     (((gx1) >= outerBounds.x1) && ((gy1) >= outerBounds.y1) && \
 679      ((gx2) <= outerBounds.x2) && ((gy2) <= outerBounds.y2))
 680 
 681 /**
 682  * Evaluates to true if the rectangle defined by gx1/gy1/gx2/gy2 intersects
 683  * the rectangle defined by bounds.
 684  */
 685 #define INTERSECTS(gx1, gy1, gx2, gy2, bounds) \
 686     ((bounds.x2 > (gx1)) && (bounds.y2 > (gy1)) && \
 687      (bounds.x1 < (gx2)) && (bounds.y1 < (gy2)))
 688 
 689 /**
 690  * This method checks to see if the given LCD glyph bounds fall within the
 691  * cached destination texture bounds.  If so, this method can return
 692  * immediately.  If not, this method will copy a chunk of framebuffer data
 693  * into the cached destination texture and then update the current cached
 694  * destination bounds before returning.
 695  */
 696 static void
 697 OGLTR_UpdateCachedDestination(OGLSDOps *dstOps, GlyphInfo *ginfo,
 698                               jint gx1, jint gy1, jint gx2, jint gy2,
 699                               jint glyphIndex, jint totalGlyphs)
 700 {
 701     jint dx1, dy1, dx2, dy2;
 702     jint dx1adj, dy1adj;
 703 
 704     if (isCachedDestValid && INSIDE(gx1, gy1, gx2, gy2, cachedDestBounds)) {
 705         // glyph is already within the cached destination bounds; no need
 706         // to read back the entire destination region again, but we do
 707         // need to see if the current glyph overlaps the previous glyph...
 708 
 709         if (INTERSECTS(gx1, gy1, gx2, gy2, previousGlyphBounds)) {
 710             // the current glyph overlaps the destination region touched
 711             // by the previous glyph, so now we need to read back the part
 712             // of the destination corresponding to the previous glyph
 713             dx1 = previousGlyphBounds.x1;
 714             dy1 = previousGlyphBounds.y1;
 715             dx2 = previousGlyphBounds.x2;
 716             dy2 = previousGlyphBounds.y2;
 717 
 718             // this accounts for lower-left origin of the destination region
 719             dx1adj = dstOps->xOffset + dx1;
 720             dy1adj = dstOps->yOffset + dstOps->height - dy2;
 721 
 722             // copy destination into subregion of cached texture tile:
 723             //   dx1-cachedDestBounds.x1 == +xoffset from left side of texture
 724             //   cachedDestBounds.y2-dy2 == +yoffset from bottom of texture
 725             j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
 726             j2d_glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
 727                                     dx1 - cachedDestBounds.x1,
 728                                     cachedDestBounds.y2 - dy2,
 729                                     dx1adj, dy1adj,
 730                                     dx2-dx1, dy2-dy1);
 731         }
 732     } else {
 733         jint remainingWidth;
 734 
 735         // destination region is not valid, so we need to read back a
 736         // chunk of the destination into our cached texture
 737 
 738         // position the upper-left corner of the destination region on the
 739         // "top" line of glyph list
 740         // REMIND: this isn't ideal; it would be better if we had some idea
 741         //         of the bounding box of the whole glyph list (this is
 742         //         do-able, but would require iterating through the whole
 743         //         list up front, which may present its own problems)
 744         dx1 = gx1;
 745         dy1 = gy1;
 746 
 747         if (ginfo->advanceX > 0) {
 748             // estimate the width based on our current position in the glyph
 749             // list and using the x advance of the current glyph (this is just
 750             // a quick and dirty heuristic; if this is a "thin" glyph image,
 751             // then we're likely to underestimate, and if it's "thick" then we
 752             // may end up reading back more than we need to)
 753             remainingWidth =
 754                 (jint)(ginfo->advanceX * (totalGlyphs - glyphIndex));
 755             if (remainingWidth > OGLTR_CACHED_DEST_WIDTH) {
 756                 remainingWidth = OGLTR_CACHED_DEST_WIDTH;
 757             } else if (remainingWidth < ginfo->width) {
 758                 // in some cases, the x-advance may be slightly smaller
 759                 // than the actual width of the glyph; if so, adjust our
 760                 // estimate so that we can accommodate the entire glyph
 761                 remainingWidth = ginfo->width;
 762             }
 763         } else {
 764             // a negative advance is possible when rendering rotated text,
 765             // in which case it is difficult to estimate an appropriate
 766             // region for readback, so we will pick a region that
 767             // encompasses just the current glyph
 768             remainingWidth = ginfo->width;
 769         }
 770         dx2 = dx1 + remainingWidth;
 771 
 772         // estimate the height (this is another sloppy heuristic; we'll
 773         // make the cached destination region tall enough to encompass most
 774         // glyphs that are small enough to fit in the glyph cache, and then
 775         // we add a little something extra to account for descenders
 776         dy2 = dy1 + OGLTR_CACHE_CELL_HEIGHT + 2;
 777 
 778         // this accounts for lower-left origin of the destination region
 779         dx1adj = dstOps->xOffset + dx1;
 780         dy1adj = dstOps->yOffset + dstOps->height - dy2;
 781 
 782         // copy destination into cached texture tile (the lower-left corner
 783         // of the destination region will be positioned at the lower-left
 784         // corner (0,0) of the texture)
 785         j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
 786         j2d_glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
 787                                 0, 0, dx1adj, dy1adj,
 788                                 dx2-dx1, dy2-dy1);
 789 
 790         // update the cached bounds and mark it valid
 791         cachedDestBounds.x1 = dx1;
 792         cachedDestBounds.y1 = dy1;
 793         cachedDestBounds.x2 = dx2;
 794         cachedDestBounds.y2 = dy2;
 795         isCachedDestValid = JNI_TRUE;
 796     }
 797 
 798     // always update the previous glyph bounds
 799     previousGlyphBounds.x1 = gx1;
 800     previousGlyphBounds.y1 = gy1;
 801     previousGlyphBounds.x2 = gx2;
 802     previousGlyphBounds.y2 = gy2;
 803 }
 804 
 805 static jboolean
 806 OGLTR_DrawLCDGlyphViaCache(OGLContext *oglc, OGLSDOps *dstOps,
 807                            GlyphInfo *ginfo, jint x, jint y,
 808                            jint glyphIndex, jint totalGlyphs,
 809                            jboolean rgbOrder, jint contrast)
 810 {
 811     CacheCellInfo *cell;
 812     jint dx1, dy1, dx2, dy2;
 813     jfloat dtx1, dty1, dtx2, dty2;
 814 
 815     if (glyphMode != MODE_USE_CACHE_LCD) {
 816         OGLTR_DisableGlyphModeState();
 817         CHECK_PREVIOUS_OP(GL_TEXTURE_2D);
 818         j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 819 
 820         if (glyphCache == NULL) {
 821             if (!OGLTR_InitGlyphCache(JNI_TRUE)) {
 822                 return JNI_FALSE;
 823             }
 824         }
 825 
 826         if (rgbOrder != lastRGBOrder) {
 827             // need to invalidate the cache in this case; see comments
 828             // for lastRGBOrder above
 829             AccelGlyphCache_Invalidate(glyphCache);
 830             lastRGBOrder = rgbOrder;
 831         }
 832 
 833         if (!OGLTR_EnableLCDGlyphModeState(glyphCache->cacheID, contrast)) {
 834             return JNI_FALSE;
 835         }
 836 
 837         // when a fragment shader is enabled, the texture function state is
 838         // ignored, so the following line is not needed...
 839         // OGLC_UPDATE_TEXTURE_FUNCTION(oglc, GL_MODULATE);
 840 
 841         glyphMode = MODE_USE_CACHE_LCD;
 842     }
 843 
 844     if (ginfo->cellInfo == NULL) {
 845         // rowBytes will always be a multiple of 3, so the following is safe
 846         j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, ginfo->rowBytes / 3);
 847 
 848         // make sure the glyph cache texture is bound to texture unit 0
 849         j2d_glActiveTextureARB(GL_TEXTURE0_ARB);
 850 
 851         // attempt to add glyph to accelerated glyph cache
 852         OGLTR_AddToGlyphCache(ginfo, rgbOrder);
 853 
 854         if (ginfo->cellInfo == NULL) {
 855             // we'll just no-op in the rare case that the cell is NULL
 856             return JNI_TRUE;
 857         }
 858     }
 859 
 860     cell = (CacheCellInfo *) (ginfo->cellInfo);
 861     cell->timesRendered++;
 862 
 863     // location of the glyph in the destination's coordinate space
 864     dx1 = x;
 865     dy1 = y;
 866     dx2 = dx1 + ginfo->width;
 867     dy2 = dy1 + ginfo->height;
 868 
 869     // copy destination into second cached texture, if necessary
 870     OGLTR_UpdateCachedDestination(dstOps, ginfo,
 871                                   dx1, dy1, dx2, dy2,
 872                                   glyphIndex, totalGlyphs);
 873 
 874     // texture coordinates of the destination tile
 875     dtx1 = ((jfloat)(dx1 - cachedDestBounds.x1)) / OGLTR_CACHED_DEST_WIDTH;
 876     dty1 = ((jfloat)(cachedDestBounds.y2 - dy1)) / OGLTR_CACHED_DEST_HEIGHT;
 877     dtx2 = ((jfloat)(dx2 - cachedDestBounds.x1)) / OGLTR_CACHED_DEST_WIDTH;
 878     dty2 = ((jfloat)(cachedDestBounds.y2 - dy2)) / OGLTR_CACHED_DEST_HEIGHT;
 879 
 880     // render composed texture to the destination surface
 881     j2d_glBegin(GL_QUADS);
 882     j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, cell->tx1, cell->ty1);
 883     j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx1, dty1);
 884     j2d_glVertex2i(dx1, dy1);
 885     j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, cell->tx2, cell->ty1);
 886     j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx2, dty1);
 887     j2d_glVertex2i(dx2, dy1);
 888     j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, cell->tx2, cell->ty2);
 889     j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx2, dty2);
 890     j2d_glVertex2i(dx2, dy2);
 891     j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, cell->tx1, cell->ty2);
 892     j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx1, dty2);
 893     j2d_glVertex2i(dx1, dy2);
 894     j2d_glEnd();
 895 
 896     return JNI_TRUE;
 897 }
 898 
 899 static jboolean
 900 OGLTR_DrawGrayscaleGlyphNoCache(OGLContext *oglc,
 901                                 GlyphInfo *ginfo, jint x, jint y)
 902 {
 903     jint tw, th;
 904     jint sx, sy, sw, sh;
 905     jint x0;
 906     jint w = ginfo->width;
 907     jint h = ginfo->height;
 908 
 909     if (glyphMode != MODE_NO_CACHE_GRAY) {
 910         OGLTR_DisableGlyphModeState();
 911         CHECK_PREVIOUS_OP(OGL_STATE_MASK_OP);
 912         glyphMode = MODE_NO_CACHE_GRAY;
 913     }
 914 
 915     x0 = x;
 916     tw = OGLVC_MASK_CACHE_TILE_WIDTH;
 917     th = OGLVC_MASK_CACHE_TILE_HEIGHT;
 918 
 919     for (sy = 0; sy < h; sy += th, y += th) {
 920         x = x0;
 921         sh = ((sy + th) > h) ? (h - sy) : th;
 922 
 923         for (sx = 0; sx < w; sx += tw, x += tw) {
 924             sw = ((sx + tw) > w) ? (w - sx) : tw;
 925 
 926             OGLVertexCache_AddMaskQuad(oglc,
 927                                        sx, sy, x, y, sw, sh,
 928                                        w, ginfo->image);
 929         }
 930     }
 931 
 932     return JNI_TRUE;
 933 }
 934 
 935 static jboolean
 936 OGLTR_DrawLCDGlyphNoCache(OGLContext *oglc, OGLSDOps *dstOps,
 937                           GlyphInfo *ginfo, jint x, jint y,
 938                           jint rowBytesOffset,
 939                           jboolean rgbOrder, jint contrast)
 940 {
 941     GLfloat tx1, ty1, tx2, ty2;
 942     GLfloat dtx1, dty1, dtx2, dty2;
 943     jint tw, th;
 944     jint sx, sy, sw, sh, dxadj, dyadj;
 945     jint x0;
 946     jint w = ginfo->width;
 947     jint h = ginfo->height;
 948     GLenum pixelFormat = rgbOrder ? GL_RGB : GL_BGR;
 949 
 950     if (glyphMode != MODE_NO_CACHE_LCD) {
 951         OGLTR_DisableGlyphModeState();
 952         CHECK_PREVIOUS_OP(GL_TEXTURE_2D);
 953         j2d_glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
 954 
 955         if (oglc->blitTextureID == 0) {
 956             if (!OGLContext_InitBlitTileTexture(oglc)) {
 957                 return JNI_FALSE;
 958             }
 959         }
 960 
 961         if (!OGLTR_EnableLCDGlyphModeState(oglc->blitTextureID, contrast)) {
 962             return JNI_FALSE;
 963         }
 964 
 965         // when a fragment shader is enabled, the texture function state is
 966         // ignored, so the following line is not needed...
 967         // OGLC_UPDATE_TEXTURE_FUNCTION(oglc, GL_MODULATE);
 968 
 969         glyphMode = MODE_NO_CACHE_LCD;
 970     }
 971 
 972     // rowBytes will always be a multiple of 3, so the following is safe
 973     j2d_glPixelStorei(GL_UNPACK_ROW_LENGTH, ginfo->rowBytes / 3);
 974 
 975     x0 = x;
 976     tx1 = 0.0f;
 977     ty1 = 0.0f;
 978     dtx1 = 0.0f;
 979     dty2 = 0.0f;
 980     tw = OGLTR_NOCACHE_TILE_SIZE;
 981     th = OGLTR_NOCACHE_TILE_SIZE;
 982 
 983     for (sy = 0; sy < h; sy += th, y += th) {
 984         x = x0;
 985         sh = ((sy + th) > h) ? (h - sy) : th;
 986 
 987         for (sx = 0; sx < w; sx += tw, x += tw) {
 988             sw = ((sx + tw) > w) ? (w - sx) : tw;
 989 
 990             // update the source pointer offsets
 991             j2d_glPixelStorei(GL_UNPACK_SKIP_PIXELS, sx);
 992             j2d_glPixelStorei(GL_UNPACK_SKIP_ROWS, sy);
 993 
 994             // copy LCD mask into glyph texture tile
 995             j2d_glActiveTextureARB(GL_TEXTURE0_ARB);
 996             j2d_glTexSubImage2D(GL_TEXTURE_2D, 0,
 997                                 0, 0, sw, sh,
 998                                 pixelFormat, GL_UNSIGNED_BYTE,
 999                                 ginfo->image + rowBytesOffset);
1000 
1001             // update the lower-right glyph texture coordinates
1002             tx2 = ((GLfloat)sw) / OGLC_BLIT_TILE_SIZE;
1003             ty2 = ((GLfloat)sh) / OGLC_BLIT_TILE_SIZE;
1004 
1005             // this accounts for lower-left origin of the destination region
1006             dxadj = dstOps->xOffset + x;
1007             dyadj = dstOps->yOffset + dstOps->height - (y + sh);
1008 
1009             // copy destination into cached texture tile (the lower-left
1010             // corner of the destination region will be positioned at the
1011             // lower-left corner (0,0) of the texture)
1012             j2d_glActiveTextureARB(GL_TEXTURE1_ARB);
1013             j2d_glCopyTexSubImage2D(GL_TEXTURE_2D, 0,
1014                                     0, 0,
1015                                     dxadj, dyadj,
1016                                     sw, sh);
1017 
1018             // update the remaining destination texture coordinates
1019             dtx2 = ((GLfloat)sw) / OGLTR_CACHED_DEST_WIDTH;
1020             dty1 = ((GLfloat)sh) / OGLTR_CACHED_DEST_HEIGHT;
1021 
1022             // render composed texture to the destination surface
1023             j2d_glBegin(GL_QUADS);
1024             j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, tx1, ty1);
1025             j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx1, dty1);
1026             j2d_glVertex2i(x, y);
1027             j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, tx2, ty1);
1028             j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx2, dty1);
1029             j2d_glVertex2i(x + sw, y);
1030             j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, tx2, ty2);
1031             j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx2, dty2);
1032             j2d_glVertex2i(x + sw, y + sh);
1033             j2d_glMultiTexCoord2fARB(GL_TEXTURE0_ARB, tx1, ty2);
1034             j2d_glMultiTexCoord2fARB(GL_TEXTURE1_ARB, dtx1, dty2);
1035             j2d_glVertex2i(x, y + sh);
1036             j2d_glEnd();
1037         }
1038     }
1039 
1040     return JNI_TRUE;
1041 }
1042 
1043 // see DrawGlyphList.c for more on this macro...
1044 #define FLOOR_ASSIGN(l, r) \
1045     if ((r)<0) (l) = ((int)floor(r)); else (l) = ((int)(r))
1046 
1047 void
1048 OGLTR_DrawGlyphList(JNIEnv *env, OGLContext *oglc, OGLSDOps *dstOps,
1049                     jint totalGlyphs, jboolean usePositions,
1050                     jboolean subPixPos, jboolean rgbOrder, jint lcdContrast,
1051                     jfloat glyphListOrigX, jfloat glyphListOrigY,
1052                     unsigned char *images, unsigned char *positions)
1053 {
1054     int glyphCounter;
1055 
1056     J2dTraceLn(J2D_TRACE_INFO, "OGLTR_DrawGlyphList");
1057 
1058     RETURN_IF_NULL(oglc);
1059     RETURN_IF_NULL(dstOps);
1060     RETURN_IF_NULL(images);
1061     if (usePositions) {
1062         RETURN_IF_NULL(positions);
1063     }
1064 
1065     glyphMode = MODE_NOT_INITED;
1066     isCachedDestValid = JNI_FALSE;
1067 
1068     for (glyphCounter = 0; glyphCounter < totalGlyphs; glyphCounter++) {
1069         jint x, y;
1070         jfloat glyphx, glyphy;
1071         jboolean grayscale, ok;
1072         GlyphInfo *ginfo = (GlyphInfo *)jlong_to_ptr(NEXT_LONG(images));
1073 
1074         if (ginfo == NULL) {
1075             // this shouldn't happen, but if it does we'll just break out...
1076             J2dRlsTraceLn(J2D_TRACE_ERROR,
1077                           "OGLTR_DrawGlyphList: glyph info is null");
1078             break;
1079         }
1080 
1081         grayscale = (ginfo->rowBytes == ginfo->width);
1082 
1083         if (usePositions) {
1084             jfloat posx = NEXT_FLOAT(positions);
1085             jfloat posy = NEXT_FLOAT(positions);
1086             glyphx = glyphListOrigX + posx + ginfo->topLeftX;
1087             glyphy = glyphListOrigY + posy + ginfo->topLeftY;
1088             FLOOR_ASSIGN(x, glyphx);
1089             FLOOR_ASSIGN(y, glyphy);
1090         } else {
1091             glyphx = glyphListOrigX + ginfo->topLeftX;
1092             glyphy = glyphListOrigY + ginfo->topLeftY;
1093             FLOOR_ASSIGN(x, glyphx);
1094             FLOOR_ASSIGN(y, glyphy);
1095             glyphListOrigX += ginfo->advanceX;
1096             glyphListOrigY += ginfo->advanceY;
1097         }
1098 
1099         if (ginfo->image == NULL) {
1100             continue;
1101         }
1102 
1103         if (grayscale) {
1104             // grayscale or monochrome glyph data
1105             if (cacheStatus != CACHE_LCD &&
1106                 ginfo->width <= OGLTR_CACHE_CELL_WIDTH &&
1107                 ginfo->height <= OGLTR_CACHE_CELL_HEIGHT)
1108             {
1109                 ok = OGLTR_DrawGrayscaleGlyphViaCache(oglc, ginfo, x, y);
1110             } else {
1111                 ok = OGLTR_DrawGrayscaleGlyphNoCache(oglc, ginfo, x, y);
1112             }
1113         } else {
1114             // LCD-optimized glyph data
1115             jint rowBytesOffset = 0;
1116 
1117             if (subPixPos) {
1118                 jint frac = (jint)((glyphx - x) * 3);
1119                 if (frac != 0) {
1120                     rowBytesOffset = 3 - frac;
1121                     x += 1;
1122                 }
1123             }
1124 
1125             if (rowBytesOffset == 0 &&
1126                 cacheStatus != CACHE_GRAY &&
1127                 ginfo->width <= OGLTR_CACHE_CELL_WIDTH &&
1128                 ginfo->height <= OGLTR_CACHE_CELL_HEIGHT)
1129             {
1130                 ok = OGLTR_DrawLCDGlyphViaCache(oglc, dstOps,
1131                                                 ginfo, x, y,
1132                                                 glyphCounter, totalGlyphs,
1133                                                 rgbOrder, lcdContrast);
1134             } else {
1135                 ok = OGLTR_DrawLCDGlyphNoCache(oglc, dstOps,
1136                                                ginfo, x, y,
1137                                                rowBytesOffset,
1138                                                rgbOrder, lcdContrast);
1139             }
1140         }
1141 
1142         if (!ok) {
1143             break;
1144         }
1145     }
1146 
1147     OGLTR_DisableGlyphModeState();
1148 }
1149 
1150 JNIEXPORT void JNICALL
1151 Java_sun_java2d_opengl_OGLTextRenderer_drawGlyphList
1152     (JNIEnv *env, jobject self,
1153      jint numGlyphs, jboolean usePositions,
1154      jboolean subPixPos, jboolean rgbOrder, jint lcdContrast,
1155      jfloat glyphListOrigX, jfloat glyphListOrigY,
1156      jlongArray imgArray, jfloatArray posArray)
1157 {
1158     unsigned char *images;
1159 
1160     J2dTraceLn(J2D_TRACE_INFO, "OGLTextRenderer_drawGlyphList");
1161 
1162     images = (unsigned char *)
1163         (*env)->GetPrimitiveArrayCritical(env, imgArray, NULL);
1164     if (images != NULL) {
1165         OGLContext *oglc = OGLRenderQueue_GetCurrentContext();
1166         OGLSDOps *dstOps = OGLRenderQueue_GetCurrentDestination();
1167 
1168         if (usePositions) {
1169             unsigned char *positions = (unsigned char *)
1170                 (*env)->GetPrimitiveArrayCritical(env, posArray, NULL);
1171             if (positions != NULL) {
1172                 OGLTR_DrawGlyphList(env, oglc, dstOps,
1173                                     numGlyphs, usePositions,
1174                                     subPixPos, rgbOrder, lcdContrast,
1175                                     glyphListOrigX, glyphListOrigY,
1176                                     images, positions);
1177                 (*env)->ReleasePrimitiveArrayCritical(env, posArray,
1178                                                       positions, JNI_ABORT);
1179             }
1180         } else {
1181             OGLTR_DrawGlyphList(env, oglc, dstOps,
1182                                 numGlyphs, usePositions,
1183                                 subPixPos, rgbOrder, lcdContrast,
1184                                 glyphListOrigX, glyphListOrigY,
1185                                 images, NULL);
1186         }
1187 
1188         // 6358147: reset current state, and ensure rendering is
1189         // flushed to dest
1190         if (oglc != NULL) {
1191             RESET_PREVIOUS_OP();
1192             j2d_glFlush();
1193         }
1194 
1195         (*env)->ReleasePrimitiveArrayCritical(env, imgArray,
1196                                               images, JNI_ABORT);
1197     }
1198 }
1199 
1200 #endif /* !HEADLESS */