1 /**************************************************************************
2  *
3  * Copyright 2007 VMware, Inc.
4  * All Rights Reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the
8  * "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sub license, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice (including the
15  * next paragraph) shall be included in all copies or substantial portions
16  * of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21  * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
22  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  **************************************************************************/
27 
28  /*
29   * Authors:
30   *   Brian Paul
31   */
32 
33 #include "main/errors.h"
34 
35 #include "main/image.h"
36 #include "main/bufferobj.h"
37 #include "main/blit.h"
38 #include "main/format_pack.h"
39 #include "main/framebuffer.h"
40 #include "main/macros.h"
41 #include "main/mtypes.h"
42 #include "main/pack.h"
43 #include "main/pbo.h"
44 #include "main/readpix.h"
45 #include "main/state.h"
46 #include "main/texformat.h"
47 #include "main/teximage.h"
48 #include "main/texstore.h"
49 #include "main/glformats.h"
50 #include "program/program.h"
51 #include "program/prog_print.h"
52 #include "program/prog_instruction.h"
53 
54 #include "st_atom.h"
55 #include "st_atom_constbuf.h"
56 #include "st_cb_bitmap.h"
57 #include "st_cb_drawpixels.h"
58 #include "st_cb_readpixels.h"
59 #include "st_cb_fbo.h"
60 #include "st_context.h"
61 #include "st_debug.h"
62 #include "st_draw.h"
63 #include "st_format.h"
64 #include "st_program.h"
65 #include "st_sampler_view.h"
66 #include "st_scissor.h"
67 #include "st_texture.h"
68 #include "st_util.h"
69 #include "st_nir.h"
70 
71 #include "pipe/p_context.h"
72 #include "pipe/p_defines.h"
73 #include "tgsi/tgsi_ureg.h"
74 #include "util/format/u_format.h"
75 #include "util/u_inlines.h"
76 #include "util/u_math.h"
77 #include "util/u_simple_shaders.h"
78 #include "util/u_tile.h"
79 #include "cso_cache/cso_context.h"
80 
81 #include "compiler/nir/nir_builder.h"
82 
83 /**
84  * We have a simple glDrawPixels cache to try to optimize the case where the
85  * same image is drawn over and over again.  It basically works as follows:
86  *
87  * 1. After we construct a texture map with the image and draw it, we do
88  *    not discard the texture.  We keep it around, plus we note the
89  *    glDrawPixels width, height, format, etc. parameters and keep a copy
90  *    of the image in a malloc'd buffer.
91  *
92  * 2. On the next glDrawPixels we check if the parameters match the previous
93  *    call.  If those match, we check if the image matches the previous image
94  *    via a memcmp() call.  If everything matches, we re-use the previous
95  *    texture, thereby avoiding the cost creating a new texture and copying
96  *    the image to it.
97  *
98  * The effectiveness of this cache depends upon:
99  * 1. If the memcmp() finds a difference, it happens relatively quickly.
100       Hopefully, not just the last pixels differ!
101  * 2. If the memcmp() finds no difference, doing that check is faster than
102  *    creating and loading a texture.
103  *
104  * Notes:
105  * 1. We don't support any pixel unpacking parameters.
106  * 2. We don't try to cache images in Pixel Buffer Objects.
107  * 3. Instead of saving the whole image, perhaps some sort of reliable
108  *    checksum function could be used instead.
109  */
110 #define USE_DRAWPIXELS_CACHE 1
111 
112 static nir_ssa_def *
sample_via_nir(nir_builder * b,nir_variable * texcoord,const char * name,int sampler,enum glsl_base_type base_type,nir_alu_type alu_type)113 sample_via_nir(nir_builder *b, nir_variable *texcoord,
114                const char *name, int sampler, enum glsl_base_type base_type,
115                nir_alu_type alu_type)
116 {
117    const struct glsl_type *sampler2D =
118       glsl_sampler_type(GLSL_SAMPLER_DIM_2D, false, false, base_type);
119 
120    nir_variable *var =
121       nir_variable_create(b->shader, nir_var_uniform, sampler2D, name);
122    var->data.binding = sampler;
123    var->data.explicit_binding = true;
124 
125    nir_deref_instr *deref = nir_build_deref_var(b, var);
126 
127    nir_tex_instr *tex = nir_tex_instr_create(b->shader, 3);
128    tex->op = nir_texop_tex;
129    tex->sampler_dim = GLSL_SAMPLER_DIM_2D;
130    tex->coord_components = 2;
131    tex->dest_type = alu_type;
132    tex->src[0].src_type = nir_tex_src_texture_deref;
133    tex->src[0].src = nir_src_for_ssa(&deref->dest.ssa);
134    tex->src[1].src_type = nir_tex_src_sampler_deref;
135    tex->src[1].src = nir_src_for_ssa(&deref->dest.ssa);
136    tex->src[2].src_type = nir_tex_src_coord;
137    tex->src[2].src =
138       nir_src_for_ssa(nir_channels(b, nir_load_var(b, texcoord),
139                                    (1 << tex->coord_components) - 1));
140 
141    nir_ssa_dest_init(&tex->instr, &tex->dest, 4, 32, NULL);
142    nir_builder_instr_insert(b, &tex->instr);
143    return nir_channel(b, &tex->dest.ssa, 0);
144 }
145 
146 static void *
make_drawpix_z_stencil_program_nir(struct st_context * st,bool write_depth,bool write_stencil)147 make_drawpix_z_stencil_program_nir(struct st_context *st,
148                                    bool write_depth,
149                                    bool write_stencil)
150 {
151    struct nir_builder b;
152    const nir_shader_compiler_options *options =
153       st_get_nir_compiler_options(st, MESA_SHADER_FRAGMENT);
154 
155    nir_builder_init_simple_shader(&b, NULL, MESA_SHADER_FRAGMENT, options);
156 
157    nir_variable *texcoord =
158       nir_variable_create(b.shader, nir_var_shader_in, glsl_vec_type(2),
159                           "texcoord");
160    texcoord->data.location = VARYING_SLOT_TEX0;
161 
162    if (write_depth) {
163       nir_variable *out =
164          nir_variable_create(b.shader, nir_var_shader_out, glsl_float_type(),
165                              "gl_FragDepth");
166       out->data.location = FRAG_RESULT_DEPTH;
167       nir_ssa_def *depth = sample_via_nir(&b, texcoord, "depth", 0,
168                                           GLSL_TYPE_FLOAT, nir_type_float);
169       nir_store_var(&b, out, depth, 0x1);
170 
171       /* Also copy color */
172       nir_variable *color_in =
173          nir_variable_create(b.shader, nir_var_shader_in, glsl_vec_type(4),
174                              "v_color");
175       color_in->data.location = VARYING_SLOT_COL0;
176 
177       nir_variable *color_out =
178          nir_variable_create(b.shader, nir_var_shader_out, glsl_vec_type(4),
179                              "gl_FragColor");
180       color_out->data.location = FRAG_RESULT_COLOR;
181       nir_copy_var(&b, color_out, color_in);
182    }
183 
184    if (write_stencil) {
185       nir_variable *out =
186          nir_variable_create(b.shader, nir_var_shader_out, glsl_uint_type(),
187                              "gl_FragStencilRefARB");
188       out->data.location = FRAG_RESULT_STENCIL;
189       nir_ssa_def *stencil = sample_via_nir(&b, texcoord, "stencil", 1,
190                                             GLSL_TYPE_UINT, nir_type_uint);
191       nir_store_var(&b, out, stencil, 0x1);
192    }
193 
194    char name[14];
195    snprintf(name, 14, "drawpixels %s%s",
196             write_depth ? "Z" : "", write_stencil ? "S" : "");
197 
198    return st_nir_finish_builtin_shader(st, b.shader, name);
199 }
200 
201 static void *
make_drawpix_zs_to_color_program_nir(struct st_context * st,bool rgba)202 make_drawpix_zs_to_color_program_nir(struct st_context *st,
203                                    bool rgba)
204 {
205    struct nir_builder b;
206    const nir_shader_compiler_options *options =
207       st_get_nir_compiler_options(st, MESA_SHADER_FRAGMENT);
208 
209    nir_builder_init_simple_shader(&b, NULL, MESA_SHADER_FRAGMENT, options);
210 
211    nir_variable *texcoord =
212       nir_variable_create(b.shader, nir_var_shader_in, glsl_vec_type(2),
213                           "texcoord");
214    texcoord->data.location = VARYING_SLOT_TEX0;
215 
216    /* Sample depth and stencil */
217    nir_ssa_def *depth = sample_via_nir(&b, texcoord, "depth", 0,
218                                        GLSL_TYPE_FLOAT, nir_type_float);
219    nir_ssa_def *stencil = sample_via_nir(&b, texcoord, "stencil", 1,
220                                          GLSL_TYPE_UINT, nir_type_uint);
221 
222    /* Create the variable to store the output color */
223    nir_variable *color_out =
224       nir_variable_create(b.shader, nir_var_shader_out, glsl_vec_type(4),
225                           "make_drawpix_zs_to_color_program_nirgl_FragColor");
226    color_out->data.location = FRAG_RESULT_COLOR;
227 
228    nir_ssa_def *shifted_depth = nir_fmul(&b,nir_f2f64(&b, depth), nir_imm_double(&b,0xffffff));
229    nir_ssa_def *int_depth = nir_f2u32(&b,shifted_depth);
230 
231    nir_ssa_def *ds[4];
232    ds[0] = nir_ubitfield_extract(&b, stencil, nir_imm_int(&b, 0), nir_imm_int(&b,8));
233    ds[1] = nir_ubitfield_extract(&b, int_depth, nir_imm_int(&b, 0), nir_imm_int(&b,8));
234    ds[2] = nir_ubitfield_extract(&b, int_depth, nir_imm_int(&b, 8), nir_imm_int(&b,8));
235    ds[3] = nir_ubitfield_extract(&b, int_depth, nir_imm_int(&b, 16), nir_imm_int(&b,8));
236 
237    nir_ssa_def *ds_comp[4];
238    ds_comp[0] = nir_fsat(&b, nir_fmul_imm(&b, nir_u2f32(&b, ds[3]), 1.0/255.0));
239    ds_comp[1] = nir_fsat(&b, nir_fmul_imm(&b, nir_u2f32(&b, ds[2]), 1.0/255.0));
240    ds_comp[2] = nir_fsat(&b, nir_fmul_imm(&b, nir_u2f32(&b, ds[1]), 1.0/255.0));
241    ds_comp[3] = nir_fsat(&b, nir_fmul_imm(&b, nir_u2f32(&b, ds[0]), 1.0/255.0));
242 
243    nir_ssa_def *unpacked_ds = nir_vec4(&b, ds_comp[0], ds_comp[1], ds_comp[2], ds_comp[3]);
244 
245    if (rgba) {
246       nir_store_var(&b, color_out, unpacked_ds, 0xf);
247    }
248    else {
249       unsigned zyxw[4] = { 2, 1, 0, 3 };
250       nir_ssa_def *swizzled_ds= nir_swizzle(&b, unpacked_ds, zyxw, 4);
251       nir_store_var(&b, color_out, swizzled_ds, 0xf);
252    }
253 
254    char name[17];
255    snprintf(name, 17, "copypixels ZStoC");
256 
257    return st_nir_finish_builtin_shader(st, b.shader, name);
258 }
259 
260 
261 /**
262  * Create fragment program that does a TEX() instruction to get a Z and/or
263  * stencil value value, then writes to FRAG_RESULT_DEPTH/FRAG_RESULT_STENCIL.
264  * Used for glDrawPixels(GL_DEPTH_COMPONENT / GL_STENCIL_INDEX).
265  * Pass fragment color through as-is.
266  *
267  * \return CSO of the fragment shader.
268  */
269 static void *
get_drawpix_z_stencil_program(struct st_context * st,bool write_depth,bool write_stencil)270 get_drawpix_z_stencil_program(struct st_context *st,
271                               bool write_depth,
272                               bool write_stencil)
273 {
274    const GLuint shaderIndex = write_depth * 2 + write_stencil;
275    void *cso;
276 
277    assert(shaderIndex < ARRAY_SIZE(st->drawpix.zs_shaders));
278 
279    if (st->drawpix.zs_shaders[shaderIndex]) {
280       /* already have the proper shader */
281       return st->drawpix.zs_shaders[shaderIndex];
282    }
283 
284    cso = make_drawpix_z_stencil_program_nir(st, write_depth, write_stencil);
285 
286    /* save the new shader */
287    st->drawpix.zs_shaders[shaderIndex] = cso;
288    return cso;
289 }
290 
291 /**
292  * Create fragment program that does a TEX() instruction to get a Z and
293  * stencil value value, then writes to FRAG_RESULT_COLOR.
294  * Used for glCopyPixels(GL_DEPTH_STENCIL_TO_RGBA_NV / GL_DEPTH_STENCIL_TO_BGRA_NV).
295  *
296  * \return CSO of the fragment shader.
297  */
298 static void *
get_drawpix_zs_to_color_program(struct st_context * st,bool rgba)299 get_drawpix_zs_to_color_program(struct st_context *st,
300                               bool rgba)
301 {
302    void *cso;
303    GLuint shaderIndex;
304 
305    if (rgba)
306       shaderIndex = 4;
307    else
308       shaderIndex = 5;
309 
310    assert(shaderIndex < ARRAY_SIZE(st->drawpix.zs_shaders));
311 
312    if (st->drawpix.zs_shaders[shaderIndex]) {
313       /* already have the proper shader */
314       return st->drawpix.zs_shaders[shaderIndex];
315    }
316 
317    cso = make_drawpix_zs_to_color_program_nir(st, rgba);
318 
319    /* save the new shader */
320    st->drawpix.zs_shaders[shaderIndex] = cso;
321    return cso;
322 }
323 
324 /**
325  * Create a simple vertex shader that just passes through the
326  * vertex position, texcoord, and color.
327  */
328 void
st_make_passthrough_vertex_shader(struct st_context * st)329 st_make_passthrough_vertex_shader(struct st_context *st)
330 {
331    if (st->passthrough_vs)
332       return;
333 
334    unsigned inputs[] =
335       {  VERT_ATTRIB_POS, VERT_ATTRIB_COLOR0, VERT_ATTRIB_GENERIC0 };
336    unsigned outputs[] =
337       { VARYING_SLOT_POS,  VARYING_SLOT_COL0,    VARYING_SLOT_TEX0 };
338 
339    st->passthrough_vs =
340       st_nir_make_passthrough_shader(st, "drawpixels VS",
341                                      MESA_SHADER_VERTEX, 3,
342                                      inputs, outputs, NULL, 0);
343 }
344 
345 
346 /**
347  * Return a texture internalFormat for drawing/copying an image
348  * of the given format and type.
349  */
350 static GLenum
internal_format(struct gl_context * ctx,GLenum format,GLenum type)351 internal_format(struct gl_context *ctx, GLenum format, GLenum type)
352 {
353    switch (format) {
354    case GL_DEPTH_COMPONENT:
355       switch (type) {
356       case GL_UNSIGNED_SHORT:
357          return GL_DEPTH_COMPONENT16;
358 
359       case GL_UNSIGNED_INT:
360          return GL_DEPTH_COMPONENT32;
361 
362       case GL_FLOAT:
363          if (ctx->Extensions.ARB_depth_buffer_float)
364             return GL_DEPTH_COMPONENT32F;
365          else
366             return GL_DEPTH_COMPONENT;
367 
368       default:
369          return GL_DEPTH_COMPONENT;
370       }
371 
372    case GL_DEPTH_STENCIL:
373       switch (type) {
374       case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
375          return GL_DEPTH32F_STENCIL8;
376 
377       case GL_UNSIGNED_INT_24_8:
378       default:
379          return GL_DEPTH24_STENCIL8;
380       }
381 
382    case GL_STENCIL_INDEX:
383       return GL_STENCIL_INDEX;
384 
385    default:
386       if (_mesa_is_enum_format_integer(format)) {
387          switch (type) {
388          case GL_BYTE:
389             return GL_RGBA8I;
390          case GL_UNSIGNED_BYTE:
391             return GL_RGBA8UI;
392          case GL_SHORT:
393             return GL_RGBA16I;
394          case GL_UNSIGNED_SHORT:
395             return GL_RGBA16UI;
396          case GL_INT:
397             return GL_RGBA32I;
398          case GL_UNSIGNED_INT:
399             return GL_RGBA32UI;
400          default:
401             assert(0 && "Unexpected type in internal_format()");
402             return GL_RGBA_INTEGER;
403          }
404       }
405       else {
406          switch (type) {
407          case GL_UNSIGNED_BYTE:
408          case GL_UNSIGNED_INT_8_8_8_8:
409          case GL_UNSIGNED_INT_8_8_8_8_REV:
410          default:
411             return GL_RGBA8;
412 
413          case GL_UNSIGNED_BYTE_3_3_2:
414          case GL_UNSIGNED_BYTE_2_3_3_REV:
415             return GL_R3_G3_B2;
416 
417          case GL_UNSIGNED_SHORT_4_4_4_4:
418          case GL_UNSIGNED_SHORT_4_4_4_4_REV:
419             return GL_RGBA4;
420 
421          case GL_UNSIGNED_SHORT_5_6_5:
422          case GL_UNSIGNED_SHORT_5_6_5_REV:
423             return GL_RGB565;
424 
425          case GL_UNSIGNED_SHORT_5_5_5_1:
426          case GL_UNSIGNED_SHORT_1_5_5_5_REV:
427             return GL_RGB5_A1;
428 
429          case GL_UNSIGNED_INT_10_10_10_2:
430          case GL_UNSIGNED_INT_2_10_10_10_REV:
431             return GL_RGB10_A2;
432 
433          case GL_UNSIGNED_SHORT:
434          case GL_UNSIGNED_INT:
435             return GL_RGBA16;
436 
437          case GL_BYTE:
438             return
439                ctx->Extensions.EXT_texture_snorm ? GL_RGBA8_SNORM : GL_RGBA8;
440 
441          case GL_SHORT:
442          case GL_INT:
443             return
444                ctx->Extensions.EXT_texture_snorm ? GL_RGBA16_SNORM : GL_RGBA16;
445 
446          case GL_HALF_FLOAT_ARB:
447             return
448                ctx->Extensions.ARB_texture_float ? GL_RGBA16F :
449                ctx->Extensions.EXT_texture_snorm ? GL_RGBA16_SNORM : GL_RGBA16;
450 
451          case GL_FLOAT:
452          case GL_DOUBLE:
453             return
454                ctx->Extensions.ARB_texture_float ? GL_RGBA32F :
455                ctx->Extensions.EXT_texture_snorm ? GL_RGBA16_SNORM : GL_RGBA16;
456 
457          case GL_UNSIGNED_INT_5_9_9_9_REV:
458             assert(ctx->Extensions.EXT_texture_shared_exponent);
459             return GL_RGB9_E5;
460 
461          case GL_UNSIGNED_INT_10F_11F_11F_REV:
462             assert(ctx->Extensions.EXT_packed_float);
463             return GL_R11F_G11F_B10F;
464          }
465       }
466    }
467 }
468 
469 
470 /**
471  * Create a temporary texture to hold an image of the given size.
472  * If width, height are not POT and the driver only handles POT textures,
473  * allocate the next larger size of texture that is POT.
474  */
475 static struct pipe_resource *
alloc_texture(struct st_context * st,GLsizei width,GLsizei height,enum pipe_format texFormat,unsigned bind)476 alloc_texture(struct st_context *st, GLsizei width, GLsizei height,
477               enum pipe_format texFormat, unsigned bind)
478 {
479    struct pipe_resource *pt;
480 
481    pt = st_texture_create(st, st->internal_target, texFormat, 0,
482                           width, height, 1, 1, 0, bind);
483 
484    return pt;
485 }
486 
487 
488 /**
489  * Search the cache for an image which matches the given parameters.
490  * \return  pipe_resource pointer if found, NULL if not found.
491  */
492 static struct pipe_resource *
search_drawpixels_cache(struct st_context * st,GLsizei width,GLsizei height,GLenum format,GLenum type,const struct gl_pixelstore_attrib * unpack,const void * pixels)493 search_drawpixels_cache(struct st_context *st,
494                         GLsizei width, GLsizei height,
495                         GLenum format, GLenum type,
496                         const struct gl_pixelstore_attrib *unpack,
497                         const void *pixels)
498 {
499    struct pipe_resource *pt = NULL;
500    const GLint bpp = _mesa_bytes_per_pixel(format, type);
501    unsigned i;
502 
503    if ((unpack->RowLength != 0 && unpack->RowLength != width) ||
504        unpack->SkipPixels != 0 ||
505        unpack->SkipRows != 0 ||
506        unpack->SwapBytes ||
507        unpack->BufferObj) {
508       /* we don't allow non-default pixel unpacking values */
509       return NULL;
510    }
511 
512    /* Search cache entries for a match */
513    for (i = 0; i < ARRAY_SIZE(st->drawpix_cache.entries); i++) {
514       struct drawpix_cache_entry *entry = &st->drawpix_cache.entries[i];
515 
516       if (width == entry->width &&
517           height == entry->height &&
518           format == entry->format &&
519           type == entry->type &&
520           pixels == entry->user_pointer &&
521           entry->image) {
522          assert(entry->texture);
523 
524          /* check if the pixel data is the same */
525          if (memcmp(pixels, entry->image, width * height * bpp) == 0) {
526             /* Success - found a cache match */
527             pipe_resource_reference(&pt, entry->texture);
528             /* refcount of returned texture should be at least two here.  One
529              * reference for the cache to hold on to, one for the caller (which
530              * it will release), and possibly more held by the driver.
531              */
532             assert(pt->reference.count >= 2);
533 
534             /* update the age of this entry */
535             entry->age = ++st->drawpix_cache.age;
536 
537             return pt;
538          }
539       }
540    }
541 
542    /* no cache match found */
543    return NULL;
544 }
545 
546 
547 /**
548  * Find the oldest entry in the glDrawPixels cache.  We'll replace this
549  * one when we need to store a new image.
550  */
551 static struct drawpix_cache_entry *
find_oldest_drawpixels_cache_entry(struct st_context * st)552 find_oldest_drawpixels_cache_entry(struct st_context *st)
553 {
554    unsigned oldest_age = ~0u, oldest_index = ~0u;
555    unsigned i;
556 
557    /* Find entry with oldest (lowest) age */
558    for (i = 0; i < ARRAY_SIZE(st->drawpix_cache.entries); i++) {
559       const struct drawpix_cache_entry *entry = &st->drawpix_cache.entries[i];
560       if (entry->age < oldest_age) {
561          oldest_age = entry->age;
562          oldest_index = i;
563       }
564    }
565 
566    assert(oldest_index != ~0u);
567 
568    return &st->drawpix_cache.entries[oldest_index];
569 }
570 
571 
572 /**
573  * Try to save the given glDrawPixels image in the cache.
574  */
575 static void
cache_drawpixels_image(struct st_context * st,GLsizei width,GLsizei height,GLenum format,GLenum type,const struct gl_pixelstore_attrib * unpack,const void * pixels,struct pipe_resource * pt)576 cache_drawpixels_image(struct st_context *st,
577                        GLsizei width, GLsizei height,
578                        GLenum format, GLenum type,
579                        const struct gl_pixelstore_attrib *unpack,
580                        const void *pixels,
581                        struct pipe_resource *pt)
582 {
583    if ((unpack->RowLength == 0 || unpack->RowLength == width) &&
584        unpack->SkipPixels == 0 &&
585        unpack->SkipRows == 0) {
586       const GLint bpp = _mesa_bytes_per_pixel(format, type);
587       struct drawpix_cache_entry *entry =
588          find_oldest_drawpixels_cache_entry(st);
589       assert(entry);
590       entry->width = width;
591       entry->height = height;
592       entry->format = format;
593       entry->type = type;
594       entry->user_pointer = pixels;
595       free(entry->image);
596       entry->image = malloc(width * height * bpp);
597       if (entry->image) {
598          memcpy(entry->image, pixels, width * height * bpp);
599          pipe_resource_reference(&entry->texture, pt);
600          entry->age = ++st->drawpix_cache.age;
601       }
602       else {
603          /* out of memory, free/disable cached texture */
604          entry->width = 0;
605          entry->height = 0;
606          pipe_resource_reference(&entry->texture, NULL);
607       }
608    }
609 }
610 
611 
612 /**
613  * Make texture containing an image for glDrawPixels image.
614  * If 'pixels' is NULL, leave the texture image data undefined.
615  */
616 static struct pipe_resource *
make_texture(struct st_context * st,GLsizei width,GLsizei height,GLenum format,GLenum type,const struct gl_pixelstore_attrib * unpack,const void * pixels)617 make_texture(struct st_context *st,
618 	     GLsizei width, GLsizei height, GLenum format, GLenum type,
619 	     const struct gl_pixelstore_attrib *unpack,
620 	     const void *pixels)
621 {
622    struct gl_context *ctx = st->ctx;
623    struct pipe_context *pipe = st->pipe;
624    mesa_format mformat;
625    struct pipe_resource *pt = NULL;
626    enum pipe_format pipeFormat;
627    GLenum baseInternalFormat;
628 
629 #if USE_DRAWPIXELS_CACHE
630    pt = search_drawpixels_cache(st, width, height, format, type,
631                                 unpack, pixels);
632    if (pt) {
633       return pt;
634    }
635 #endif
636 
637    /* Choose a pixel format for the temp texture which will hold the
638     * image to draw.
639     */
640    pipeFormat = st_choose_matching_format(st, PIPE_BIND_SAMPLER_VIEW,
641                                           format, type, unpack->SwapBytes);
642 
643    if (pipeFormat == PIPE_FORMAT_NONE) {
644       /* Use the generic approach. */
645       GLenum intFormat = internal_format(ctx, format, type);
646 
647       pipeFormat = st_choose_format(st, intFormat, format, type,
648                                     st->internal_target, 0, 0,
649                                     PIPE_BIND_SAMPLER_VIEW,
650                                     false, false);
651       assert(pipeFormat != PIPE_FORMAT_NONE);
652    }
653 
654    mformat = st_pipe_format_to_mesa_format(pipeFormat);
655    baseInternalFormat = _mesa_get_format_base_format(mformat);
656 
657    pixels = _mesa_map_pbo_source(ctx, unpack, pixels);
658    if (!pixels)
659       return NULL;
660 
661    /* alloc temporary texture */
662    pt = alloc_texture(st, width, height, pipeFormat, PIPE_BIND_SAMPLER_VIEW);
663    if (!pt) {
664       _mesa_unmap_pbo_source(ctx, unpack);
665       return NULL;
666    }
667 
668    {
669       struct pipe_transfer *transfer;
670       GLubyte *dest;
671       const GLbitfield imageTransferStateSave = ctx->_ImageTransferState;
672 
673       /* we'll do pixel transfer in a fragment shader */
674       ctx->_ImageTransferState = 0x0;
675 
676       /* map texture transfer */
677       dest = pipe_transfer_map(pipe, pt, 0, 0,
678                                PIPE_MAP_WRITE, 0, 0,
679                                width, height, &transfer);
680       if (!dest) {
681          pipe_resource_reference(&pt, NULL);
682          _mesa_unmap_pbo_source(ctx, unpack);
683          return NULL;
684       }
685 
686       /* Put image into texture transfer.
687        * Note that the image is actually going to be upside down in
688        * the texture.  We deal with that with texcoords.
689        */
690       if ((format == GL_RGBA || format == GL_BGRA)
691           && type == GL_UNSIGNED_BYTE) {
692          /* Use a memcpy-based texstore to avoid software pixel swizzling.
693           * We'll do the necessary swizzling with the pipe_sampler_view to
694           * give much better performance.
695           * XXX in the future, expand this to accomodate more format and
696           * type combinations.
697           */
698          _mesa_memcpy_texture(ctx, 2,
699                               mformat,          /* mesa_format */
700                               transfer->stride, /* dstRowStride, bytes */
701                               &dest,            /* destSlices */
702                               width, height, 1, /* size */
703                               format, type,     /* src format/type */
704                               pixels,           /* data source */
705                               unpack);
706       }
707       else {
708          ASSERTED bool success;
709          success = _mesa_texstore(ctx, 2,           /* dims */
710                                   baseInternalFormat, /* baseInternalFormat */
711                                   mformat,          /* mesa_format */
712                                   transfer->stride, /* dstRowStride, bytes */
713                                   &dest,            /* destSlices */
714                                   width, height, 1, /* size */
715                                   format, type,     /* src format/type */
716                                   pixels,           /* data source */
717                                   unpack);
718 
719          assert(success);
720       }
721 
722       /* unmap */
723       pipe_transfer_unmap(pipe, transfer);
724 
725       /* restore */
726       ctx->_ImageTransferState = imageTransferStateSave;
727    }
728 
729 #if USE_DRAWPIXELS_CACHE
730    cache_drawpixels_image(st, width, height, format, type, unpack, pixels, pt);
731 #endif
732 
733    _mesa_unmap_pbo_source(ctx, unpack);
734 
735    return pt;
736 }
737 
738 
739 static void
draw_textured_quad(struct gl_context * ctx,GLint x,GLint y,GLfloat z,GLsizei width,GLsizei height,GLfloat zoomX,GLfloat zoomY,struct pipe_sampler_view ** sv,int num_sampler_view,void * driver_vp,void * driver_fp,struct st_fp_variant * fpv,const GLfloat * color,GLboolean invertTex,GLboolean write_depth,GLboolean write_stencil)740 draw_textured_quad(struct gl_context *ctx, GLint x, GLint y, GLfloat z,
741                    GLsizei width, GLsizei height,
742                    GLfloat zoomX, GLfloat zoomY,
743                    struct pipe_sampler_view **sv,
744                    int num_sampler_view,
745                    void *driver_vp,
746                    void *driver_fp,
747                    struct st_fp_variant *fpv,
748                    const GLfloat *color,
749                    GLboolean invertTex,
750                    GLboolean write_depth, GLboolean write_stencil)
751 {
752    struct st_context *st = st_context(ctx);
753    struct pipe_context *pipe = st->pipe;
754    struct cso_context *cso = st->cso_context;
755    const unsigned fb_width = _mesa_geometric_width(ctx->DrawBuffer);
756    const unsigned fb_height = _mesa_geometric_height(ctx->DrawBuffer);
757    GLfloat x0, y0, x1, y1;
758    ASSERTED GLsizei maxSize;
759    boolean normalized = sv[0]->texture->target == PIPE_TEXTURE_2D;
760    unsigned cso_state_mask;
761 
762    assert(sv[0]->texture->target == st->internal_target);
763 
764    /* limit checks */
765    /* XXX if DrawPixels image is larger than max texture size, break
766     * it up into chunks.
767     */
768    maxSize = pipe->screen->get_param(pipe->screen,
769                                      PIPE_CAP_MAX_TEXTURE_2D_SIZE);
770    assert(width <= maxSize);
771    assert(height <= maxSize);
772 
773    cso_state_mask = (CSO_BIT_RASTERIZER |
774                      CSO_BIT_VIEWPORT |
775                      CSO_BIT_FRAGMENT_SAMPLERS |
776                      CSO_BIT_FRAGMENT_SAMPLER_VIEWS |
777                      CSO_BIT_STREAM_OUTPUTS |
778                      CSO_BIT_VERTEX_ELEMENTS |
779                      CSO_BIT_AUX_VERTEX_BUFFER_SLOT |
780                      CSO_BITS_ALL_SHADERS);
781    if (write_stencil) {
782       cso_state_mask |= (CSO_BIT_DEPTH_STENCIL_ALPHA |
783                          CSO_BIT_BLEND);
784    }
785    cso_save_state(cso, cso_state_mask);
786 
787    /* rasterizer state: just scissor */
788    {
789       struct pipe_rasterizer_state rasterizer;
790       memset(&rasterizer, 0, sizeof(rasterizer));
791       rasterizer.clamp_fragment_color = !st->clamp_frag_color_in_shader &&
792                                         ctx->Color._ClampFragmentColor;
793       rasterizer.half_pixel_center = 1;
794       rasterizer.bottom_edge_rule = 1;
795       rasterizer.depth_clip_near = st->clamp_frag_depth_in_shader ||
796                                    !ctx->Transform.DepthClampNear;
797       rasterizer.depth_clip_far = st->clamp_frag_depth_in_shader ||
798                                   !ctx->Transform.DepthClampFar;
799       rasterizer.scissor = ctx->Scissor.EnableFlags;
800       cso_set_rasterizer(cso, &rasterizer);
801    }
802 
803    if (write_stencil) {
804       /* Stencil writing bypasses the normal fragment pipeline to
805        * disable color writing and set stencil test to always pass.
806        */
807       struct pipe_depth_stencil_alpha_state dsa;
808       struct pipe_blend_state blend;
809 
810       /* depth/stencil */
811       memset(&dsa, 0, sizeof(dsa));
812       dsa.stencil[0].enabled = 1;
813       dsa.stencil[0].func = PIPE_FUNC_ALWAYS;
814       dsa.stencil[0].writemask = ctx->Stencil.WriteMask[0] & 0xff;
815       dsa.stencil[0].zpass_op = PIPE_STENCIL_OP_REPLACE;
816       if (write_depth) {
817          /* writing depth+stencil: depth test always passes */
818          dsa.depth.enabled = 1;
819          dsa.depth.writemask = ctx->Depth.Mask;
820          dsa.depth.func = PIPE_FUNC_ALWAYS;
821       }
822       cso_set_depth_stencil_alpha(cso, &dsa);
823 
824       /* blend (colormask) */
825       memset(&blend, 0, sizeof(blend));
826       cso_set_blend(cso, &blend);
827    }
828 
829    /* fragment shader state: TEX lookup program */
830    cso_set_fragment_shader_handle(cso, driver_fp);
831 
832    /* vertex shader state: position + texcoord pass-through */
833    cso_set_vertex_shader_handle(cso, driver_vp);
834 
835    /* disable other shaders */
836    cso_set_tessctrl_shader_handle(cso, NULL);
837    cso_set_tesseval_shader_handle(cso, NULL);
838    cso_set_geometry_shader_handle(cso, NULL);
839 
840    /* user samplers, plus the drawpix samplers */
841    {
842       struct pipe_sampler_state sampler;
843 
844       memset(&sampler, 0, sizeof(sampler));
845       sampler.wrap_s = PIPE_TEX_WRAP_CLAMP;
846       sampler.wrap_t = PIPE_TEX_WRAP_CLAMP;
847       sampler.wrap_r = PIPE_TEX_WRAP_CLAMP;
848       sampler.min_img_filter = PIPE_TEX_FILTER_NEAREST;
849       sampler.min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
850       sampler.mag_img_filter = PIPE_TEX_FILTER_NEAREST;
851       sampler.normalized_coords = normalized;
852 
853       if (fpv) {
854          /* drawing a color image */
855          const struct pipe_sampler_state *samplers[PIPE_MAX_SAMPLERS];
856          uint num = MAX3(fpv->drawpix_sampler + 1,
857                          fpv->pixelmap_sampler + 1,
858                          st->state.num_frag_samplers);
859          uint i;
860 
861          for (i = 0; i < st->state.num_frag_samplers; i++)
862             samplers[i] = &st->state.frag_samplers[i];
863 
864          samplers[fpv->drawpix_sampler] = &sampler;
865          if (sv[1])
866             samplers[fpv->pixelmap_sampler] = &sampler;
867 
868          cso_set_samplers(cso, PIPE_SHADER_FRAGMENT, num, samplers);
869       } else {
870          /* drawing a depth/stencil image */
871          const struct pipe_sampler_state *samplers[2] = {&sampler, &sampler};
872 
873          cso_set_samplers(cso, PIPE_SHADER_FRAGMENT, num_sampler_view, samplers);
874       }
875    }
876 
877    /* user textures, plus the drawpix textures */
878    if (fpv) {
879       /* drawing a color image */
880       struct pipe_sampler_view *sampler_views[PIPE_MAX_SAMPLERS];
881       uint num = MAX3(fpv->drawpix_sampler + 1,
882                       fpv->pixelmap_sampler + 1,
883                       st->state.num_sampler_views[PIPE_SHADER_FRAGMENT]);
884 
885       memcpy(sampler_views, st->state.frag_sampler_views,
886              sizeof(sampler_views));
887 
888       sampler_views[fpv->drawpix_sampler] = sv[0];
889       if (sv[1])
890          sampler_views[fpv->pixelmap_sampler] = sv[1];
891       cso_set_sampler_views(cso, PIPE_SHADER_FRAGMENT, num, sampler_views);
892    } else {
893       /* drawing a depth/stencil image */
894       cso_set_sampler_views(cso, PIPE_SHADER_FRAGMENT, num_sampler_view, sv);
895    }
896 
897    /* viewport state: viewport matching window dims */
898    cso_set_viewport_dims(cso, fb_width, fb_height, TRUE);
899 
900    st->util_velems.count = 3;
901    cso_set_vertex_elements(cso, &st->util_velems);
902    cso_set_stream_outputs(cso, 0, NULL, NULL);
903 
904    /* Compute Gallium window coords (y=0=top) with pixel zoom.
905     * Recall that these coords are transformed by the current
906     * vertex shader and viewport transformation.
907     */
908    if (st_fb_orientation(ctx->DrawBuffer) == Y_0_BOTTOM) {
909       y = fb_height - (int) (y + height * ctx->Pixel.ZoomY);
910       invertTex = !invertTex;
911    }
912 
913    x0 = (GLfloat) x;
914    x1 = x + width * ctx->Pixel.ZoomX;
915    y0 = (GLfloat) y;
916    y1 = y + height * ctx->Pixel.ZoomY;
917 
918    /* convert Z from [0,1] to [-1,-1] to match viewport Z scale/bias */
919    z = z * 2.0f - 1.0f;
920 
921    {
922       const float clip_x0 = x0 / (float) fb_width * 2.0f - 1.0f;
923       const float clip_y0 = y0 / (float) fb_height * 2.0f - 1.0f;
924       const float clip_x1 = x1 / (float) fb_width * 2.0f - 1.0f;
925       const float clip_y1 = y1 / (float) fb_height * 2.0f - 1.0f;
926       const float maxXcoord = normalized ?
927          ((float) width / sv[0]->texture->width0) : (float) width;
928       const float maxYcoord = normalized
929          ? ((float) height / sv[0]->texture->height0) : (float) height;
930       const float sLeft = 0.0f, sRight = maxXcoord;
931       const float tTop = invertTex ? maxYcoord : 0.0f;
932       const float tBot = invertTex ? 0.0f : maxYcoord;
933 
934       if (!st_draw_quad(st, clip_x0, clip_y0, clip_x1, clip_y1, z,
935                         sLeft, tBot, sRight, tTop, color, 0)) {
936          _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDrawPixels");
937       }
938    }
939 
940    /* restore state */
941    cso_restore_state(cso);
942 }
943 
944 
945 /**
946  * Software fallback to do glDrawPixels(GL_STENCIL_INDEX) when we
947  * can't use a fragment shader to write stencil values.
948  */
949 static void
draw_stencil_pixels(struct gl_context * ctx,GLint x,GLint y,GLsizei width,GLsizei height,GLenum format,GLenum type,const struct gl_pixelstore_attrib * unpack,const void * pixels)950 draw_stencil_pixels(struct gl_context *ctx, GLint x, GLint y,
951                     GLsizei width, GLsizei height, GLenum format, GLenum type,
952                     const struct gl_pixelstore_attrib *unpack,
953                     const void *pixels)
954 {
955    struct st_context *st = st_context(ctx);
956    struct pipe_context *pipe = st->pipe;
957    struct st_renderbuffer *strb;
958    enum pipe_map_flags usage;
959    struct pipe_transfer *pt;
960    const GLboolean zoom = ctx->Pixel.ZoomX != 1.0 || ctx->Pixel.ZoomY != 1.0;
961    ubyte *stmap;
962    struct gl_pixelstore_attrib clippedUnpack = *unpack;
963    GLubyte *sValues;
964    GLuint *zValues;
965 
966    if (!zoom) {
967       if (!_mesa_clip_drawpixels(ctx, &x, &y, &width, &height,
968                                  &clippedUnpack)) {
969          /* totally clipped */
970          return;
971       }
972    }
973 
974    strb = st_renderbuffer(ctx->DrawBuffer->
975                           Attachment[BUFFER_STENCIL].Renderbuffer);
976 
977    if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
978       y = ctx->DrawBuffer->Height - y - height;
979    }
980 
981    if (format == GL_STENCIL_INDEX &&
982        _mesa_is_format_packed_depth_stencil(strb->Base.Format)) {
983       /* writing stencil to a combined depth+stencil buffer */
984       usage = PIPE_MAP_READ_WRITE;
985    }
986    else {
987       usage = PIPE_MAP_WRITE;
988    }
989 
990    stmap = pipe_transfer_map(pipe, strb->texture,
991                              strb->surface->u.tex.level,
992                              strb->surface->u.tex.first_layer,
993                              usage, x, y,
994                              width, height, &pt);
995 
996    pixels = _mesa_map_pbo_source(ctx, &clippedUnpack, pixels);
997    assert(pixels);
998 
999    sValues = malloc(width * sizeof(GLubyte));
1000    zValues = malloc(width * sizeof(GLuint));
1001 
1002    if (sValues && zValues) {
1003       GLint row;
1004       for (row = 0; row < height; row++) {
1005          GLfloat *zValuesFloat = (GLfloat*)zValues;
1006          GLenum destType = GL_UNSIGNED_BYTE;
1007          const void *source = _mesa_image_address2d(&clippedUnpack, pixels,
1008                                                       width, height,
1009                                                       format, type,
1010                                                       row, 0);
1011          _mesa_unpack_stencil_span(ctx, width, destType, sValues,
1012                                    type, source, &clippedUnpack,
1013                                    ctx->_ImageTransferState);
1014 
1015          if (format == GL_DEPTH_STENCIL) {
1016             GLenum ztype =
1017                pt->resource->format == PIPE_FORMAT_Z32_FLOAT_S8X24_UINT ?
1018                GL_FLOAT : GL_UNSIGNED_INT;
1019 
1020             _mesa_unpack_depth_span(ctx, width, ztype, zValues,
1021                                     (1 << 24) - 1, type, source,
1022                                     &clippedUnpack);
1023          }
1024 
1025          if (zoom) {
1026             _mesa_problem(ctx, "Gallium glDrawPixels(GL_STENCIL) with "
1027                           "zoom not complete");
1028          }
1029 
1030          {
1031             GLint spanY;
1032 
1033             if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
1034                spanY = height - row - 1;
1035             }
1036             else {
1037                spanY = row;
1038             }
1039 
1040             /* now pack the stencil (and Z) values in the dest format */
1041             switch (pt->resource->format) {
1042             case PIPE_FORMAT_S8_UINT:
1043                {
1044                   ubyte *dest = stmap + spanY * pt->stride;
1045                   assert(usage == PIPE_MAP_WRITE);
1046                   memcpy(dest, sValues, width);
1047                }
1048                break;
1049             case PIPE_FORMAT_Z24_UNORM_S8_UINT:
1050                if (format == GL_DEPTH_STENCIL) {
1051                   uint *dest = (uint *) (stmap + spanY * pt->stride);
1052                   GLint k;
1053                   assert(usage == PIPE_MAP_WRITE);
1054                   for (k = 0; k < width; k++) {
1055                      dest[k] = zValues[k] | (sValues[k] << 24);
1056                   }
1057                }
1058                else {
1059                   uint *dest = (uint *) (stmap + spanY * pt->stride);
1060                   GLint k;
1061                   assert(usage == PIPE_MAP_READ_WRITE);
1062                   for (k = 0; k < width; k++) {
1063                      dest[k] = (dest[k] & 0xffffff) | (sValues[k] << 24);
1064                   }
1065                }
1066                break;
1067             case PIPE_FORMAT_S8_UINT_Z24_UNORM:
1068                if (format == GL_DEPTH_STENCIL) {
1069                   uint *dest = (uint *) (stmap + spanY * pt->stride);
1070                   GLint k;
1071                   assert(usage == PIPE_MAP_WRITE);
1072                   for (k = 0; k < width; k++) {
1073                      dest[k] = (zValues[k] << 8) | (sValues[k] & 0xff);
1074                   }
1075                }
1076                else {
1077                   uint *dest = (uint *) (stmap + spanY * pt->stride);
1078                   GLint k;
1079                   assert(usage == PIPE_MAP_READ_WRITE);
1080                   for (k = 0; k < width; k++) {
1081                      dest[k] = (dest[k] & 0xffffff00) | (sValues[k] & 0xff);
1082                   }
1083                }
1084                break;
1085             case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
1086                if (format == GL_DEPTH_STENCIL) {
1087                   uint *dest = (uint *) (stmap + spanY * pt->stride);
1088                   GLfloat *destf = (GLfloat*)dest;
1089                   GLint k;
1090                   assert(usage == PIPE_MAP_WRITE);
1091                   for (k = 0; k < width; k++) {
1092                      destf[k*2] = zValuesFloat[k];
1093                      dest[k*2+1] = sValues[k] & 0xff;
1094                   }
1095                }
1096                else {
1097                   uint *dest = (uint *) (stmap + spanY * pt->stride);
1098                   GLint k;
1099                   assert(usage == PIPE_MAP_READ_WRITE);
1100                   for (k = 0; k < width; k++) {
1101                      dest[k*2+1] = sValues[k] & 0xff;
1102                   }
1103                }
1104                break;
1105             default:
1106                assert(0);
1107             }
1108          }
1109       }
1110    }
1111    else {
1112       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDrawPixels()");
1113    }
1114 
1115    free(sValues);
1116    free(zValues);
1117 
1118    _mesa_unmap_pbo_source(ctx, &clippedUnpack);
1119 
1120    /* unmap the stencil buffer */
1121    pipe_transfer_unmap(pipe, pt);
1122 }
1123 
1124 
1125 /**
1126  * Get fragment program variant for a glDrawPixels or glCopyPixels
1127  * command for RGBA data.
1128  */
1129 static struct st_fp_variant *
get_color_fp_variant(struct st_context * st)1130 get_color_fp_variant(struct st_context *st)
1131 {
1132    struct gl_context *ctx = st->ctx;
1133    struct st_fp_variant_key key;
1134    struct st_fp_variant *fpv;
1135 
1136    memset(&key, 0, sizeof(key));
1137 
1138    key.st = st->has_shareable_shaders ? NULL : st;
1139    key.drawpixels = 1;
1140    key.scaleAndBias = (ctx->Pixel.RedBias != 0.0 ||
1141                        ctx->Pixel.RedScale != 1.0 ||
1142                        ctx->Pixel.GreenBias != 0.0 ||
1143                        ctx->Pixel.GreenScale != 1.0 ||
1144                        ctx->Pixel.BlueBias != 0.0 ||
1145                        ctx->Pixel.BlueScale != 1.0 ||
1146                        ctx->Pixel.AlphaBias != 0.0 ||
1147                        ctx->Pixel.AlphaScale != 1.0);
1148    key.pixelMaps = ctx->Pixel.MapColorFlag;
1149    key.clamp_color = st->clamp_frag_color_in_shader &&
1150                      ctx->Color._ClampFragmentColor;
1151    key.lower_alpha_func = COMPARE_FUNC_ALWAYS;
1152 
1153    fpv = st_get_fp_variant(st, st->fp, &key);
1154 
1155    return fpv;
1156 }
1157 
1158 /**
1159  * Get fragment program variant for a glDrawPixels command
1160  * for COLOR_INDEX data
1161  */
1162 static struct st_fp_variant *
get_color_index_fp_variant(struct st_context * st)1163 get_color_index_fp_variant(struct st_context *st)
1164 {
1165    struct gl_context *ctx = st->ctx;
1166    struct st_fp_variant_key key;
1167    struct st_fp_variant *fpv;
1168 
1169    memset(&key, 0, sizeof(key));
1170 
1171    key.st = st->has_shareable_shaders ? NULL : st;
1172    key.drawpixels = 1;
1173    /* Since GL is always in RGBA mode MapColorFlag does not
1174     * affect GL_COLOR_INDEX format.
1175     * Scale and bias also never affect GL_COLOR_INDEX format.
1176     */
1177    key.scaleAndBias = 0;
1178    key.pixelMaps = 0;
1179    key.clamp_color = st->clamp_frag_color_in_shader &&
1180                      ctx->Color._ClampFragmentColor;
1181    key.lower_alpha_func = COMPARE_FUNC_ALWAYS;
1182 
1183    fpv = st_get_fp_variant(st, st->fp, &key);
1184 
1185    return fpv;
1186 }
1187 
1188 
1189 /**
1190  * Clamp glDrawPixels width and height to the maximum texture size.
1191  */
1192 static void
clamp_size(struct pipe_context * pipe,GLsizei * width,GLsizei * height,struct gl_pixelstore_attrib * unpack)1193 clamp_size(struct pipe_context *pipe, GLsizei *width, GLsizei *height,
1194            struct gl_pixelstore_attrib *unpack)
1195 {
1196    const int maxSize = pipe->screen->get_param(pipe->screen,
1197                                                PIPE_CAP_MAX_TEXTURE_2D_SIZE);
1198 
1199    if (*width > maxSize) {
1200       if (unpack->RowLength == 0)
1201          unpack->RowLength = *width;
1202       *width = maxSize;
1203    }
1204    if (*height > maxSize) {
1205       *height = maxSize;
1206    }
1207 }
1208 
1209 
1210 /**
1211  * Search the array of 4 swizzle components for the named component and return
1212  * its position.
1213  */
1214 static unsigned
search_swizzle(const unsigned char swizzle[4],unsigned component)1215 search_swizzle(const unsigned char swizzle[4], unsigned component)
1216 {
1217    unsigned i;
1218    for (i = 0; i < 4; i++) {
1219       if (swizzle[i] == component)
1220          return i;
1221    }
1222    assert(!"search_swizzle() failed");
1223    return 0;
1224 }
1225 
1226 
1227 /**
1228  * Set the sampler view's swizzle terms.  This is used to handle RGBA
1229  * swizzling when the incoming image format isn't an exact match for
1230  * the actual texture format.  For example, if we have glDrawPixels(
1231  * GL_RGBA, GL_UNSIGNED_BYTE) and we chose the texture format
1232  * PIPE_FORMAT_B8G8R8A8 then we can do use the sampler view swizzle to
1233  * avoid swizzling all the pixels in software in the texstore code.
1234  */
1235 static void
setup_sampler_swizzle(struct pipe_sampler_view * sv,GLenum format,GLenum type)1236 setup_sampler_swizzle(struct pipe_sampler_view *sv, GLenum format, GLenum type)
1237 {
1238    if ((format == GL_RGBA || format == GL_BGRA) && type == GL_UNSIGNED_BYTE) {
1239       const struct util_format_description *desc =
1240          util_format_description(sv->format);
1241       unsigned c0, c1, c2, c3;
1242 
1243       /* Every gallium driver supports at least one 32-bit packed RGBA format.
1244        * We must have chosen one for (GL_RGBA, GL_UNSIGNED_BYTE).
1245        */
1246       assert(desc->block.bits == 32);
1247 
1248       /* invert the format's swizzle to setup the sampler's swizzle */
1249       if (format == GL_RGBA) {
1250          c0 = PIPE_SWIZZLE_X;
1251          c1 = PIPE_SWIZZLE_Y;
1252          c2 = PIPE_SWIZZLE_Z;
1253          c3 = PIPE_SWIZZLE_W;
1254       }
1255       else {
1256          assert(format == GL_BGRA);
1257          c0 = PIPE_SWIZZLE_Z;
1258          c1 = PIPE_SWIZZLE_Y;
1259          c2 = PIPE_SWIZZLE_X;
1260          c3 = PIPE_SWIZZLE_W;
1261       }
1262       sv->swizzle_r = search_swizzle(desc->swizzle, c0);
1263       sv->swizzle_g = search_swizzle(desc->swizzle, c1);
1264       sv->swizzle_b = search_swizzle(desc->swizzle, c2);
1265       sv->swizzle_a = search_swizzle(desc->swizzle, c3);
1266    }
1267    else {
1268       /* use the default sampler swizzle */
1269    }
1270 }
1271 
1272 
1273 /**
1274  * Compute the effective raster z position. This performs depth-clamping
1275  * if needed.
1276  */
1277 static float
get_effective_raster_z(struct gl_context * ctx)1278 get_effective_raster_z(struct gl_context *ctx)
1279 {
1280    float z = ctx->Current.RasterPos[2];
1281    if (st_context(ctx)->clamp_frag_depth_in_shader) {
1282       GLfloat depth_near;
1283       GLfloat depth_far;
1284       if (ctx->ViewportArray[0].Near < ctx->ViewportArray[0].Far) {
1285          depth_near = ctx->ViewportArray[0].Near;
1286          depth_far = ctx->ViewportArray[0].Far;
1287       } else {
1288          depth_near = ctx->ViewportArray[0].Far;
1289          depth_far = ctx->ViewportArray[0].Near;
1290       }
1291 
1292       if (ctx->Transform.DepthClampNear)
1293          z = MAX2(z, depth_near);
1294       if (ctx->Transform.DepthClampFar)
1295          z = MIN2(z, depth_far);
1296    }
1297    return z;
1298 }
1299 
1300 
1301 /**
1302  * Called via ctx->Driver.DrawPixels()
1303  */
1304 static void
st_DrawPixels(struct gl_context * ctx,GLint x,GLint y,GLsizei width,GLsizei height,GLenum format,GLenum type,const struct gl_pixelstore_attrib * unpack,const void * pixels)1305 st_DrawPixels(struct gl_context *ctx, GLint x, GLint y,
1306               GLsizei width, GLsizei height,
1307               GLenum format, GLenum type,
1308               const struct gl_pixelstore_attrib *unpack, const void *pixels)
1309 {
1310    void *driver_fp;
1311    struct st_context *st = st_context(ctx);
1312    struct pipe_context *pipe = st->pipe;
1313    GLboolean write_stencil = GL_FALSE, write_depth = GL_FALSE;
1314    struct pipe_sampler_view *sv[2] = { NULL };
1315    int num_sampler_view = 1;
1316    struct gl_pixelstore_attrib clippedUnpack;
1317    struct st_fp_variant *fpv = NULL;
1318    struct pipe_resource *pt;
1319 
1320    /* Mesa state should be up to date by now */
1321    assert(ctx->NewState == 0x0);
1322 
1323    _mesa_update_draw_buffer_bounds(ctx, ctx->DrawBuffer);
1324 
1325    st_flush_bitmap_cache(st);
1326    st_invalidate_readpix_cache(st);
1327 
1328    st_validate_state(st, ST_PIPELINE_META);
1329 
1330    /* Limit the size of the glDrawPixels to the max texture size.
1331     * Strictly speaking, that's not correct but since we don't handle
1332     * larger images yet, this is better than crashing.
1333     */
1334    clippedUnpack = *unpack;
1335    unpack = &clippedUnpack;
1336    clamp_size(st->pipe, &width, &height, &clippedUnpack);
1337 
1338    if (format == GL_DEPTH_STENCIL)
1339       write_stencil = write_depth = GL_TRUE;
1340    else if (format == GL_STENCIL_INDEX)
1341       write_stencil = GL_TRUE;
1342    else if (format == GL_DEPTH_COMPONENT)
1343       write_depth = GL_TRUE;
1344 
1345    if (write_stencil &&
1346        !pipe->screen->get_param(pipe->screen, PIPE_CAP_SHADER_STENCIL_EXPORT)) {
1347       /* software fallback */
1348       draw_stencil_pixels(ctx, x, y, width, height, format, type,
1349                           unpack, pixels);
1350       return;
1351    }
1352 
1353    /* Put glDrawPixels image into a texture */
1354    pt = make_texture(st, width, height, format, type, unpack, pixels);
1355    if (!pt) {
1356       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDrawPixels");
1357       return;
1358    }
1359 
1360    st_make_passthrough_vertex_shader(st);
1361 
1362    /*
1363     * Get vertex/fragment shaders
1364     */
1365    if (write_depth || write_stencil) {
1366       driver_fp = get_drawpix_z_stencil_program(st, write_depth,
1367                                                 write_stencil);
1368    }
1369    else {
1370       fpv = (format != GL_COLOR_INDEX) ? get_color_fp_variant(st) :
1371                                          get_color_index_fp_variant(st);
1372 
1373       driver_fp = fpv->base.driver_shader;
1374 
1375       if (ctx->Pixel.MapColorFlag && format != GL_COLOR_INDEX) {
1376          pipe_sampler_view_reference(&sv[1],
1377                                      st->pixel_xfer.pixelmap_sampler_view);
1378          num_sampler_view++;
1379       }
1380 
1381       /* compiling a new fragment shader variant added new state constants
1382        * into the constant buffer, we need to update them
1383        */
1384       st_upload_constants(st, &st->fp->Base);
1385    }
1386 
1387    {
1388       /* create sampler view for the image */
1389       struct pipe_sampler_view templ;
1390 
1391       u_sampler_view_default_template(&templ, pt, pt->format);
1392       /* Set up the sampler view's swizzle */
1393       setup_sampler_swizzle(&templ, format, type);
1394 
1395       sv[0] = st->pipe->create_sampler_view(st->pipe, pt, &templ);
1396    }
1397    if (!sv[0]) {
1398       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDrawPixels");
1399       pipe_resource_reference(&pt, NULL);
1400       return;
1401    }
1402 
1403    /* Create a second sampler view to read stencil.  The stencil is
1404     * written using the shader stencil export functionality.
1405     */
1406    if (write_stencil) {
1407       enum pipe_format stencil_format =
1408          util_format_stencil_only(pt->format);
1409       /* we should not be doing pixel map/transfer (see above) */
1410       assert(num_sampler_view == 1);
1411       sv[1] = st_create_texture_sampler_view_format(st->pipe, pt,
1412                                                     stencil_format);
1413       if (!sv[1]) {
1414          _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDrawPixels");
1415          pipe_resource_reference(&pt, NULL);
1416          pipe_sampler_view_reference(&sv[0], NULL);
1417          return;
1418       }
1419       num_sampler_view++;
1420    }
1421 
1422    draw_textured_quad(ctx, x, y, get_effective_raster_z(ctx),
1423                       width, height,
1424                       ctx->Pixel.ZoomX, ctx->Pixel.ZoomY,
1425                       sv,
1426                       num_sampler_view,
1427                       st->passthrough_vs,
1428                       driver_fp, fpv,
1429                       ctx->Current.RasterColor,
1430                       GL_FALSE, write_depth, write_stencil);
1431    pipe_sampler_view_reference(&sv[0], NULL);
1432    if (num_sampler_view > 1)
1433       pipe_sampler_view_reference(&sv[1], NULL);
1434 
1435    /* free the texture (but may persist in the cache) */
1436    pipe_resource_reference(&pt, NULL);
1437 }
1438 
1439 
1440 
1441 /**
1442  * Software fallback for glCopyPixels(GL_STENCIL).
1443  */
1444 static void
copy_stencil_pixels(struct gl_context * ctx,GLint srcx,GLint srcy,GLsizei width,GLsizei height,GLint dstx,GLint dsty)1445 copy_stencil_pixels(struct gl_context *ctx, GLint srcx, GLint srcy,
1446                     GLsizei width, GLsizei height,
1447                     GLint dstx, GLint dsty)
1448 {
1449    struct st_renderbuffer *rbDraw;
1450    struct pipe_context *pipe = st_context(ctx)->pipe;
1451    enum pipe_map_flags usage;
1452    struct pipe_transfer *ptDraw;
1453    ubyte *drawMap;
1454    ubyte *buffer;
1455    int i;
1456 
1457    buffer = malloc(width * height * sizeof(ubyte));
1458    if (!buffer) {
1459       _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCopyPixels(stencil)");
1460       return;
1461    }
1462 
1463    /* Get the dest renderbuffer */
1464    rbDraw = st_renderbuffer(ctx->DrawBuffer->
1465                             Attachment[BUFFER_STENCIL].Renderbuffer);
1466 
1467    /* this will do stencil pixel transfer ops */
1468    _mesa_readpixels(ctx, srcx, srcy, width, height,
1469                     GL_STENCIL_INDEX, GL_UNSIGNED_BYTE,
1470                     &ctx->DefaultPacking, buffer);
1471 
1472    if (0) {
1473       /* debug code: dump stencil values */
1474       GLint row, col;
1475       for (row = 0; row < height; row++) {
1476          printf("%3d: ", row);
1477          for (col = 0; col < width; col++) {
1478             printf("%02x ", buffer[col + row * width]);
1479          }
1480          printf("\n");
1481       }
1482    }
1483 
1484    if (_mesa_is_format_packed_depth_stencil(rbDraw->Base.Format))
1485       usage = PIPE_MAP_READ_WRITE;
1486    else
1487       usage = PIPE_MAP_WRITE;
1488 
1489    if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
1490       dsty = rbDraw->Base.Height - dsty - height;
1491    }
1492 
1493    assert(util_format_get_blockwidth(rbDraw->texture->format) == 1);
1494    assert(util_format_get_blockheight(rbDraw->texture->format) == 1);
1495 
1496    /* map the stencil buffer */
1497    drawMap = pipe_transfer_map(pipe,
1498                                rbDraw->texture,
1499                                rbDraw->surface->u.tex.level,
1500                                rbDraw->surface->u.tex.first_layer,
1501                                usage, dstx, dsty,
1502                                width, height, &ptDraw);
1503 
1504    /* draw */
1505    /* XXX PixelZoom not handled yet */
1506    for (i = 0; i < height; i++) {
1507       ubyte *dst;
1508       const ubyte *src;
1509       int y;
1510 
1511       y = i;
1512 
1513       if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
1514          y = height - y - 1;
1515       }
1516 
1517       dst = drawMap + y * ptDraw->stride;
1518       src = buffer + i * width;
1519 
1520       _mesa_pack_ubyte_stencil_row(rbDraw->Base.Format, width, src, dst);
1521    }
1522 
1523    free(buffer);
1524 
1525    /* unmap the stencil buffer */
1526    pipe_transfer_unmap(pipe, ptDraw);
1527 }
1528 
1529 
1530 /**
1531  * Return renderbuffer to use for reading color pixels for glCopyPixels
1532  */
1533 static struct st_renderbuffer *
st_get_color_read_renderbuffer(struct gl_context * ctx)1534 st_get_color_read_renderbuffer(struct gl_context *ctx)
1535 {
1536    struct gl_framebuffer *fb = ctx->ReadBuffer;
1537    struct st_renderbuffer *strb =
1538       st_renderbuffer(fb->_ColorReadBuffer);
1539 
1540    return strb;
1541 }
1542 
1543 
1544 /**
1545  * Try to do a glCopyPixels for simple cases with a blit by calling
1546  * pipe->blit().
1547  *
1548  * We can do this when we're copying color pixels (depth/stencil
1549  * eventually) with no pixel zoom, no pixel transfer ops, no
1550  * per-fragment ops, and the src/dest regions don't overlap.
1551  */
1552 static GLboolean
blit_copy_pixels(struct gl_context * ctx,GLint srcx,GLint srcy,GLsizei width,GLsizei height,GLint dstx,GLint dsty,GLenum type)1553 blit_copy_pixels(struct gl_context *ctx, GLint srcx, GLint srcy,
1554                  GLsizei width, GLsizei height,
1555                  GLint dstx, GLint dsty, GLenum type)
1556 {
1557    struct st_context *st = st_context(ctx);
1558    struct pipe_context *pipe = st->pipe;
1559    struct pipe_screen *screen = pipe->screen;
1560    struct gl_pixelstore_attrib pack, unpack;
1561    GLint readX, readY, readW, readH, drawX, drawY, drawW, drawH;
1562 
1563    if (type == GL_DEPTH_STENCIL_TO_RGBA_NV || type == GL_DEPTH_STENCIL_TO_BGRA_NV)
1564       return GL_FALSE;
1565 
1566    if (ctx->Pixel.ZoomX == 1.0 &&
1567        ctx->Pixel.ZoomY == 1.0 &&
1568        (type != GL_COLOR ||
1569         (ctx->_ImageTransferState == 0x0 &&
1570          !ctx->Color.BlendEnabled &&
1571          !ctx->Color.AlphaEnabled &&
1572          (!ctx->Color.ColorLogicOpEnabled || ctx->Color.LogicOp == GL_COPY) &&
1573          !ctx->Depth.BoundsTest &&
1574          !ctx->Depth.Test &&
1575          !ctx->Fog.Enabled &&
1576          !ctx->Stencil.Enabled &&
1577          !ctx->FragmentProgram.Enabled &&
1578          !ctx->VertexProgram.Enabled &&
1579          !ctx->_Shader->CurrentProgram[MESA_SHADER_FRAGMENT] &&
1580          !_mesa_ati_fragment_shader_enabled(ctx) &&
1581          ctx->DrawBuffer->_NumColorDrawBuffers == 1)) &&
1582        !ctx->Query.CondRenderQuery &&
1583        !ctx->Query.CurrentOcclusionObject) {
1584       struct st_renderbuffer *rbRead, *rbDraw;
1585 
1586       /*
1587        * Clip the read region against the src buffer bounds.
1588        * We'll still allocate a temporary buffer/texture for the original
1589        * src region size but we'll only read the region which is on-screen.
1590        * This may mean that we draw garbage pixels into the dest region, but
1591        * that's expected.
1592        */
1593       readX = srcx;
1594       readY = srcy;
1595       readW = width;
1596       readH = height;
1597       pack = ctx->DefaultPacking;
1598       if (!_mesa_clip_readpixels(ctx, &readX, &readY, &readW, &readH, &pack))
1599          return GL_TRUE; /* all done */
1600 
1601       /* clip against dest buffer bounds and scissor box */
1602       drawX = dstx + pack.SkipPixels;
1603       drawY = dsty + pack.SkipRows;
1604       unpack = pack;
1605       if (!_mesa_clip_drawpixels(ctx, &drawX, &drawY, &readW, &readH, &unpack))
1606          return GL_TRUE; /* all done */
1607 
1608       readX = readX - pack.SkipPixels + unpack.SkipPixels;
1609       readY = readY - pack.SkipRows + unpack.SkipRows;
1610 
1611       drawW = readW;
1612       drawH = readH;
1613 
1614       if (type == GL_COLOR) {
1615          rbRead = st_get_color_read_renderbuffer(ctx);
1616          rbDraw = st_renderbuffer(ctx->DrawBuffer->_ColorDrawBuffers[0]);
1617       } else if (type == GL_DEPTH || type == GL_DEPTH_STENCIL) {
1618          rbRead = st_renderbuffer(ctx->ReadBuffer->Attachment[BUFFER_DEPTH].Renderbuffer);
1619          rbDraw = st_renderbuffer(ctx->DrawBuffer->Attachment[BUFFER_DEPTH].Renderbuffer);
1620       } else if (type == GL_STENCIL) {
1621          rbRead = st_renderbuffer(ctx->ReadBuffer->Attachment[BUFFER_STENCIL].Renderbuffer);
1622          rbDraw = st_renderbuffer(ctx->DrawBuffer->Attachment[BUFFER_STENCIL].Renderbuffer);
1623       } else {
1624          return false;
1625       }
1626 
1627       /* Flip src/dst position depending on the orientation of buffers. */
1628       if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1629          readY = rbRead->Base.Height - readY;
1630          readH = -readH;
1631       }
1632 
1633       if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
1634          /* We can't flip the destination for pipe->blit, so we only adjust
1635           * its position and flip the source.
1636           */
1637          drawY = rbDraw->Base.Height - drawY - drawH;
1638          readY += readH;
1639          readH = -readH;
1640       }
1641 
1642       if (rbRead != rbDraw ||
1643           !_mesa_regions_overlap(readX, readY, readX + readW, readY + readH,
1644                                  drawX, drawY, drawX + drawW, drawY + drawH)) {
1645          struct pipe_blit_info blit;
1646 
1647          memset(&blit, 0, sizeof(blit));
1648          blit.src.resource = rbRead->texture;
1649          blit.src.level = rbRead->surface->u.tex.level;
1650          blit.src.format = rbRead->texture->format;
1651          blit.src.box.x = readX;
1652          blit.src.box.y = readY;
1653          blit.src.box.z = rbRead->surface->u.tex.first_layer;
1654          blit.src.box.width = readW;
1655          blit.src.box.height = readH;
1656          blit.src.box.depth = 1;
1657          blit.dst.resource = rbDraw->texture;
1658          blit.dst.level = rbDraw->surface->u.tex.level;
1659          blit.dst.format = rbDraw->texture->format;
1660          blit.dst.box.x = drawX;
1661          blit.dst.box.y = drawY;
1662          blit.dst.box.z = rbDraw->surface->u.tex.first_layer;
1663          blit.dst.box.width = drawW;
1664          blit.dst.box.height = drawH;
1665          blit.dst.box.depth = 1;
1666          blit.filter = PIPE_TEX_FILTER_NEAREST;
1667 
1668          if (type == GL_COLOR)
1669             blit.mask |= PIPE_MASK_RGBA;
1670          if (type == GL_DEPTH)
1671             blit.mask |= PIPE_MASK_Z;
1672          if (type == GL_STENCIL)
1673             blit.mask |= PIPE_MASK_S;
1674          if (type == GL_DEPTH_STENCIL)
1675             blit.mask |= PIPE_MASK_ZS;
1676 
1677          if (ctx->DrawBuffer != ctx->WinSysDrawBuffer)
1678             st_window_rectangles_to_blit(ctx, &blit);
1679 
1680          if (screen->is_format_supported(screen, blit.src.format,
1681                                          blit.src.resource->target,
1682                                          blit.src.resource->nr_samples,
1683                                          blit.src.resource->nr_storage_samples,
1684                                          PIPE_BIND_SAMPLER_VIEW) &&
1685              screen->is_format_supported(screen, blit.dst.format,
1686                                          blit.dst.resource->target,
1687                                          blit.dst.resource->nr_samples,
1688                                          blit.dst.resource->nr_storage_samples,
1689                                          PIPE_BIND_RENDER_TARGET)) {
1690             pipe->blit(pipe, &blit);
1691             return GL_TRUE;
1692          }
1693       }
1694    }
1695 
1696    return GL_FALSE;
1697 }
1698 
1699 
1700 static void
st_CopyPixels(struct gl_context * ctx,GLint srcx,GLint srcy,GLsizei width,GLsizei height,GLint dstx,GLint dsty,GLenum type)1701 st_CopyPixels(struct gl_context *ctx, GLint srcx, GLint srcy,
1702               GLsizei width, GLsizei height,
1703               GLint dstx, GLint dsty, GLenum type)
1704 {
1705    struct st_context *st = st_context(ctx);
1706    struct pipe_context *pipe = st->pipe;
1707    struct pipe_screen *screen = pipe->screen;
1708    struct st_renderbuffer *rbRead;
1709    void *driver_fp;
1710    struct pipe_resource *pt;
1711    struct pipe_sampler_view *sv[2] = { NULL };
1712    struct st_fp_variant *fpv = NULL;
1713    int num_sampler_view = 1;
1714    enum pipe_format srcFormat;
1715    unsigned srcBind;
1716    GLboolean invertTex = GL_FALSE;
1717    GLint readX, readY, readW, readH;
1718    struct gl_pixelstore_attrib pack = ctx->DefaultPacking;
1719    GLboolean write_stencil = GL_FALSE;
1720    GLboolean write_depth = GL_FALSE;
1721 
1722    _mesa_update_draw_buffer_bounds(ctx, ctx->DrawBuffer);
1723 
1724    st_flush_bitmap_cache(st);
1725    st_invalidate_readpix_cache(st);
1726 
1727    st_validate_state(st, ST_PIPELINE_META);
1728 
1729    if (blit_copy_pixels(ctx, srcx, srcy, width, height, dstx, dsty, type))
1730       return;
1731 
1732    /* fallback if the driver can't do stencil exports */
1733    if (type == GL_DEPTH_STENCIL &&
1734       !pipe->screen->get_param(pipe->screen, PIPE_CAP_SHADER_STENCIL_EXPORT)) {
1735       st_CopyPixels(ctx, srcx, srcy, width, height, dstx, dsty, GL_STENCIL);
1736       st_CopyPixels(ctx, srcx, srcy, width, height, dstx, dsty, GL_DEPTH);
1737       return;
1738    }
1739 
1740    /* fallback if the driver can't do stencil exports */
1741    if (type == GL_STENCIL &&
1742        !pipe->screen->get_param(pipe->screen, PIPE_CAP_SHADER_STENCIL_EXPORT)) {
1743       copy_stencil_pixels(ctx, srcx, srcy, width, height, dstx, dsty);
1744       return;
1745    }
1746 
1747    /*
1748     * The subsequent code implements glCopyPixels by copying the source
1749     * pixels into a temporary texture that's then applied to a textured quad.
1750     * When we draw the textured quad, all the usual per-fragment operations
1751     * are handled.
1752     */
1753 
1754    st_make_passthrough_vertex_shader(st);
1755 
1756    /*
1757     * Get vertex/fragment shaders
1758     */
1759    if (type == GL_COLOR) {
1760       fpv = get_color_fp_variant(st);
1761 
1762       rbRead = st_get_color_read_renderbuffer(ctx);
1763 
1764       driver_fp = fpv->base.driver_shader;
1765 
1766       if (ctx->Pixel.MapColorFlag) {
1767          pipe_sampler_view_reference(&sv[1],
1768                                      st->pixel_xfer.pixelmap_sampler_view);
1769          num_sampler_view++;
1770       }
1771 
1772       /* compiling a new fragment shader variant added new state constants
1773        * into the constant buffer, we need to update them
1774        */
1775       st_upload_constants(st, &st->fp->Base);
1776    } else if (type == GL_DEPTH) {
1777       rbRead = st_renderbuffer(ctx->ReadBuffer->
1778                                Attachment[BUFFER_DEPTH].Renderbuffer);
1779       driver_fp = get_drawpix_z_stencil_program(st, GL_TRUE, GL_FALSE);
1780    } else if (type == GL_STENCIL) {
1781       rbRead = st_renderbuffer(ctx->ReadBuffer->
1782                                Attachment[BUFFER_STENCIL].Renderbuffer);
1783       driver_fp = get_drawpix_z_stencil_program(st, GL_FALSE, GL_TRUE);
1784    } else if (type == GL_DEPTH_STENCIL) {
1785       rbRead = st_renderbuffer(ctx->ReadBuffer->
1786                                Attachment[BUFFER_DEPTH].Renderbuffer);
1787       driver_fp = get_drawpix_z_stencil_program(st, GL_TRUE, GL_TRUE);
1788    } else {
1789       assert(type == GL_DEPTH_STENCIL_TO_RGBA_NV || type == GL_DEPTH_STENCIL_TO_BGRA_NV);
1790       rbRead = st_renderbuffer(ctx->ReadBuffer->
1791                                Attachment[BUFFER_DEPTH].Renderbuffer);
1792       if (type == GL_DEPTH_STENCIL_TO_RGBA_NV)
1793          driver_fp = get_drawpix_zs_to_color_program(st, GL_TRUE);
1794       else
1795          driver_fp = get_drawpix_zs_to_color_program(st, GL_FALSE);
1796       if (!driver_fp) {
1797          assert(0 && "operation not supported by CopyPixels implemetation");
1798          return;
1799       }
1800    }
1801 
1802 
1803    /* Choose the format for the temporary texture. */
1804    srcFormat = rbRead->texture->format;
1805    srcBind = PIPE_BIND_SAMPLER_VIEW |
1806       (type == GL_COLOR ? PIPE_BIND_RENDER_TARGET : PIPE_BIND_DEPTH_STENCIL);
1807 
1808    if (!screen->is_format_supported(screen, srcFormat, st->internal_target, 0,
1809                                     0, srcBind)) {
1810       /* srcFormat is non-renderable. Find a compatible renderable format. */
1811       if (type == GL_DEPTH) {
1812          srcFormat = st_choose_format(st, GL_DEPTH_COMPONENT, GL_NONE,
1813                                       GL_NONE, st->internal_target, 0, 0,
1814                                       srcBind, false, false);
1815       }
1816       else if (type == GL_STENCIL) {
1817          /* can't use texturing, fallback to copy */
1818          copy_stencil_pixels(ctx, srcx, srcy, width, height, dstx, dsty);
1819          return;
1820       }
1821       else {
1822          assert(type == GL_COLOR);
1823 
1824          if (util_format_is_float(srcFormat)) {
1825             srcFormat = st_choose_format(st, GL_RGBA32F, GL_NONE,
1826                                          GL_NONE, st->internal_target, 0, 0,
1827                                          srcBind, false, false);
1828          }
1829          else if (util_format_is_pure_sint(srcFormat)) {
1830             srcFormat = st_choose_format(st, GL_RGBA32I, GL_NONE,
1831                                          GL_NONE, st->internal_target, 0, 0,
1832                                          srcBind, false, false);
1833          }
1834          else if (util_format_is_pure_uint(srcFormat)) {
1835             srcFormat = st_choose_format(st, GL_RGBA32UI, GL_NONE,
1836                                          GL_NONE, st->internal_target, 0, 0,
1837                                          srcBind, false, false);
1838          }
1839          else if (util_format_is_snorm(srcFormat)) {
1840             srcFormat = st_choose_format(st, GL_RGBA16_SNORM, GL_NONE,
1841                                          GL_NONE, st->internal_target, 0, 0,
1842                                          srcBind, false, false);
1843          }
1844          else {
1845             srcFormat = st_choose_format(st, GL_RGBA, GL_NONE,
1846                                          GL_NONE, st->internal_target, 0, 0,
1847                                          srcBind, false, false);
1848          }
1849       }
1850 
1851       if (srcFormat == PIPE_FORMAT_NONE) {
1852          assert(0 && "cannot choose a format for src of CopyPixels");
1853          return;
1854       }
1855    }
1856 
1857    /* Invert src region if needed */
1858    if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1859       srcy = ctx->ReadBuffer->Height - srcy - height;
1860       invertTex = !invertTex;
1861    }
1862 
1863    /* Clip the read region against the src buffer bounds.
1864     * We'll still allocate a temporary buffer/texture for the original
1865     * src region size but we'll only read the region which is on-screen.
1866     * This may mean that we draw garbage pixels into the dest region, but
1867     * that's expected.
1868     */
1869    readX = srcx;
1870    readY = srcy;
1871    readW = width;
1872    readH = height;
1873    if (!_mesa_clip_readpixels(ctx, &readX, &readY, &readW, &readH, &pack)) {
1874       /* The source region is completely out of bounds.  Do nothing.
1875        * The GL spec says "Results of copies from outside the window,
1876        * or from regions of the window that are not exposed, are
1877        * hardware dependent and undefined."
1878        */
1879       return;
1880    }
1881 
1882    readW = MAX2(0, readW);
1883    readH = MAX2(0, readH);
1884 
1885    /* Allocate the temporary texture. */
1886    pt = alloc_texture(st, width, height, srcFormat, srcBind);
1887    if (!pt)
1888       return;
1889 
1890    sv[0] = st_create_texture_sampler_view(st->pipe, pt);
1891    if (!sv[0]) {
1892       pipe_resource_reference(&pt, NULL);
1893       return;
1894    }
1895 
1896    /* Create a second sampler view to read stencil */
1897    if (type == GL_STENCIL || type == GL_DEPTH_STENCIL ||
1898        type == GL_DEPTH_STENCIL_TO_RGBA_NV || type == GL_DEPTH_STENCIL_TO_BGRA_NV) {
1899       write_stencil = GL_TRUE;
1900       if (type == GL_DEPTH_STENCIL)
1901          write_depth = GL_TRUE;
1902       if (type == GL_DEPTH_STENCIL_TO_RGBA_NV || type == GL_DEPTH_STENCIL_TO_BGRA_NV) {
1903          write_depth = FALSE;
1904          write_stencil = FALSE;
1905       }
1906 
1907       enum pipe_format stencil_format =
1908          util_format_stencil_only(pt->format);
1909       /* we should not be doing pixel map/transfer (see above) */
1910       assert(num_sampler_view == 1);
1911       sv[1] = st_create_texture_sampler_view_format(st->pipe, pt,
1912                                                     stencil_format);
1913       if (!sv[1]) {
1914          _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCopyPixels");
1915          pipe_resource_reference(&pt, NULL);
1916          pipe_sampler_view_reference(&sv[0], NULL);
1917          return;
1918       }
1919       num_sampler_view++;
1920    }
1921    /* Copy the src region to the temporary texture. */
1922    {
1923       struct pipe_blit_info blit;
1924 
1925       memset(&blit, 0, sizeof(blit));
1926       blit.src.resource = rbRead->texture;
1927       blit.src.level = rbRead->surface->u.tex.level;
1928       blit.src.format = rbRead->texture->format;
1929       blit.src.box.x = readX;
1930       blit.src.box.y = readY;
1931       blit.src.box.z = rbRead->surface->u.tex.first_layer;
1932       blit.src.box.width = readW;
1933       blit.src.box.height = readH;
1934       blit.src.box.depth = 1;
1935       blit.dst.resource = pt;
1936       blit.dst.level = 0;
1937       blit.dst.format = pt->format;
1938       blit.dst.box.x = pack.SkipPixels;
1939       blit.dst.box.y = pack.SkipRows;
1940       blit.dst.box.z = 0;
1941       blit.dst.box.width = readW;
1942       blit.dst.box.height = readH;
1943       blit.dst.box.depth = 1;
1944       if (type == GL_DEPTH)
1945           blit.mask = util_format_get_mask(pt->format) & ~PIPE_MASK_S;
1946       else if (type == GL_STENCIL)
1947           blit.mask = util_format_get_mask(pt->format) & ~PIPE_MASK_Z;
1948       else
1949          blit.mask = util_format_get_mask(pt->format);
1950       blit.filter = PIPE_TEX_FILTER_NEAREST;
1951 
1952       pipe->blit(pipe, &blit);
1953    }
1954 
1955    /* OK, the texture 'pt' contains the src image/pixels.  Now draw a
1956     * textured quad with that texture.
1957     */
1958 
1959    draw_textured_quad(ctx, dstx, dsty, get_effective_raster_z(ctx),
1960                       width, height, ctx->Pixel.ZoomX, ctx->Pixel.ZoomY,
1961                       sv,
1962                       num_sampler_view,
1963                       st->passthrough_vs,
1964                       driver_fp, fpv,
1965                       ctx->Current.Attrib[VERT_ATTRIB_COLOR0],
1966                       invertTex, write_depth, write_stencil);
1967 
1968    pipe_resource_reference(&pt, NULL);
1969    pipe_sampler_view_reference(&sv[0], NULL);
1970 }
1971 
1972 
1973 
st_init_drawpixels_functions(struct dd_function_table * functions)1974 void st_init_drawpixels_functions(struct dd_function_table *functions)
1975 {
1976    functions->DrawPixels = st_DrawPixels;
1977    functions->CopyPixels = st_CopyPixels;
1978 }
1979 
1980 
1981 void
st_destroy_drawpix(struct st_context * st)1982 st_destroy_drawpix(struct st_context *st)
1983 {
1984    GLuint i;
1985 
1986    for (i = 0; i < ARRAY_SIZE(st->drawpix.zs_shaders); i++) {
1987       if (st->drawpix.zs_shaders[i])
1988          st->pipe->delete_fs_state(st->pipe, st->drawpix.zs_shaders[i]);
1989    }
1990 
1991    if (st->passthrough_vs)
1992       st->pipe->delete_vs_state(st->pipe, st->passthrough_vs);
1993 
1994    /* Free cache data */
1995    for (i = 0; i < ARRAY_SIZE(st->drawpix_cache.entries); i++) {
1996       struct drawpix_cache_entry *entry = &st->drawpix_cache.entries[i];
1997       free(entry->image);
1998       pipe_resource_reference(&entry->texture, NULL);
1999    }
2000 }
2001