st_cb_drawpixels.c revision ea6f035ae90895bd4ee3247408eb179dfdf96d22
1/**************************************************************************
2 *
3 * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
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 TUNGSTEN GRAPHICS 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/imports.h"
34#include "main/image.h"
35#include "main/bufferobj.h"
36#include "main/format_pack.h"
37#include "main/macros.h"
38#include "main/mfeatures.h"
39#include "main/mtypes.h"
40#include "main/pack.h"
41#include "main/pbo.h"
42#include "main/readpix.h"
43#include "main/texformat.h"
44#include "main/teximage.h"
45#include "main/texstore.h"
46#include "main/glformats.h"
47#include "program/program.h"
48#include "program/prog_print.h"
49#include "program/prog_instruction.h"
50
51#include "st_atom.h"
52#include "st_atom_constbuf.h"
53#include "st_cb_drawpixels.h"
54#include "st_cb_readpixels.h"
55#include "st_cb_fbo.h"
56#include "st_context.h"
57#include "st_debug.h"
58#include "st_format.h"
59#include "st_program.h"
60#include "st_texture.h"
61
62#include "pipe/p_context.h"
63#include "pipe/p_defines.h"
64#include "tgsi/tgsi_ureg.h"
65#include "util/u_draw_quad.h"
66#include "util/u_format.h"
67#include "util/u_inlines.h"
68#include "util/u_math.h"
69#include "util/u_tile.h"
70#include "util/u_upload_mgr.h"
71#include "cso_cache/cso_context.h"
72
73
74#if FEATURE_drawpix
75
76/**
77 * Check if the given program is:
78 * 0: MOVE result.color, fragment.color;
79 * 1: END;
80 */
81static GLboolean
82is_passthrough_program(const struct gl_fragment_program *prog)
83{
84   if (prog->Base.NumInstructions == 2) {
85      const struct prog_instruction *inst = prog->Base.Instructions;
86      if (inst[0].Opcode == OPCODE_MOV &&
87          inst[1].Opcode == OPCODE_END &&
88          inst[0].DstReg.File == PROGRAM_OUTPUT &&
89          inst[0].DstReg.Index == FRAG_RESULT_COLOR &&
90          inst[0].DstReg.WriteMask == WRITEMASK_XYZW &&
91          inst[0].SrcReg[0].File == PROGRAM_INPUT &&
92          inst[0].SrcReg[0].Index == FRAG_ATTRIB_COL0 &&
93          inst[0].SrcReg[0].Swizzle == SWIZZLE_XYZW) {
94         return GL_TRUE;
95      }
96   }
97   return GL_FALSE;
98}
99
100
101/**
102 * Returns a fragment program which implements the current pixel transfer ops.
103 */
104static struct gl_fragment_program *
105get_glsl_pixel_transfer_program(struct st_context *st,
106                                struct st_fragment_program *orig)
107{
108   int pixelMaps = 0, scaleAndBias = 0;
109   struct gl_context *ctx = st->ctx;
110   struct st_fragment_program *fp = (struct st_fragment_program *)
111      ctx->Driver.NewProgram(ctx, GL_FRAGMENT_PROGRAM_ARB, 0);
112
113   if (!fp)
114      return NULL;
115
116   if (ctx->Pixel.RedBias != 0.0 || ctx->Pixel.RedScale != 1.0 ||
117       ctx->Pixel.GreenBias != 0.0 || ctx->Pixel.GreenScale != 1.0 ||
118       ctx->Pixel.BlueBias != 0.0 || ctx->Pixel.BlueScale != 1.0 ||
119       ctx->Pixel.AlphaBias != 0.0 || ctx->Pixel.AlphaScale != 1.0) {
120      scaleAndBias = 1;
121   }
122
123   pixelMaps = ctx->Pixel.MapColorFlag;
124
125   if (pixelMaps) {
126      /* create the colormap/texture now if not already done */
127      if (!st->pixel_xfer.pixelmap_texture) {
128         st->pixel_xfer.pixelmap_texture = st_create_color_map_texture(ctx);
129         st->pixel_xfer.pixelmap_sampler_view =
130            st_create_texture_sampler_view(st->pipe,
131                                           st->pixel_xfer.pixelmap_texture);
132      }
133   }
134
135   get_pixel_transfer_visitor(fp, orig->glsl_to_tgsi,
136                              scaleAndBias, pixelMaps);
137
138   return &fp->Base;
139}
140
141
142/**
143 * Make fragment shader for glDraw/CopyPixels.  This shader is made
144 * by combining the pixel transfer shader with the user-defined shader.
145 * \param fpIn  the current/incoming fragment program
146 * \param fpOut  returns the combined fragment program
147 */
148void
149st_make_drawpix_fragment_program(struct st_context *st,
150                                 struct gl_fragment_program *fpIn,
151                                 struct gl_fragment_program **fpOut)
152{
153   struct gl_program *newProg;
154   struct st_fragment_program *stfp = (struct st_fragment_program *) fpIn;
155
156   if (is_passthrough_program(fpIn)) {
157      newProg = (struct gl_program *) _mesa_clone_fragment_program(st->ctx,
158                                             &st->pixel_xfer.program->Base);
159   }
160   else if (stfp->glsl_to_tgsi != NULL) {
161      newProg = (struct gl_program *) get_glsl_pixel_transfer_program(st, stfp);
162   }
163   else {
164#if 0
165      /* debug */
166      printf("Base program:\n");
167      _mesa_print_program(&fpIn->Base);
168      printf("DrawPix program:\n");
169      _mesa_print_program(&st->pixel_xfer.program->Base.Base);
170#endif
171      newProg = _mesa_combine_programs(st->ctx,
172                                       &st->pixel_xfer.program->Base.Base,
173                                       &fpIn->Base);
174   }
175
176#if 0
177   /* debug */
178   printf("Combined DrawPixels program:\n");
179   _mesa_print_program(newProg);
180   printf("InputsRead: 0x%x\n", newProg->InputsRead);
181   printf("OutputsWritten: 0x%x\n", newProg->OutputsWritten);
182   _mesa_print_parameter_list(newProg->Parameters);
183#endif
184
185   *fpOut = (struct gl_fragment_program *) newProg;
186}
187
188
189/**
190 * Create fragment program that does a TEX() instruction to get a Z and/or
191 * stencil value value, then writes to FRAG_RESULT_DEPTH/FRAG_RESULT_STENCIL.
192 * Used for glDrawPixels(GL_DEPTH_COMPONENT / GL_STENCIL_INDEX).
193 * Pass fragment color through as-is.
194 * \return pointer to the gl_fragment program
195 */
196struct gl_fragment_program *
197st_make_drawpix_z_stencil_program(struct st_context *st,
198                                  GLboolean write_depth,
199                                  GLboolean write_stencil)
200{
201   struct gl_context *ctx = st->ctx;
202   struct gl_program *p;
203   struct gl_fragment_program *fp;
204   GLuint ic = 0;
205   const GLuint shaderIndex = write_depth * 2 + write_stencil;
206
207   assert(shaderIndex < Elements(st->drawpix.shaders));
208
209   if (st->drawpix.shaders[shaderIndex]) {
210      /* already have the proper shader */
211      return st->drawpix.shaders[shaderIndex];
212   }
213
214   /*
215    * Create shader now
216    */
217   p = ctx->Driver.NewProgram(ctx, GL_FRAGMENT_PROGRAM_ARB, 0);
218   if (!p)
219      return NULL;
220
221   p->NumInstructions = write_depth ? 3 : 1;
222   p->NumInstructions += write_stencil ? 1 : 0;
223
224   p->Instructions = _mesa_alloc_instructions(p->NumInstructions);
225   if (!p->Instructions) {
226      ctx->Driver.DeleteProgram(ctx, p);
227      return NULL;
228   }
229   _mesa_init_instructions(p->Instructions, p->NumInstructions);
230
231   if (write_depth) {
232      /* TEX result.depth, fragment.texcoord[0], texture[0], 2D; */
233      p->Instructions[ic].Opcode = OPCODE_TEX;
234      p->Instructions[ic].DstReg.File = PROGRAM_OUTPUT;
235      p->Instructions[ic].DstReg.Index = FRAG_RESULT_DEPTH;
236      p->Instructions[ic].DstReg.WriteMask = WRITEMASK_Z;
237      p->Instructions[ic].SrcReg[0].File = PROGRAM_INPUT;
238      p->Instructions[ic].SrcReg[0].Index = FRAG_ATTRIB_TEX0;
239      p->Instructions[ic].TexSrcUnit = 0;
240      p->Instructions[ic].TexSrcTarget = TEXTURE_2D_INDEX;
241      ic++;
242      /* MOV result.color, fragment.color; */
243      p->Instructions[ic].Opcode = OPCODE_MOV;
244      p->Instructions[ic].DstReg.File = PROGRAM_OUTPUT;
245      p->Instructions[ic].DstReg.Index = FRAG_RESULT_COLOR;
246      p->Instructions[ic].SrcReg[0].File = PROGRAM_INPUT;
247      p->Instructions[ic].SrcReg[0].Index = FRAG_ATTRIB_COL0;
248      ic++;
249   }
250
251   if (write_stencil) {
252      /* TEX result.stencil, fragment.texcoord[0], texture[0], 2D; */
253      p->Instructions[ic].Opcode = OPCODE_TEX;
254      p->Instructions[ic].DstReg.File = PROGRAM_OUTPUT;
255      p->Instructions[ic].DstReg.Index = FRAG_RESULT_STENCIL;
256      p->Instructions[ic].DstReg.WriteMask = WRITEMASK_Y;
257      p->Instructions[ic].SrcReg[0].File = PROGRAM_INPUT;
258      p->Instructions[ic].SrcReg[0].Index = FRAG_ATTRIB_TEX0;
259      p->Instructions[ic].TexSrcUnit = 1;
260      p->Instructions[ic].TexSrcTarget = TEXTURE_2D_INDEX;
261      ic++;
262   }
263
264   /* END; */
265   p->Instructions[ic++].Opcode = OPCODE_END;
266
267   assert(ic == p->NumInstructions);
268
269   p->InputsRead = FRAG_BIT_TEX0 | FRAG_BIT_COL0;
270   p->OutputsWritten = 0;
271   if (write_depth) {
272      p->OutputsWritten |= BITFIELD64_BIT(FRAG_RESULT_DEPTH);
273      p->OutputsWritten |= BITFIELD64_BIT(FRAG_RESULT_COLOR);
274   }
275   if (write_stencil)
276      p->OutputsWritten |= BITFIELD64_BIT(FRAG_RESULT_STENCIL);
277
278   p->SamplersUsed =  0x1;  /* sampler 0 (bit 0) is used */
279   if (write_stencil)
280      p->SamplersUsed |= 1 << 1;
281
282   fp = (struct gl_fragment_program *) p;
283
284   /* save the new shader */
285   st->drawpix.shaders[shaderIndex] = fp;
286
287   return fp;
288}
289
290
291/**
292 * Create a simple vertex shader that just passes through the
293 * vertex position and texcoord (and optionally, color).
294 */
295static void *
296make_passthrough_vertex_shader(struct st_context *st,
297                               GLboolean passColor)
298{
299   if (!st->drawpix.vert_shaders[passColor]) {
300      struct ureg_program *ureg = ureg_create( TGSI_PROCESSOR_VERTEX );
301
302      if (ureg == NULL)
303         return NULL;
304
305      /* MOV result.pos, vertex.pos; */
306      ureg_MOV(ureg,
307               ureg_DECL_output( ureg, TGSI_SEMANTIC_POSITION, 0 ),
308               ureg_DECL_vs_input( ureg, 0 ));
309
310      /* MOV result.texcoord0, vertex.attr[1]; */
311      ureg_MOV(ureg,
312               ureg_DECL_output( ureg, TGSI_SEMANTIC_GENERIC, 0 ),
313               ureg_DECL_vs_input( ureg, 1 ));
314
315      if (passColor) {
316         /* MOV result.color0, vertex.attr[2]; */
317         ureg_MOV(ureg,
318                  ureg_DECL_output( ureg, TGSI_SEMANTIC_COLOR, 0 ),
319                  ureg_DECL_vs_input( ureg, 2 ));
320      }
321
322      ureg_END( ureg );
323
324      st->drawpix.vert_shaders[passColor] =
325         ureg_create_shader_and_destroy( ureg, st->pipe );
326   }
327
328   return st->drawpix.vert_shaders[passColor];
329}
330
331
332/**
333 * Return a texture internalFormat for drawing/copying an image
334 * of the given format and type.
335 */
336static GLenum
337internal_format(struct gl_context *ctx, GLenum format, GLenum type)
338{
339   switch (format) {
340   case GL_DEPTH_COMPONENT:
341      switch (type) {
342      case GL_UNSIGNED_SHORT:
343         return GL_DEPTH_COMPONENT16;
344
345      case GL_UNSIGNED_INT:
346         return GL_DEPTH_COMPONENT32;
347
348      case GL_FLOAT:
349         if (ctx->Extensions.ARB_depth_buffer_float)
350            return GL_DEPTH_COMPONENT32F;
351         else
352            return GL_DEPTH_COMPONENT;
353
354      default:
355         return GL_DEPTH_COMPONENT;
356      }
357
358   case GL_DEPTH_STENCIL:
359      switch (type) {
360      case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
361         return GL_DEPTH32F_STENCIL8;
362
363      case GL_UNSIGNED_INT_24_8:
364      default:
365         return GL_DEPTH24_STENCIL8;
366      }
367
368   case GL_STENCIL_INDEX:
369      return GL_STENCIL_INDEX;
370
371   default:
372      if (_mesa_is_enum_format_integer(format)) {
373         switch (type) {
374         case GL_BYTE:
375            return GL_RGBA8I;
376         case GL_UNSIGNED_BYTE:
377            return GL_RGBA8UI;
378         case GL_SHORT:
379            return GL_RGBA16I;
380         case GL_UNSIGNED_SHORT:
381            return GL_RGBA16UI;
382         case GL_INT:
383            return GL_RGBA32I;
384         case GL_UNSIGNED_INT:
385            return GL_RGBA32UI;
386         default:
387            assert(0 && "Unexpected type in internal_format()");
388            return GL_RGBA_INTEGER;
389         }
390      }
391      else {
392         switch (type) {
393         case GL_UNSIGNED_BYTE:
394         case GL_UNSIGNED_INT_8_8_8_8:
395         case GL_UNSIGNED_INT_8_8_8_8_REV:
396         default:
397            return GL_RGBA8;
398
399         case GL_UNSIGNED_BYTE_3_3_2:
400         case GL_UNSIGNED_BYTE_2_3_3_REV:
401         case GL_UNSIGNED_SHORT_4_4_4_4:
402         case GL_UNSIGNED_SHORT_4_4_4_4_REV:
403            return GL_RGBA4;
404
405         case GL_UNSIGNED_SHORT_5_6_5:
406         case GL_UNSIGNED_SHORT_5_6_5_REV:
407            return GL_RGB565;
408
409         case GL_UNSIGNED_SHORT_5_5_5_1:
410         case GL_UNSIGNED_SHORT_1_5_5_5_REV:
411            return GL_RGB5_A1;
412
413         case GL_UNSIGNED_INT_10_10_10_2:
414         case GL_UNSIGNED_INT_2_10_10_10_REV:
415            return GL_RGB10_A2;
416
417         case GL_UNSIGNED_SHORT:
418         case GL_UNSIGNED_INT:
419            return GL_RGBA16;
420
421         case GL_BYTE:
422            return
423               ctx->Extensions.EXT_texture_snorm ? GL_RGBA8_SNORM : GL_RGBA8;
424
425         case GL_SHORT:
426         case GL_INT:
427            return
428               ctx->Extensions.EXT_texture_snorm ? GL_RGBA16_SNORM : GL_RGBA16;
429
430         case GL_HALF_FLOAT_ARB:
431            return
432               ctx->Extensions.ARB_texture_float ? GL_RGBA16F :
433               ctx->Extensions.EXT_texture_snorm ? GL_RGBA16_SNORM : GL_RGBA16;
434
435         case GL_FLOAT:
436         case GL_DOUBLE:
437            return
438               ctx->Extensions.ARB_texture_float ? GL_RGBA32F :
439               ctx->Extensions.EXT_texture_snorm ? GL_RGBA16_SNORM : GL_RGBA16;
440
441         case GL_UNSIGNED_INT_5_9_9_9_REV:
442            assert(ctx->Extensions.EXT_texture_shared_exponent);
443            return GL_RGB9_E5;
444
445         case GL_UNSIGNED_INT_10F_11F_11F_REV:
446            assert(ctx->Extensions.EXT_packed_float);
447            return GL_R11F_G11F_B10F;
448         }
449      }
450   }
451}
452
453
454/**
455 * Create a temporary texture to hold an image of the given size.
456 * If width, height are not POT and the driver only handles POT textures,
457 * allocate the next larger size of texture that is POT.
458 */
459static struct pipe_resource *
460alloc_texture(struct st_context *st, GLsizei width, GLsizei height,
461              enum pipe_format texFormat)
462{
463   struct pipe_resource *pt;
464
465   pt = st_texture_create(st, st->internal_target, texFormat, 0,
466                          width, height, 1, 1, PIPE_BIND_SAMPLER_VIEW);
467
468   return pt;
469}
470
471
472/**
473 * Make texture containing an image for glDrawPixels image.
474 * If 'pixels' is NULL, leave the texture image data undefined.
475 */
476static struct pipe_resource *
477make_texture(struct st_context *st,
478	     GLsizei width, GLsizei height, GLenum format, GLenum type,
479	     const struct gl_pixelstore_attrib *unpack,
480	     const GLvoid *pixels)
481{
482   struct gl_context *ctx = st->ctx;
483   struct pipe_context *pipe = st->pipe;
484   gl_format mformat;
485   struct pipe_resource *pt;
486   enum pipe_format pipeFormat;
487   GLenum baseInternalFormat, intFormat;
488
489   intFormat = internal_format(ctx, format, type);
490   baseInternalFormat = _mesa_base_tex_format(ctx, intFormat);
491
492   mformat = st_ChooseTextureFormat_renderable(ctx, intFormat,
493                                               format, type, GL_FALSE);
494   assert(mformat);
495
496   pipeFormat = st_mesa_format_to_pipe_format(mformat);
497   assert(pipeFormat);
498
499   pixels = _mesa_map_pbo_source(ctx, unpack, pixels);
500   if (!pixels)
501      return NULL;
502
503   /* alloc temporary texture */
504   pt = alloc_texture(st, width, height, pipeFormat);
505   if (!pt) {
506      _mesa_unmap_pbo_source(ctx, unpack);
507      return NULL;
508   }
509
510   {
511      struct pipe_transfer *transfer;
512      GLboolean success;
513      GLubyte *dest;
514      const GLbitfield imageTransferStateSave = ctx->_ImageTransferState;
515
516      /* we'll do pixel transfer in a fragment shader */
517      ctx->_ImageTransferState = 0x0;
518
519      transfer = pipe_get_transfer(st->pipe, pt, 0, 0,
520                                   PIPE_TRANSFER_WRITE, 0, 0,
521                                   width, height);
522
523      /* map texture transfer */
524      dest = pipe_transfer_map(pipe, transfer);
525
526
527      /* Put image into texture transfer.
528       * Note that the image is actually going to be upside down in
529       * the texture.  We deal with that with texcoords.
530       */
531      success = _mesa_texstore(ctx, 2,           /* dims */
532                               baseInternalFormat, /* baseInternalFormat */
533                               mformat,          /* gl_format */
534                               transfer->stride, /* dstRowStride, bytes */
535                               &dest,            /* destSlices */
536                               width, height, 1, /* size */
537                               format, type,     /* src format/type */
538                               pixels,           /* data source */
539                               unpack);
540
541      /* unmap */
542      pipe_transfer_unmap(pipe, transfer);
543      pipe->transfer_destroy(pipe, transfer);
544
545      assert(success);
546
547      /* restore */
548      ctx->_ImageTransferState = imageTransferStateSave;
549   }
550
551   _mesa_unmap_pbo_source(ctx, unpack);
552
553   return pt;
554}
555
556
557/**
558 * Draw quad with texcoords and optional color.
559 * Coords are gallium window coords with y=0=top.
560 * \param color  may be null
561 * \param invertTex  if true, flip texcoords vertically
562 */
563static void
564draw_quad(struct gl_context *ctx, GLfloat x0, GLfloat y0, GLfloat z,
565          GLfloat x1, GLfloat y1, const GLfloat *color,
566          GLboolean invertTex, GLfloat maxXcoord, GLfloat maxYcoord)
567{
568   struct st_context *st = st_context(ctx);
569   struct pipe_context *pipe = st->pipe;
570   GLfloat (*verts)[3][4]; /* four verts, three attribs, XYZW */
571   struct pipe_resource *buf = NULL;
572   unsigned offset;
573
574   u_upload_alloc(st->uploader, 0, 4 * sizeof(verts[0]), &offset, &buf,
575		  (void**)&verts);
576   if (!buf) {
577      return;
578   }
579
580   /* setup vertex data */
581   {
582      const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
583      const GLfloat fb_width = (GLfloat) fb->Width;
584      const GLfloat fb_height = (GLfloat) fb->Height;
585      const GLfloat clip_x0 = x0 / fb_width * 2.0f - 1.0f;
586      const GLfloat clip_y0 = y0 / fb_height * 2.0f - 1.0f;
587      const GLfloat clip_x1 = x1 / fb_width * 2.0f - 1.0f;
588      const GLfloat clip_y1 = y1 / fb_height * 2.0f - 1.0f;
589      const GLfloat sLeft = 0.0f, sRight = maxXcoord;
590      const GLfloat tTop = invertTex ? maxYcoord : 0.0f;
591      const GLfloat tBot = invertTex ? 0.0f : maxYcoord;
592      GLuint i;
593
594      /* upper-left */
595      verts[0][0][0] = clip_x0;    /* v[0].attr[0].x */
596      verts[0][0][1] = clip_y0;    /* v[0].attr[0].y */
597
598      /* upper-right */
599      verts[1][0][0] = clip_x1;
600      verts[1][0][1] = clip_y0;
601
602      /* lower-right */
603      verts[2][0][0] = clip_x1;
604      verts[2][0][1] = clip_y1;
605
606      /* lower-left */
607      verts[3][0][0] = clip_x0;
608      verts[3][0][1] = clip_y1;
609
610      verts[0][1][0] = sLeft; /* v[0].attr[1].S */
611      verts[0][1][1] = tTop;  /* v[0].attr[1].T */
612      verts[1][1][0] = sRight;
613      verts[1][1][1] = tTop;
614      verts[2][1][0] = sRight;
615      verts[2][1][1] = tBot;
616      verts[3][1][0] = sLeft;
617      verts[3][1][1] = tBot;
618
619      /* same for all verts: */
620      if (color) {
621         for (i = 0; i < 4; i++) {
622            verts[i][0][2] = z;         /* v[i].attr[0].z */
623            verts[i][0][3] = 1.0f;      /* v[i].attr[0].w */
624            verts[i][2][0] = color[0];  /* v[i].attr[2].r */
625            verts[i][2][1] = color[1];  /* v[i].attr[2].g */
626            verts[i][2][2] = color[2];  /* v[i].attr[2].b */
627            verts[i][2][3] = color[3];  /* v[i].attr[2].a */
628            verts[i][1][2] = 0.0f;      /* v[i].attr[1].R */
629            verts[i][1][3] = 1.0f;      /* v[i].attr[1].Q */
630         }
631      }
632      else {
633         for (i = 0; i < 4; i++) {
634            verts[i][0][2] = z;    /*Z*/
635            verts[i][0][3] = 1.0f; /*W*/
636            verts[i][1][2] = 0.0f; /*R*/
637            verts[i][1][3] = 1.0f; /*Q*/
638         }
639      }
640   }
641
642   u_upload_unmap(st->uploader);
643   util_draw_vertex_buffer(pipe, st->cso_context, buf, offset,
644			   PIPE_PRIM_QUADS,
645			   4,  /* verts */
646			   3); /* attribs/vert */
647   pipe_resource_reference(&buf, NULL);
648}
649
650
651
652static void
653draw_textured_quad(struct gl_context *ctx, GLint x, GLint y, GLfloat z,
654                   GLsizei width, GLsizei height,
655                   GLfloat zoomX, GLfloat zoomY,
656                   struct pipe_sampler_view **sv,
657                   int num_sampler_view,
658                   void *driver_vp,
659                   void *driver_fp,
660                   const GLfloat *color,
661                   GLboolean invertTex,
662                   GLboolean write_depth, GLboolean write_stencil)
663{
664   struct st_context *st = st_context(ctx);
665   struct pipe_context *pipe = st->pipe;
666   struct cso_context *cso = st->cso_context;
667   GLfloat x0, y0, x1, y1;
668   GLsizei maxSize;
669   boolean normalized = sv[0]->texture->target != PIPE_TEXTURE_RECT;
670
671   /* limit checks */
672   /* XXX if DrawPixels image is larger than max texture size, break
673    * it up into chunks.
674    */
675   maxSize = 1 << (pipe->screen->get_param(pipe->screen,
676                                        PIPE_CAP_MAX_TEXTURE_2D_LEVELS) - 1);
677   assert(width <= maxSize);
678   assert(height <= maxSize);
679
680   cso_save_rasterizer(cso);
681   cso_save_viewport(cso);
682   cso_save_samplers(cso, PIPE_SHADER_FRAGMENT);
683   cso_save_sampler_views(cso, PIPE_SHADER_FRAGMENT);
684   cso_save_fragment_shader(cso);
685   cso_save_stream_outputs(cso);
686   cso_save_vertex_shader(cso);
687   cso_save_geometry_shader(cso);
688   cso_save_vertex_elements(cso);
689   cso_save_vertex_buffers(cso);
690   if (write_stencil) {
691      cso_save_depth_stencil_alpha(cso);
692      cso_save_blend(cso);
693   }
694
695   /* rasterizer state: just scissor */
696   {
697      struct pipe_rasterizer_state rasterizer;
698      memset(&rasterizer, 0, sizeof(rasterizer));
699      rasterizer.clamp_fragment_color = !st->clamp_frag_color_in_shader &&
700                                        ctx->Color._ClampFragmentColor;
701      rasterizer.gl_rasterization_rules = 1;
702      rasterizer.depth_clip = !ctx->Transform.DepthClamp;
703      rasterizer.scissor = ctx->Scissor.Enabled;
704      cso_set_rasterizer(cso, &rasterizer);
705   }
706
707   if (write_stencil) {
708      /* Stencil writing bypasses the normal fragment pipeline to
709       * disable color writing and set stencil test to always pass.
710       */
711      struct pipe_depth_stencil_alpha_state dsa;
712      struct pipe_blend_state blend;
713
714      /* depth/stencil */
715      memset(&dsa, 0, sizeof(dsa));
716      dsa.stencil[0].enabled = 1;
717      dsa.stencil[0].func = PIPE_FUNC_ALWAYS;
718      dsa.stencil[0].writemask = ctx->Stencil.WriteMask[0] & 0xff;
719      dsa.stencil[0].zpass_op = PIPE_STENCIL_OP_REPLACE;
720      if (write_depth) {
721         /* writing depth+stencil: depth test always passes */
722         dsa.depth.enabled = 1;
723         dsa.depth.writemask = ctx->Depth.Mask;
724         dsa.depth.func = PIPE_FUNC_ALWAYS;
725      }
726      cso_set_depth_stencil_alpha(cso, &dsa);
727
728      /* blend (colormask) */
729      memset(&blend, 0, sizeof(blend));
730      cso_set_blend(cso, &blend);
731   }
732
733   /* fragment shader state: TEX lookup program */
734   cso_set_fragment_shader_handle(cso, driver_fp);
735
736   /* vertex shader state: position + texcoord pass-through */
737   cso_set_vertex_shader_handle(cso, driver_vp);
738
739   /* geometry shader state: disabled */
740   cso_set_geometry_shader_handle(cso, NULL);
741
742   /* texture sampling state: */
743   {
744      struct pipe_sampler_state sampler;
745      memset(&sampler, 0, sizeof(sampler));
746      sampler.wrap_s = PIPE_TEX_WRAP_CLAMP;
747      sampler.wrap_t = PIPE_TEX_WRAP_CLAMP;
748      sampler.wrap_r = PIPE_TEX_WRAP_CLAMP;
749      sampler.min_img_filter = PIPE_TEX_FILTER_NEAREST;
750      sampler.min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
751      sampler.mag_img_filter = PIPE_TEX_FILTER_NEAREST;
752      sampler.normalized_coords = normalized;
753
754      cso_single_sampler(cso, PIPE_SHADER_FRAGMENT, 0, &sampler);
755      if (num_sampler_view > 1) {
756         cso_single_sampler(cso, PIPE_SHADER_FRAGMENT, 1, &sampler);
757      }
758      cso_single_sampler_done(cso, PIPE_SHADER_FRAGMENT);
759   }
760
761   /* viewport state: viewport matching window dims */
762   {
763      const float w = (float) ctx->DrawBuffer->Width;
764      const float h = (float) ctx->DrawBuffer->Height;
765      struct pipe_viewport_state vp;
766      vp.scale[0] =  0.5f * w;
767      vp.scale[1] = -0.5f * h;
768      vp.scale[2] = 0.5f;
769      vp.scale[3] = 1.0f;
770      vp.translate[0] = 0.5f * w;
771      vp.translate[1] = 0.5f * h;
772      vp.translate[2] = 0.5f;
773      vp.translate[3] = 0.0f;
774      cso_set_viewport(cso, &vp);
775   }
776
777   cso_set_vertex_elements(cso, 3, st->velems_util_draw);
778   cso_set_stream_outputs(st->cso_context, 0, NULL, 0);
779
780   /* texture state: */
781   cso_set_sampler_views(cso, PIPE_SHADER_FRAGMENT, num_sampler_view, sv);
782
783   /* Compute Gallium window coords (y=0=top) with pixel zoom.
784    * Recall that these coords are transformed by the current
785    * vertex shader and viewport transformation.
786    */
787   if (st_fb_orientation(ctx->DrawBuffer) == Y_0_BOTTOM) {
788      y = ctx->DrawBuffer->Height - (int) (y + height * ctx->Pixel.ZoomY);
789      invertTex = !invertTex;
790   }
791
792   x0 = (GLfloat) x;
793   x1 = x + width * ctx->Pixel.ZoomX;
794   y0 = (GLfloat) y;
795   y1 = y + height * ctx->Pixel.ZoomY;
796
797   /* convert Z from [0,1] to [-1,-1] to match viewport Z scale/bias */
798   z = z * 2.0 - 1.0;
799
800   draw_quad(ctx, x0, y0, z, x1, y1, color, invertTex,
801             normalized ? ((GLfloat) width / sv[0]->texture->width0) : (GLfloat)width,
802             normalized ? ((GLfloat) height / sv[0]->texture->height0) : (GLfloat)height);
803
804   /* restore state */
805   cso_restore_rasterizer(cso);
806   cso_restore_viewport(cso);
807   cso_restore_samplers(cso, PIPE_SHADER_FRAGMENT);
808   cso_restore_sampler_views(cso, PIPE_SHADER_FRAGMENT);
809   cso_restore_fragment_shader(cso);
810   cso_restore_vertex_shader(cso);
811   cso_restore_geometry_shader(cso);
812   cso_restore_vertex_elements(cso);
813   cso_restore_vertex_buffers(cso);
814   cso_restore_stream_outputs(cso);
815   if (write_stencil) {
816      cso_restore_depth_stencil_alpha(cso);
817      cso_restore_blend(cso);
818   }
819}
820
821
822/**
823 * Software fallback to do glDrawPixels(GL_STENCIL_INDEX) when we
824 * can't use a fragment shader to write stencil values.
825 */
826static void
827draw_stencil_pixels(struct gl_context *ctx, GLint x, GLint y,
828                    GLsizei width, GLsizei height, GLenum format, GLenum type,
829                    const struct gl_pixelstore_attrib *unpack,
830                    const GLvoid *pixels)
831{
832   struct st_context *st = st_context(ctx);
833   struct pipe_context *pipe = st->pipe;
834   struct st_renderbuffer *strb;
835   enum pipe_transfer_usage usage;
836   struct pipe_transfer *pt;
837   const GLboolean zoom = ctx->Pixel.ZoomX != 1.0 || ctx->Pixel.ZoomY != 1.0;
838   ubyte *stmap;
839   struct gl_pixelstore_attrib clippedUnpack = *unpack;
840   GLubyte *sValues;
841   GLuint *zValues;
842
843   if (!zoom) {
844      if (!_mesa_clip_drawpixels(ctx, &x, &y, &width, &height,
845                                 &clippedUnpack)) {
846         /* totally clipped */
847         return;
848      }
849   }
850
851   strb = st_renderbuffer(ctx->DrawBuffer->
852                          Attachment[BUFFER_STENCIL].Renderbuffer);
853
854   if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
855      y = ctx->DrawBuffer->Height - y - height;
856   }
857
858   if (format == GL_STENCIL_INDEX &&
859       _mesa_is_format_packed_depth_stencil(strb->Base.Format)) {
860      /* writing stencil to a combined depth+stencil buffer */
861      usage = PIPE_TRANSFER_READ_WRITE;
862   }
863   else {
864      usage = PIPE_TRANSFER_WRITE;
865   }
866
867   pt = pipe_get_transfer(pipe, strb->texture,
868                          strb->rtt_level, strb->rtt_face + strb->rtt_slice,
869                          usage, x, y,
870                          width, height);
871
872   stmap = pipe_transfer_map(pipe, pt);
873
874   pixels = _mesa_map_pbo_source(ctx, &clippedUnpack, pixels);
875   assert(pixels);
876
877   sValues = (GLubyte *) malloc(width * sizeof(GLubyte));
878   zValues = (GLuint *) malloc(width * sizeof(GLuint));
879
880   if (sValues && zValues) {
881      GLint row;
882      for (row = 0; row < height; row++) {
883         GLfloat *zValuesFloat = (GLfloat*)zValues;
884         GLenum destType = GL_UNSIGNED_BYTE;
885         const GLvoid *source = _mesa_image_address2d(&clippedUnpack, pixels,
886                                                      width, height,
887                                                      format, type,
888                                                      row, 0);
889         _mesa_unpack_stencil_span(ctx, width, destType, sValues,
890                                   type, source, &clippedUnpack,
891                                   ctx->_ImageTransferState);
892
893         if (format == GL_DEPTH_STENCIL) {
894            GLenum ztype =
895               pt->resource->format == PIPE_FORMAT_Z32_FLOAT_S8X24_UINT ?
896               GL_FLOAT : GL_UNSIGNED_INT;
897
898            _mesa_unpack_depth_span(ctx, width, ztype, zValues,
899                                    (1 << 24) - 1, type, source,
900                                    &clippedUnpack);
901         }
902
903         if (zoom) {
904            _mesa_problem(ctx, "Gallium glDrawPixels(GL_STENCIL) with "
905                          "zoom not complete");
906         }
907
908         {
909            GLint spanY;
910
911            if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
912               spanY = height - row - 1;
913            }
914            else {
915               spanY = row;
916            }
917
918            /* now pack the stencil (and Z) values in the dest format */
919            switch (pt->resource->format) {
920            case PIPE_FORMAT_S8_UINT:
921               {
922                  ubyte *dest = stmap + spanY * pt->stride;
923                  assert(usage == PIPE_TRANSFER_WRITE);
924                  memcpy(dest, sValues, width);
925               }
926               break;
927            case PIPE_FORMAT_Z24_UNORM_S8_UINT:
928               if (format == GL_DEPTH_STENCIL) {
929                  uint *dest = (uint *) (stmap + spanY * pt->stride);
930                  GLint k;
931                  assert(usage == PIPE_TRANSFER_WRITE);
932                  for (k = 0; k < width; k++) {
933                     dest[k] = zValues[k] | (sValues[k] << 24);
934                  }
935               }
936               else {
937                  uint *dest = (uint *) (stmap + spanY * pt->stride);
938                  GLint k;
939                  assert(usage == PIPE_TRANSFER_READ_WRITE);
940                  for (k = 0; k < width; k++) {
941                     dest[k] = (dest[k] & 0xffffff) | (sValues[k] << 24);
942                  }
943               }
944               break;
945            case PIPE_FORMAT_S8_UINT_Z24_UNORM:
946               if (format == GL_DEPTH_STENCIL) {
947                  uint *dest = (uint *) (stmap + spanY * pt->stride);
948                  GLint k;
949                  assert(usage == PIPE_TRANSFER_WRITE);
950                  for (k = 0; k < width; k++) {
951                     dest[k] = (zValues[k] << 8) | (sValues[k] & 0xff);
952                  }
953               }
954               else {
955                  uint *dest = (uint *) (stmap + spanY * pt->stride);
956                  GLint k;
957                  assert(usage == PIPE_TRANSFER_READ_WRITE);
958                  for (k = 0; k < width; k++) {
959                     dest[k] = (dest[k] & 0xffffff00) | (sValues[k] & 0xff);
960                  }
961               }
962               break;
963            case PIPE_FORMAT_Z32_FLOAT_S8X24_UINT:
964               if (format == GL_DEPTH_STENCIL) {
965                  uint *dest = (uint *) (stmap + spanY * pt->stride);
966                  GLfloat *destf = (GLfloat*)dest;
967                  GLint k;
968                  assert(usage == PIPE_TRANSFER_WRITE);
969                  for (k = 0; k < width; k++) {
970                     destf[k*2] = zValuesFloat[k];
971                     dest[k*2+1] = sValues[k] & 0xff;
972                  }
973               }
974               else {
975                  uint *dest = (uint *) (stmap + spanY * pt->stride);
976                  GLint k;
977                  assert(usage == PIPE_TRANSFER_READ_WRITE);
978                  for (k = 0; k < width; k++) {
979                     dest[k*2+1] = sValues[k] & 0xff;
980                  }
981               }
982               break;
983            default:
984               assert(0);
985            }
986         }
987      }
988   }
989   else {
990      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDrawPixels()");
991   }
992
993   free(sValues);
994   free(zValues);
995
996   _mesa_unmap_pbo_source(ctx, &clippedUnpack);
997
998   /* unmap the stencil buffer */
999   pipe_transfer_unmap(pipe, pt);
1000   pipe->transfer_destroy(pipe, pt);
1001}
1002
1003
1004/**
1005 * Get fragment program variant for a glDrawPixels or glCopyPixels
1006 * command for RGBA data.
1007 */
1008static struct st_fp_variant *
1009get_color_fp_variant(struct st_context *st)
1010{
1011   struct gl_context *ctx = st->ctx;
1012   struct st_fp_variant_key key;
1013   struct st_fp_variant *fpv;
1014
1015   memset(&key, 0, sizeof(key));
1016
1017   key.st = st;
1018   key.drawpixels = 1;
1019   key.scaleAndBias = (ctx->Pixel.RedBias != 0.0 ||
1020                       ctx->Pixel.RedScale != 1.0 ||
1021                       ctx->Pixel.GreenBias != 0.0 ||
1022                       ctx->Pixel.GreenScale != 1.0 ||
1023                       ctx->Pixel.BlueBias != 0.0 ||
1024                       ctx->Pixel.BlueScale != 1.0 ||
1025                       ctx->Pixel.AlphaBias != 0.0 ||
1026                       ctx->Pixel.AlphaScale != 1.0);
1027   key.pixelMaps = ctx->Pixel.MapColorFlag;
1028   key.clamp_color = st->clamp_frag_color_in_shader &&
1029                     st->ctx->Color._ClampFragmentColor;
1030
1031   fpv = st_get_fp_variant(st, st->fp, &key);
1032
1033   return fpv;
1034}
1035
1036
1037/**
1038 * Get fragment program variant for a glDrawPixels or glCopyPixels
1039 * command for depth/stencil data.
1040 */
1041static struct st_fp_variant *
1042get_depth_stencil_fp_variant(struct st_context *st, GLboolean write_depth,
1043                             GLboolean write_stencil)
1044{
1045   struct st_fp_variant_key key;
1046   struct st_fp_variant *fpv;
1047
1048   memset(&key, 0, sizeof(key));
1049
1050   key.st = st;
1051   key.drawpixels = 1;
1052   key.drawpixels_z = write_depth;
1053   key.drawpixels_stencil = write_stencil;
1054
1055   fpv = st_get_fp_variant(st, st->fp, &key);
1056
1057   return fpv;
1058}
1059
1060
1061/**
1062 * Clamp glDrawPixels width and height to the maximum texture size.
1063 */
1064static void
1065clamp_size(struct pipe_context *pipe, GLsizei *width, GLsizei *height,
1066           struct gl_pixelstore_attrib *unpack)
1067{
1068   const unsigned maxSize =
1069      1 << (pipe->screen->get_param(pipe->screen,
1070                                    PIPE_CAP_MAX_TEXTURE_2D_LEVELS) - 1);
1071
1072   if (*width > maxSize) {
1073      if (unpack->RowLength == 0)
1074         unpack->RowLength = *width;
1075      *width = maxSize;
1076   }
1077   if (*height > maxSize) {
1078      *height = maxSize;
1079   }
1080}
1081
1082
1083/**
1084 * Called via ctx->Driver.DrawPixels()
1085 */
1086static void
1087st_DrawPixels(struct gl_context *ctx, GLint x, GLint y,
1088              GLsizei width, GLsizei height,
1089              GLenum format, GLenum type,
1090              const struct gl_pixelstore_attrib *unpack, const GLvoid *pixels)
1091{
1092   void *driver_vp, *driver_fp;
1093   struct st_context *st = st_context(ctx);
1094   const GLfloat *color;
1095   struct pipe_context *pipe = st->pipe;
1096   GLboolean write_stencil = GL_FALSE, write_depth = GL_FALSE;
1097   struct pipe_sampler_view *sv[2];
1098   int num_sampler_view = 1;
1099   struct st_fp_variant *fpv;
1100   struct gl_pixelstore_attrib clippedUnpack;
1101
1102   /* Mesa state should be up to date by now */
1103   assert(ctx->NewState == 0x0);
1104
1105   st_validate_state(st);
1106
1107   /* Limit the size of the glDrawPixels to the max texture size.
1108    * Strictly speaking, that's not correct but since we don't handle
1109    * larger images yet, this is better than crashing.
1110    */
1111   clippedUnpack = *unpack;
1112   unpack = &clippedUnpack;
1113   clamp_size(st->pipe, &width, &height, &clippedUnpack);
1114
1115   if (format == GL_DEPTH_STENCIL)
1116      write_stencil = write_depth = GL_TRUE;
1117   else if (format == GL_STENCIL_INDEX)
1118      write_stencil = GL_TRUE;
1119   else if (format == GL_DEPTH_COMPONENT)
1120      write_depth = GL_TRUE;
1121
1122   if (write_stencil &&
1123       !pipe->screen->get_param(pipe->screen, PIPE_CAP_SHADER_STENCIL_EXPORT)) {
1124      /* software fallback */
1125      draw_stencil_pixels(ctx, x, y, width, height, format, type,
1126                          unpack, pixels);
1127      return;
1128   }
1129
1130   /*
1131    * Get vertex/fragment shaders
1132    */
1133   if (write_depth || write_stencil) {
1134      fpv = get_depth_stencil_fp_variant(st, write_depth, write_stencil);
1135
1136      driver_fp = fpv->driver_shader;
1137
1138      driver_vp = make_passthrough_vertex_shader(st, GL_TRUE);
1139
1140      color = ctx->Current.RasterColor;
1141   }
1142   else {
1143      fpv = get_color_fp_variant(st);
1144
1145      driver_fp = fpv->driver_shader;
1146
1147      driver_vp = make_passthrough_vertex_shader(st, GL_FALSE);
1148
1149      color = NULL;
1150      if (st->pixel_xfer.pixelmap_enabled) {
1151	  sv[1] = st->pixel_xfer.pixelmap_sampler_view;
1152	  num_sampler_view++;
1153      }
1154   }
1155
1156   /* update fragment program constants */
1157   st_upload_constants(st, fpv->parameters, PIPE_SHADER_FRAGMENT);
1158
1159   /* draw with textured quad */
1160   {
1161      struct pipe_resource *pt
1162         = make_texture(st, width, height, format, type, unpack, pixels);
1163      if (pt) {
1164         sv[0] = st_create_texture_sampler_view(st->pipe, pt);
1165
1166         if (sv[0]) {
1167            /* Create a second sampler view to read stencil.
1168             * The stencil is written using the shader stencil export
1169             * functionality. */
1170            if (write_stencil) {
1171               enum pipe_format stencil_format =
1172                     util_format_stencil_only(pt->format);
1173
1174               sv[1] = st_create_texture_sampler_view_format(st->pipe, pt,
1175                                                             stencil_format);
1176               num_sampler_view++;
1177            }
1178
1179            draw_textured_quad(ctx, x, y, ctx->Current.RasterPos[2],
1180                               width, height,
1181                               ctx->Pixel.ZoomX, ctx->Pixel.ZoomY,
1182                               sv,
1183                               num_sampler_view,
1184                               driver_vp,
1185                               driver_fp,
1186                               color, GL_FALSE, write_depth, write_stencil);
1187            pipe_sampler_view_reference(&sv[0], NULL);
1188            if (num_sampler_view > 1)
1189               pipe_sampler_view_reference(&sv[1], NULL);
1190         }
1191         pipe_resource_reference(&pt, NULL);
1192      }
1193   }
1194}
1195
1196
1197
1198/**
1199 * Software fallback for glCopyPixels(GL_STENCIL).
1200 */
1201static void
1202copy_stencil_pixels(struct gl_context *ctx, GLint srcx, GLint srcy,
1203                    GLsizei width, GLsizei height,
1204                    GLint dstx, GLint dsty)
1205{
1206   struct st_renderbuffer *rbDraw;
1207   struct pipe_context *pipe = st_context(ctx)->pipe;
1208   enum pipe_transfer_usage usage;
1209   struct pipe_transfer *ptDraw;
1210   ubyte *drawMap;
1211   ubyte *buffer;
1212   int i;
1213
1214   buffer = malloc(width * height * sizeof(ubyte));
1215   if (!buffer) {
1216      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCopyPixels(stencil)");
1217      return;
1218   }
1219
1220   /* Get the dest renderbuffer */
1221   rbDraw = st_renderbuffer(ctx->DrawBuffer->
1222                            Attachment[BUFFER_STENCIL].Renderbuffer);
1223
1224   /* this will do stencil pixel transfer ops */
1225   _mesa_readpixels(ctx, srcx, srcy, width, height,
1226                    GL_STENCIL_INDEX, GL_UNSIGNED_BYTE,
1227                    &ctx->DefaultPacking, buffer);
1228
1229   if (0) {
1230      /* debug code: dump stencil values */
1231      GLint row, col;
1232      for (row = 0; row < height; row++) {
1233         printf("%3d: ", row);
1234         for (col = 0; col < width; col++) {
1235            printf("%02x ", buffer[col + row * width]);
1236         }
1237         printf("\n");
1238      }
1239   }
1240
1241   if (_mesa_is_format_packed_depth_stencil(rbDraw->Base.Format))
1242      usage = PIPE_TRANSFER_READ_WRITE;
1243   else
1244      usage = PIPE_TRANSFER_WRITE;
1245
1246   if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
1247      dsty = rbDraw->Base.Height - dsty - height;
1248   }
1249
1250   ptDraw = pipe_get_transfer(pipe,
1251                              rbDraw->texture,
1252                              rbDraw->rtt_level,
1253                              rbDraw->rtt_face + rbDraw->rtt_slice,
1254                              usage, dstx, dsty,
1255                              width, height);
1256
1257   assert(util_format_get_blockwidth(ptDraw->resource->format) == 1);
1258   assert(util_format_get_blockheight(ptDraw->resource->format) == 1);
1259
1260   /* map the stencil buffer */
1261   drawMap = pipe_transfer_map(pipe, ptDraw);
1262
1263   /* draw */
1264   /* XXX PixelZoom not handled yet */
1265   for (i = 0; i < height; i++) {
1266      ubyte *dst;
1267      const ubyte *src;
1268      int y;
1269
1270      y = i;
1271
1272      if (st_fb_orientation(ctx->DrawBuffer) == Y_0_TOP) {
1273         y = height - y - 1;
1274      }
1275
1276      dst = drawMap + y * ptDraw->stride;
1277      src = buffer + i * width;
1278
1279      _mesa_pack_ubyte_stencil_row(rbDraw->Base.Format, width, src, dst);
1280   }
1281
1282   free(buffer);
1283
1284   /* unmap the stencil buffer */
1285   pipe_transfer_unmap(pipe, ptDraw);
1286   pipe->transfer_destroy(pipe, ptDraw);
1287}
1288
1289
1290/**
1291 * Return renderbuffer to use for reading color pixels for glCopyPixels
1292 */
1293static struct st_renderbuffer *
1294st_get_color_read_renderbuffer(struct gl_context *ctx)
1295{
1296   struct gl_framebuffer *fb = ctx->ReadBuffer;
1297   struct st_renderbuffer *strb =
1298      st_renderbuffer(fb->_ColorReadBuffer);
1299
1300   return strb;
1301}
1302
1303
1304/** Do the src/dest regions overlap? */
1305static GLboolean
1306regions_overlap(GLint srcX, GLint srcY, GLint dstX, GLint dstY,
1307                GLsizei width, GLsizei height)
1308{
1309   if (srcX + width <= dstX ||
1310       dstX + width <= srcX ||
1311       srcY + height <= dstY ||
1312       dstY + height <= srcY)
1313      return GL_FALSE;
1314   else
1315      return GL_TRUE;
1316}
1317
1318
1319/**
1320 * Try to do a glCopyPixels for simple cases with a blit by calling
1321 * pipe->resource_copy_region().
1322 *
1323 * We can do this when we're copying color pixels (depth/stencil
1324 * eventually) with no pixel zoom, no pixel transfer ops, no
1325 * per-fragment ops, the src/dest regions don't overlap and the
1326 * src/dest pixel formats are the same.
1327 */
1328static GLboolean
1329blit_copy_pixels(struct gl_context *ctx, GLint srcx, GLint srcy,
1330                 GLsizei width, GLsizei height,
1331                 GLint dstx, GLint dsty, GLenum type)
1332{
1333   struct st_context *st = st_context(ctx);
1334   struct pipe_context *pipe = st->pipe;
1335   struct gl_pixelstore_attrib pack, unpack;
1336   GLint readX, readY, readW, readH;
1337
1338   if (type == GL_COLOR &&
1339       ctx->Pixel.ZoomX == 1.0 &&
1340       ctx->Pixel.ZoomY == 1.0 &&
1341       ctx->_ImageTransferState == 0x0 &&
1342       !ctx->Color.BlendEnabled &&
1343       !ctx->Color.AlphaEnabled &&
1344       !ctx->Depth.Test &&
1345       !ctx->Fog.Enabled &&
1346       !ctx->Stencil.Enabled &&
1347       !ctx->FragmentProgram.Enabled &&
1348       !ctx->VertexProgram.Enabled &&
1349       !ctx->Shader.CurrentFragmentProgram &&
1350       st_fb_orientation(ctx->ReadBuffer) == st_fb_orientation(ctx->DrawBuffer) &&
1351       ctx->DrawBuffer->_NumColorDrawBuffers == 1 &&
1352       !ctx->Query.CondRenderQuery) {
1353      struct st_renderbuffer *rbRead, *rbDraw;
1354      GLint drawX, drawY;
1355
1356      /*
1357       * Clip the read region against the src buffer bounds.
1358       * We'll still allocate a temporary buffer/texture for the original
1359       * src region size but we'll only read the region which is on-screen.
1360       * This may mean that we draw garbage pixels into the dest region, but
1361       * that's expected.
1362       */
1363      readX = srcx;
1364      readY = srcy;
1365      readW = width;
1366      readH = height;
1367      pack = ctx->DefaultPacking;
1368      if (!_mesa_clip_readpixels(ctx, &readX, &readY, &readW, &readH, &pack))
1369         return GL_TRUE; /* all done */
1370
1371      /* clip against dest buffer bounds and scissor box */
1372      drawX = dstx + pack.SkipPixels;
1373      drawY = dsty + pack.SkipRows;
1374      unpack = pack;
1375      if (!_mesa_clip_drawpixels(ctx, &drawX, &drawY, &readW, &readH, &unpack))
1376         return GL_TRUE; /* all done */
1377
1378      readX = readX - pack.SkipPixels + unpack.SkipPixels;
1379      readY = readY - pack.SkipRows + unpack.SkipRows;
1380
1381      rbRead = st_get_color_read_renderbuffer(ctx);
1382      rbDraw = st_renderbuffer(ctx->DrawBuffer->_ColorDrawBuffers[0]);
1383
1384      if ((rbRead != rbDraw ||
1385           !regions_overlap(readX, readY, drawX, drawY, readW, readH)) &&
1386          rbRead->Base.Format == rbDraw->Base.Format) {
1387         struct pipe_box srcBox;
1388
1389         /* flip src/dst position if needed */
1390         if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1391            /* both buffers will have the same orientation */
1392            readY = ctx->ReadBuffer->Height - readY - readH;
1393            drawY = ctx->DrawBuffer->Height - drawY - readH;
1394         }
1395
1396         u_box_2d(readX, readY, readW, readH, &srcBox);
1397
1398         pipe->resource_copy_region(pipe,
1399                                    rbDraw->texture,
1400                                    rbDraw->rtt_level, drawX, drawY, 0,
1401                                    rbRead->texture,
1402                                    rbRead->rtt_level, &srcBox);
1403         return GL_TRUE;
1404      }
1405   }
1406
1407   return GL_FALSE;
1408}
1409
1410
1411static void
1412st_CopyPixels(struct gl_context *ctx, GLint srcx, GLint srcy,
1413              GLsizei width, GLsizei height,
1414              GLint dstx, GLint dsty, GLenum type)
1415{
1416   struct st_context *st = st_context(ctx);
1417   struct pipe_context *pipe = st->pipe;
1418   struct pipe_screen *screen = pipe->screen;
1419   struct st_renderbuffer *rbRead;
1420   void *driver_vp, *driver_fp;
1421   struct pipe_resource *pt;
1422   struct pipe_sampler_view *sv[2];
1423   int num_sampler_view = 1;
1424   GLfloat *color;
1425   enum pipe_format srcFormat, texFormat;
1426   GLboolean invertTex = GL_FALSE;
1427   GLint readX, readY, readW, readH;
1428   GLuint sample_count;
1429   struct gl_pixelstore_attrib pack = ctx->DefaultPacking;
1430   struct st_fp_variant *fpv;
1431
1432   st_validate_state(st);
1433
1434   if (type == GL_DEPTH_STENCIL) {
1435      /* XXX make this more efficient */
1436      st_CopyPixels(ctx, srcx, srcy, width, height, dstx, dsty, GL_STENCIL);
1437      st_CopyPixels(ctx, srcx, srcy, width, height, dstx, dsty, GL_DEPTH);
1438      return;
1439   }
1440
1441   if (type == GL_STENCIL) {
1442      /* can't use texturing to do stencil */
1443      copy_stencil_pixels(ctx, srcx, srcy, width, height, dstx, dsty);
1444      return;
1445   }
1446
1447   if (blit_copy_pixels(ctx, srcx, srcy, width, height, dstx, dsty, type))
1448      return;
1449
1450   /*
1451    * The subsequent code implements glCopyPixels by copying the source
1452    * pixels into a temporary texture that's then applied to a textured quad.
1453    * When we draw the textured quad, all the usual per-fragment operations
1454    * are handled.
1455    */
1456
1457
1458   /*
1459    * Get vertex/fragment shaders
1460    */
1461   if (type == GL_COLOR) {
1462      rbRead = st_get_color_read_renderbuffer(ctx);
1463      color = NULL;
1464
1465      fpv = get_color_fp_variant(st);
1466      driver_fp = fpv->driver_shader;
1467
1468      driver_vp = make_passthrough_vertex_shader(st, GL_FALSE);
1469
1470      if (st->pixel_xfer.pixelmap_enabled) {
1471	  sv[1] = st->pixel_xfer.pixelmap_sampler_view;
1472	  num_sampler_view++;
1473      }
1474   }
1475   else {
1476      assert(type == GL_DEPTH);
1477      rbRead = st_renderbuffer(ctx->ReadBuffer->
1478                               Attachment[BUFFER_DEPTH].Renderbuffer);
1479      color = ctx->Current.Attrib[VERT_ATTRIB_COLOR0];
1480
1481      fpv = get_depth_stencil_fp_variant(st, GL_TRUE, GL_FALSE);
1482      driver_fp = fpv->driver_shader;
1483
1484      driver_vp = make_passthrough_vertex_shader(st, GL_TRUE);
1485   }
1486
1487   /* update fragment program constants */
1488   st_upload_constants(st, fpv->parameters, PIPE_SHADER_FRAGMENT);
1489
1490   sample_count = rbRead->texture->nr_samples;
1491   /* I believe this would be legal, presumably would need to do a resolve
1492      for color, and for depth/stencil spec says to just use one of the
1493      depth/stencil samples per pixel? Need some transfer clarifications. */
1494   assert(sample_count < 2);
1495
1496   srcFormat = rbRead->texture->format;
1497
1498   if (screen->is_format_supported(screen, srcFormat, st->internal_target,
1499                                   sample_count,
1500                                   PIPE_BIND_SAMPLER_VIEW)) {
1501      texFormat = srcFormat;
1502   }
1503   else {
1504      /* srcFormat can't be used as a texture format */
1505      if (type == GL_DEPTH) {
1506         texFormat = st_choose_format(screen, GL_DEPTH_COMPONENT,
1507                                      GL_NONE, GL_NONE, st->internal_target,
1508				      sample_count, PIPE_BIND_DEPTH_STENCIL);
1509         assert(texFormat != PIPE_FORMAT_NONE);
1510      }
1511      else {
1512         /* default color format */
1513         texFormat = st_choose_format(screen, GL_RGBA,
1514                                      GL_NONE, GL_NONE, st->internal_target,
1515                                      sample_count, PIPE_BIND_SAMPLER_VIEW);
1516         assert(texFormat != PIPE_FORMAT_NONE);
1517      }
1518   }
1519
1520   /* Invert src region if needed */
1521   if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1522      srcy = ctx->ReadBuffer->Height - srcy - height;
1523      invertTex = !invertTex;
1524   }
1525
1526   /* Clip the read region against the src buffer bounds.
1527    * We'll still allocate a temporary buffer/texture for the original
1528    * src region size but we'll only read the region which is on-screen.
1529    * This may mean that we draw garbage pixels into the dest region, but
1530    * that's expected.
1531    */
1532   readX = srcx;
1533   readY = srcy;
1534   readW = width;
1535   readH = height;
1536   if (!_mesa_clip_readpixels(ctx, &readX, &readY, &readW, &readH, &pack)) {
1537      /* The source region is completely out of bounds.  Do nothing.
1538       * The GL spec says "Results of copies from outside the window,
1539       * or from regions of the window that are not exposed, are
1540       * hardware dependent and undefined."
1541       */
1542      return;
1543   }
1544
1545   readW = MAX2(0, readW);
1546   readH = MAX2(0, readH);
1547
1548   /* alloc temporary texture */
1549   pt = alloc_texture(st, width, height, texFormat);
1550   if (!pt)
1551      return;
1552
1553   sv[0] = st_create_texture_sampler_view(st->pipe, pt);
1554   if (!sv[0]) {
1555      pipe_resource_reference(&pt, NULL);
1556      return;
1557   }
1558
1559   /* Make temporary texture which is a copy of the src region.
1560    */
1561   if (srcFormat == texFormat) {
1562      struct pipe_box src_box;
1563      u_box_2d(readX, readY, readW, readH, &src_box);
1564      /* copy source framebuffer surface into mipmap/texture */
1565      pipe->resource_copy_region(pipe,
1566                                 pt,                                /* dest tex */
1567                                 0,                                 /* dest lvl */
1568                                 pack.SkipPixels, pack.SkipRows, 0, /* dest pos */
1569                                 rbRead->texture,                   /* src tex */
1570                                 rbRead->rtt_level,                 /* src lvl */
1571                                 &src_box);
1572
1573   }
1574   else {
1575      /* CPU-based fallback/conversion */
1576      struct pipe_transfer *ptRead =
1577         pipe_get_transfer(st->pipe, rbRead->texture,
1578                           rbRead->rtt_level,
1579                           rbRead->rtt_face + rbRead->rtt_slice,
1580                           PIPE_TRANSFER_READ,
1581                           readX, readY, readW, readH);
1582      struct pipe_transfer *ptTex;
1583      enum pipe_transfer_usage transfer_usage;
1584
1585      if (ST_DEBUG & DEBUG_FALLBACK)
1586         debug_printf("%s: fallback processing\n", __FUNCTION__);
1587
1588      if (type == GL_DEPTH && util_format_is_depth_and_stencil(pt->format))
1589         transfer_usage = PIPE_TRANSFER_READ_WRITE;
1590      else
1591         transfer_usage = PIPE_TRANSFER_WRITE;
1592
1593      ptTex = pipe_get_transfer(st->pipe, pt, 0, 0, transfer_usage,
1594                                0, 0, width, height);
1595
1596      /* copy image from ptRead surface to ptTex surface */
1597      if (type == GL_COLOR) {
1598         /* alternate path using get/put_tile() */
1599         GLfloat *buf = (GLfloat *) malloc(width * height * 4 * sizeof(GLfloat));
1600         enum pipe_format readFormat, drawFormat;
1601         readFormat = util_format_linear(rbRead->texture->format);
1602         drawFormat = util_format_linear(pt->format);
1603         pipe_get_tile_rgba_format(pipe, ptRead, 0, 0, readW, readH,
1604                                   readFormat, buf);
1605         pipe_put_tile_rgba_format(pipe, ptTex, pack.SkipPixels, pack.SkipRows,
1606                                   readW, readH, drawFormat, buf);
1607         free(buf);
1608      }
1609      else {
1610         /* GL_DEPTH */
1611         GLuint *buf = (GLuint *) malloc(width * height * sizeof(GLuint));
1612         pipe_get_tile_z(pipe, ptRead, 0, 0, readW, readH, buf);
1613         pipe_put_tile_z(pipe, ptTex, pack.SkipPixels, pack.SkipRows,
1614                         readW, readH, buf);
1615         free(buf);
1616      }
1617
1618      pipe->transfer_destroy(pipe, ptRead);
1619      pipe->transfer_destroy(pipe, ptTex);
1620   }
1621
1622   /* OK, the texture 'pt' contains the src image/pixels.  Now draw a
1623    * textured quad with that texture.
1624    */
1625   draw_textured_quad(ctx, dstx, dsty, ctx->Current.RasterPos[2],
1626                      width, height, ctx->Pixel.ZoomX, ctx->Pixel.ZoomY,
1627                      sv,
1628                      num_sampler_view,
1629                      driver_vp,
1630                      driver_fp,
1631                      color, invertTex, GL_FALSE, GL_FALSE);
1632
1633   pipe_resource_reference(&pt, NULL);
1634   pipe_sampler_view_reference(&sv[0], NULL);
1635}
1636
1637
1638
1639void st_init_drawpixels_functions(struct dd_function_table *functions)
1640{
1641   functions->DrawPixels = st_DrawPixels;
1642   functions->CopyPixels = st_CopyPixels;
1643}
1644
1645
1646void
1647st_destroy_drawpix(struct st_context *st)
1648{
1649   GLuint i;
1650
1651   for (i = 0; i < Elements(st->drawpix.shaders); i++) {
1652      if (st->drawpix.shaders[i])
1653         _mesa_reference_fragprog(st->ctx, &st->drawpix.shaders[i], NULL);
1654   }
1655
1656   st_reference_fragprog(st, &st->pixel_xfer.combined_prog, NULL);
1657   if (st->drawpix.vert_shaders[0])
1658      cso_delete_vertex_shader(st->cso_context, st->drawpix.vert_shaders[0]);
1659   if (st->drawpix.vert_shaders[1])
1660      cso_delete_vertex_shader(st->cso_context, st->drawpix.vert_shaders[1]);
1661}
1662
1663#endif /* FEATURE_drawpix */
1664