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