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