st_cb_texture.c revision a7427b0f7b2325b8dcc560d57cb894df25ebef93
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#include "main/mfeatures.h"
29#include "main/bufferobj.h"
30#if FEATURE_convolve
31#include "main/convolve.h"
32#endif
33#include "main/enums.h"
34#include "main/image.h"
35#include "main/imports.h"
36#include "main/macros.h"
37#include "main/mipmap.h"
38#include "main/pixel.h"
39#include "main/texcompress.h"
40#include "main/texformat.h"
41#include "main/texgetimage.h"
42#include "main/teximage.h"
43#include "main/texobj.h"
44#include "main/texstore.h"
45
46#include "state_tracker/st_context.h"
47#include "state_tracker/st_cb_fbo.h"
48#include "state_tracker/st_cb_texture.h"
49#include "state_tracker/st_format.h"
50#include "state_tracker/st_public.h"
51#include "state_tracker/st_texture.h"
52#include "state_tracker/st_gen_mipmap.h"
53#include "state_tracker/st_inlines.h"
54#include "state_tracker/st_atom.h"
55
56#include "pipe/p_context.h"
57#include "pipe/p_defines.h"
58#include "pipe/p_inlines.h"
59#include "util/u_tile.h"
60#include "util/u_blit.h"
61#include "util/u_surface.h"
62
63
64#define DBG if (0) printf
65
66
67static enum pipe_texture_target
68gl_target_to_pipe(GLenum target)
69{
70   switch (target) {
71   case GL_TEXTURE_1D:
72      return PIPE_TEXTURE_1D;
73
74   case GL_TEXTURE_2D:
75   case GL_TEXTURE_RECTANGLE_NV:
76      return PIPE_TEXTURE_2D;
77
78   case GL_TEXTURE_3D:
79      return PIPE_TEXTURE_3D;
80
81   case GL_TEXTURE_CUBE_MAP_ARB:
82      return PIPE_TEXTURE_CUBE;
83
84   default:
85      assert(0);
86      return 0;
87   }
88}
89
90
91/**
92 * Return nominal bytes per texel for a compressed format, 0 for non-compressed
93 * format.
94 */
95static GLuint
96compressed_num_bytes(GLuint mesaFormat)
97{
98   switch(mesaFormat) {
99#if FEATURE_texture_fxt1
100   case MESA_FORMAT_RGB_FXT1:
101   case MESA_FORMAT_RGBA_FXT1:
102#endif
103#if FEATURE_texture_s3tc
104   case MESA_FORMAT_RGB_DXT1:
105   case MESA_FORMAT_RGBA_DXT1:
106      return 2;
107   case MESA_FORMAT_RGBA_DXT3:
108   case MESA_FORMAT_RGBA_DXT5:
109      return 4;
110#endif
111   default:
112      return 0;
113   }
114}
115
116
117static GLboolean
118is_compressed_mesa_format(const struct gl_texture_format *format)
119{
120   switch (format->MesaFormat) {
121   case MESA_FORMAT_RGB_DXT1:
122   case MESA_FORMAT_RGBA_DXT1:
123   case MESA_FORMAT_RGBA_DXT3:
124   case MESA_FORMAT_RGBA_DXT5:
125   case MESA_FORMAT_SRGB_DXT1:
126   case MESA_FORMAT_SRGBA_DXT1:
127   case MESA_FORMAT_SRGBA_DXT3:
128   case MESA_FORMAT_SRGBA_DXT5:
129      return GL_TRUE;
130   default:
131      return GL_FALSE;
132   }
133}
134
135
136/** called via ctx->Driver.NewTextureImage() */
137static struct gl_texture_image *
138st_NewTextureImage(GLcontext * ctx)
139{
140   DBG("%s\n", __FUNCTION__);
141   (void) ctx;
142   return (struct gl_texture_image *) ST_CALLOC_STRUCT(st_texture_image);
143}
144
145
146/** called via ctx->Driver.NewTextureObject() */
147static struct gl_texture_object *
148st_NewTextureObject(GLcontext * ctx, GLuint name, GLenum target)
149{
150   struct st_texture_object *obj = ST_CALLOC_STRUCT(st_texture_object);
151
152   DBG("%s\n", __FUNCTION__);
153   _mesa_initialize_texture_object(&obj->base, name, target);
154
155   return &obj->base;
156}
157
158/** called via ctx->Driver.DeleteTextureImage() */
159static void
160st_DeleteTextureObject(GLcontext *ctx,
161                       struct gl_texture_object *texObj)
162{
163   struct st_texture_object *stObj = st_texture_object(texObj);
164   if (stObj->pt)
165      pipe_texture_reference(&stObj->pt, NULL);
166
167   _mesa_delete_texture_object(ctx, texObj);
168}
169
170
171/** called via ctx->Driver.FreeTexImageData() */
172static void
173st_FreeTextureImageData(GLcontext * ctx, struct gl_texture_image *texImage)
174{
175   struct st_texture_image *stImage = st_texture_image(texImage);
176
177   DBG("%s\n", __FUNCTION__);
178
179   if (stImage->pt) {
180      pipe_texture_reference(&stImage->pt, NULL);
181   }
182
183   if (texImage->Data) {
184      _mesa_align_free(texImage->Data);
185      texImage->Data = NULL;
186   }
187}
188
189
190/**
191 * From linux kernel i386 header files, copes with odd sizes better
192 * than COPY_DWORDS would:
193 * XXX Put this in src/mesa/main/imports.h ???
194 */
195#if defined(PIPE_CC_GCC) && defined(PIPE_ARCH_X86)
196static INLINE void *
197__memcpy(void *to, const void *from, size_t n)
198{
199   int d0, d1, d2;
200   __asm__ __volatile__("rep ; movsl\n\t"
201                        "testb $2,%b4\n\t"
202                        "je 1f\n\t"
203                        "movsw\n"
204                        "1:\ttestb $1,%b4\n\t"
205                        "je 2f\n\t"
206                        "movsb\n" "2:":"=&c"(d0), "=&D"(d1), "=&S"(d2)
207                        :"0"(n / 4), "q"(n), "1"((long) to), "2"((long) from)
208                        :"memory");
209   return (to);
210}
211#else
212#define __memcpy(a,b,c) memcpy(a,b,c)
213#endif
214
215
216/**
217 * The system memcpy (at least on ubuntu 5.10) has problems copying
218 * to agp (writecombined) memory from a source which isn't 64-byte
219 * aligned - there is a 4x performance falloff.
220 *
221 * The x86 __memcpy is immune to this but is slightly slower
222 * (10%-ish) than the system memcpy.
223 *
224 * The sse_memcpy seems to have a slight cliff at 64/32 bytes, but
225 * isn't much faster than x86_memcpy for agp copies.
226 *
227 * TODO: switch dynamically.
228 */
229static void *
230do_memcpy(void *dest, const void *src, size_t n)
231{
232   if ((((unsigned long) src) & 63) || (((unsigned long) dest) & 63)) {
233      return __memcpy(dest, src, n);
234   }
235   else
236      return memcpy(dest, src, n);
237}
238
239
240static INLINE unsigned
241logbase2(unsigned n)
242{
243   unsigned log2 = 0;
244   while (n >>= 1)
245      ++log2;
246   return log2;
247}
248
249
250/**
251 * Return default texture usage bitmask for the given texture format.
252 */
253static GLuint
254default_usage(enum pipe_format fmt)
255{
256   GLuint usage = PIPE_TEXTURE_USAGE_SAMPLER;
257   if (pf_is_depth_stencil(fmt))
258      usage |= PIPE_TEXTURE_USAGE_DEPTH_STENCIL;
259   else
260      usage |= PIPE_TEXTURE_USAGE_RENDER_TARGET;
261   return usage;
262}
263
264
265/**
266 * Allocate a pipe_texture object for the given st_texture_object using
267 * the given st_texture_image to guess the mipmap size/levels.
268 *
269 * [comments...]
270 * Otherwise, store it in memory if (Border != 0) or (any dimension ==
271 * 1).
272 *
273 * Otherwise, if max_level >= level >= min_level, create texture with
274 * space for images from min_level down to max_level.
275 *
276 * Otherwise, create texture with space for images from (level 0)..(1x1).
277 * Consider pruning this texture at a validation if the saving is worth it.
278 */
279static void
280guess_and_alloc_texture(struct st_context *st,
281			struct st_texture_object *stObj,
282			const struct st_texture_image *stImage)
283{
284   GLuint firstLevel;
285   GLuint lastLevel;
286   GLuint width = stImage->base.Width2;  /* size w/out border */
287   GLuint height = stImage->base.Height2;
288   GLuint depth = stImage->base.Depth2;
289   GLuint i, usage;
290   enum pipe_format fmt;
291
292   DBG("%s\n", __FUNCTION__);
293
294   assert(!stObj->pt);
295
296   if (stObj->pt &&
297       (GLint) stImage->level > stObj->base.BaseLevel &&
298       (stImage->base.Width == 1 ||
299        (stObj->base.Target != GL_TEXTURE_1D &&
300         stImage->base.Height == 1) ||
301        (stObj->base.Target == GL_TEXTURE_3D &&
302         stImage->base.Depth == 1)))
303      return;
304
305   /* If this image disrespects BaseLevel, allocate from level zero.
306    * Usually BaseLevel == 0, so it's unlikely to happen.
307    */
308   if ((GLint) stImage->level < stObj->base.BaseLevel)
309      firstLevel = 0;
310   else
311      firstLevel = stObj->base.BaseLevel;
312
313
314   /* Figure out image dimensions at start level.
315    */
316   for (i = stImage->level; i > firstLevel; i--) {
317      if (width != 1)
318         width <<= 1;
319      if (height != 1)
320         height <<= 1;
321      if (depth != 1)
322         depth <<= 1;
323   }
324
325   if (width == 0 || height == 0 || depth == 0) {
326      /* no texture needed */
327      return;
328   }
329
330   /* Guess a reasonable value for lastLevel.  This is probably going
331    * to be wrong fairly often and might mean that we have to look at
332    * resizable buffers, or require that buffers implement lazy
333    * pagetable arrangements.
334    */
335   if ((stObj->base.MinFilter == GL_NEAREST ||
336        stObj->base.MinFilter == GL_LINEAR ||
337        stImage->base._BaseFormat == GL_DEPTH_COMPONENT ||
338        stImage->base._BaseFormat == GL_DEPTH_STENCIL_EXT) &&
339       stImage->level == firstLevel) {
340      lastLevel = firstLevel;
341   }
342   else {
343      GLuint l2width = logbase2(width);
344      GLuint l2height = logbase2(height);
345      GLuint l2depth = logbase2(depth);
346      lastLevel = firstLevel + MAX2(MAX2(l2width, l2height), l2depth);
347   }
348
349   fmt = st_mesa_format_to_pipe_format(stImage->base.TexFormat->MesaFormat);
350
351   usage = default_usage(fmt);
352
353   stObj->pt = st_texture_create(st,
354                                 gl_target_to_pipe(stObj->base.Target),
355                                 fmt,
356                                 lastLevel,
357                                 width,
358                                 height,
359                                 depth,
360                                 usage);
361
362   DBG("%s - success\n", __FUNCTION__);
363}
364
365
366/**
367 * Adjust pixel unpack params and image dimensions to strip off the
368 * texture border.
369 * Gallium doesn't support texture borders.  They've seldem been used
370 * and seldom been implemented correctly anyway.
371 * \param unpackNew  returns the new pixel unpack parameters
372 */
373static void
374strip_texture_border(GLint border,
375                     GLint *width, GLint *height, GLint *depth,
376                     const struct gl_pixelstore_attrib *unpack,
377                     struct gl_pixelstore_attrib *unpackNew)
378{
379   assert(border > 0);  /* sanity check */
380
381   *unpackNew = *unpack;
382
383   if (unpackNew->RowLength == 0)
384      unpackNew->RowLength = *width;
385
386   if (depth && unpackNew->ImageHeight == 0)
387      unpackNew->ImageHeight = *height;
388
389   unpackNew->SkipPixels += border;
390   if (height)
391      unpackNew->SkipRows += border;
392   if (depth)
393      unpackNew->SkipImages += border;
394
395   assert(*width >= 3);
396   *width = *width - 2 * border;
397   if (height && *height >= 3)
398      *height = *height - 2 * border;
399   if (depth && *depth >= 3)
400      *depth = *depth - 2 * border;
401}
402
403
404/**
405 * Try to do texture compression via rendering.  If the Gallium driver
406 * can render into a compressed surface this will allow us to do texture
407 * compression.
408 * \return GL_TRUE for success, GL_FALSE for failure
409 */
410static GLboolean
411compress_with_blit(GLcontext * ctx,
412                   GLenum target, GLint level,
413                   GLint xoffset, GLint yoffset, GLint zoffset,
414                   GLint width, GLint height, GLint depth,
415                   GLenum format, GLenum type, const void *pixels,
416                   const struct gl_pixelstore_attrib *unpack,
417                   struct gl_texture_image *texImage)
418{
419   const GLuint dstImageOffsets[1] = {0};
420   struct st_texture_image *stImage = st_texture_image(texImage);
421   struct pipe_screen *screen = ctx->st->pipe->screen;
422   const struct gl_texture_format *mesa_format;
423   struct pipe_texture templ;
424   struct pipe_texture *src_tex;
425   struct pipe_surface *dst_surface;
426   struct pipe_transfer *tex_xfer;
427   void *map;
428
429
430   if (!stImage->pt) {
431      /* XXX: Can this happen? Should we assert? */
432      return GL_FALSE;
433   }
434
435   /* get destination surface (in the compressed texture) */
436   dst_surface = screen->get_tex_surface(screen, stImage->pt,
437                                         stImage->face, stImage->level, 0,
438                                         PIPE_BUFFER_USAGE_GPU_WRITE);
439   if (!dst_surface) {
440      /* can't render into this format (or other problem) */
441      return GL_FALSE;
442   }
443
444   /* Choose format for the temporary RGBA texture image.
445    */
446   mesa_format = st_ChooseTextureFormat(ctx, GL_RGBA, format, type);
447   assert(mesa_format);
448   if (!mesa_format)
449      return GL_FALSE;
450
451   /* Create the temporary source texture
452    */
453   memset(&templ, 0, sizeof(templ));
454   templ.target = PIPE_TEXTURE_2D;
455   templ.format = st_mesa_format_to_pipe_format(mesa_format->MesaFormat);
456   pf_get_block(templ.format, &templ.block);
457   templ.width[0] = width;
458   templ.height[0] = height;
459   templ.depth[0] = 1;
460   templ.last_level = 0;
461   templ.tex_usage = PIPE_TEXTURE_USAGE_SAMPLER;
462   src_tex = screen->texture_create(screen, &templ);
463
464   if (!src_tex)
465      return GL_FALSE;
466
467   /* Put user's tex data into the temporary texture
468    */
469   tex_xfer = st_cond_flush_get_tex_transfer(st_context(ctx), src_tex,
470					     0, 0, 0, /* face, level are zero */
471					     PIPE_TRANSFER_WRITE,
472					     0, 0, width, height); /* x, y, w, h */
473   map = screen->transfer_map(screen, tex_xfer);
474
475   mesa_format->StoreImage(ctx, 2, GL_RGBA, mesa_format,
476                           map,              /* dest ptr */
477                           0, 0, 0,          /* dest x/y/z offset */
478                           tex_xfer->stride, /* dest row stride (bytes) */
479                           dstImageOffsets,  /* image offsets (for 3D only) */
480                           width, height, 1, /* size */
481                           format, type,     /* source format/type */
482                           pixels,           /* source data */
483                           unpack);          /* source data packing */
484
485   screen->transfer_unmap(screen, tex_xfer);
486   screen->tex_transfer_destroy(tex_xfer);
487
488   /* copy / compress image */
489   util_blit_pixels_tex(ctx->st->blit,
490                        src_tex,          /* pipe_texture (src) */
491                        0, 0,             /* src x0, y0 */
492                        width, height,    /* src x1, y1 */
493                        dst_surface,      /* pipe_surface (dst) */
494                        xoffset, yoffset, /* dst x0, y0 */
495                        xoffset + width,  /* dst x1 */
496                        yoffset + height, /* dst y1 */
497                        0.0,              /* z */
498                        PIPE_TEX_MIPFILTER_NEAREST);
499
500   pipe_surface_reference(&dst_surface, NULL);
501   pipe_texture_reference(&src_tex, NULL);
502
503   return GL_TRUE;
504}
505
506
507/**
508 * Do glTexImage1/2/3D().
509 */
510static void
511st_TexImage(GLcontext * ctx,
512            GLint dims,
513            GLenum target, GLint level,
514            GLint internalFormat,
515            GLint width, GLint height, GLint depth,
516            GLint border,
517            GLenum format, GLenum type, const void *pixels,
518            const struct gl_pixelstore_attrib *unpack,
519            struct gl_texture_object *texObj,
520            struct gl_texture_image *texImage,
521            GLsizei imageSize, GLboolean compressed_src)
522{
523   struct pipe_screen *screen = ctx->st->pipe->screen;
524   struct st_texture_object *stObj = st_texture_object(texObj);
525   struct st_texture_image *stImage = st_texture_image(texImage);
526   GLint postConvWidth, postConvHeight;
527   GLint texelBytes, sizeInBytes;
528   GLuint dstRowStride;
529   struct gl_pixelstore_attrib unpackNB;
530   enum pipe_transfer_usage transfer_usage;
531
532   DBG("%s target %s level %d %dx%dx%d border %d\n", __FUNCTION__,
533       _mesa_lookup_enum_by_nr(target), level, width, height, depth, border);
534
535   /* gallium does not support texture borders, strip it off */
536   if (border) {
537      strip_texture_border(border, &width, &height, &depth, unpack, &unpackNB);
538      unpack = &unpackNB;
539      texImage->Width = width;
540      texImage->Height = height;
541      texImage->Depth = depth;
542      texImage->Border = 0;
543      border = 0;
544   }
545
546   postConvWidth = width;
547   postConvHeight = height;
548
549   stImage->face = _mesa_tex_target_to_face(target);
550   stImage->level = level;
551
552#if FEATURE_convolve
553   if (ctx->_ImageTransferState & IMAGE_CONVOLUTION_BIT) {
554      _mesa_adjust_image_for_convolution(ctx, dims, &postConvWidth,
555                                         &postConvHeight);
556   }
557#endif
558
559   /* choose the texture format */
560   texImage->TexFormat = st_ChooseTextureFormat(ctx, internalFormat,
561                                                format, type);
562
563   _mesa_set_fetch_functions(texImage, dims);
564
565   if (texImage->TexFormat->TexelBytes == 0) {
566      /* must be a compressed format */
567      texelBytes = 0;
568      texImage->IsCompressed = GL_TRUE;
569      texImage->CompressedSize =
570	 ctx->Driver.CompressedTextureSize(ctx, texImage->Width,
571					   texImage->Height, texImage->Depth,
572					   texImage->TexFormat->MesaFormat);
573   }
574   else {
575      texelBytes = texImage->TexFormat->TexelBytes;
576
577      /* Minimum pitch of 32 bytes */
578      if (postConvWidth * texelBytes < 32) {
579	 postConvWidth = 32 / texelBytes;
580	 texImage->RowStride = postConvWidth;
581      }
582
583      /* we'll set RowStride elsewhere when the texture is a "mapped" state */
584      /*assert(texImage->RowStride == postConvWidth);*/
585   }
586
587   /* Release the reference to a potentially orphaned buffer.
588    * Release any old malloced memory.
589    */
590   if (stImage->pt) {
591      pipe_texture_reference(&stImage->pt, NULL);
592      assert(!texImage->Data);
593   }
594   else if (texImage->Data) {
595      _mesa_align_free(texImage->Data);
596   }
597
598   if (width == 0 || height == 0 || depth == 0) {
599      /* stop after freeing old image */
600      return;
601   }
602
603   /* If this is the only mipmap level in the texture, could call
604    * bmBufferData with NULL data to free the old block and avoid
605    * waiting on any outstanding fences.
606    */
607   if (stObj->pt) {
608      if (stObj->teximage_realloc ||
609          level > (GLint) stObj->pt->last_level ||
610          (stObj->pt->last_level == level &&
611           stObj->pt->target != PIPE_TEXTURE_CUBE &&
612           !st_texture_match_image(stObj->pt, &stImage->base,
613                                   stImage->face, stImage->level))) {
614         DBG("release it\n");
615         pipe_texture_reference(&stObj->pt, NULL);
616         assert(!stObj->pt);
617         stObj->teximage_realloc = FALSE;
618      }
619   }
620
621   if (!stObj->pt) {
622      guess_and_alloc_texture(ctx->st, stObj, stImage);
623      if (!stObj->pt) {
624         /* Probably out of memory.
625          * Try flushing any pending rendering, then retry.
626          */
627         st_finish(ctx->st);
628         guess_and_alloc_texture(ctx->st, stObj, stImage);
629         if (!stObj->pt) {
630            _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
631            return;
632         }
633      }
634   }
635
636   assert(!stImage->pt);
637
638   if (stObj->pt &&
639       st_texture_match_image(stObj->pt, &stImage->base,
640                                 stImage->face, stImage->level)) {
641
642      pipe_texture_reference(&stImage->pt, stObj->pt);
643      assert(stImage->pt);
644   }
645
646   if (!stImage->pt)
647      DBG("XXX: Image did not fit into texture - storing in local memory!\n");
648
649   /* st_CopyTexImage calls this function with pixels == NULL, with
650    * the expectation that the texture will be set up but nothing
651    * more will be done.  This is where those calls return:
652    */
653   if (compressed_src) {
654      pixels = _mesa_validate_pbo_compressed_teximage(ctx, imageSize, pixels,
655						      unpack,
656						      "glCompressedTexImage");
657   }
658   else {
659      pixels = _mesa_validate_pbo_teximage(ctx, dims, width, height, 1,
660					   format, type,
661					   pixels, unpack, "glTexImage");
662   }
663   if (!pixels)
664      return;
665
666   /* See if we can do texture compression with a blit/render.
667    */
668   if (!compressed_src &&
669       !ctx->Mesa_DXTn &&
670       is_compressed_mesa_format(texImage->TexFormat) &&
671       screen->is_format_supported(screen,
672                                   stImage->pt->format,
673                                   stImage->pt->target,
674                                   PIPE_TEXTURE_USAGE_RENDER_TARGET, 0)) {
675      if (compress_with_blit(ctx, target, level, 0, 0, 0, width, height, depth,
676                             format, type, pixels, unpack, texImage)) {
677         goto done;
678      }
679   }
680
681   if (stImage->pt) {
682      if (format == GL_DEPTH_COMPONENT &&
683          pf_is_depth_and_stencil(stImage->pt->format))
684         transfer_usage = PIPE_TRANSFER_READ_WRITE;
685      else
686         transfer_usage = PIPE_TRANSFER_WRITE;
687
688      texImage->Data = st_texture_image_map(ctx->st, stImage, 0,
689                                            transfer_usage, 0, 0,
690                                            stImage->base.Width,
691                                            stImage->base.Height);
692      if(stImage->transfer)
693         dstRowStride = stImage->transfer->stride;
694   }
695   else {
696      /* Allocate regular memory and store the image there temporarily.   */
697      if (texImage->IsCompressed) {
698         sizeInBytes = texImage->CompressedSize;
699         dstRowStride =
700            _mesa_compressed_row_stride(texImage->TexFormat->MesaFormat, width);
701         assert(dims != 3);
702      }
703      else {
704         dstRowStride = postConvWidth * texelBytes;
705         sizeInBytes = depth * dstRowStride * postConvHeight;
706      }
707
708      texImage->Data = _mesa_align_malloc(sizeInBytes, 16);
709   }
710
711   if (!texImage->Data) {
712      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
713      return;
714   }
715
716   DBG("Upload image %dx%dx%d row_len %x pitch %x\n",
717       width, height, depth, width * texelBytes, dstRowStride);
718
719   /* Copy data.  Would like to know when it's ok for us to eg. use
720    * the blitter to copy.  Or, use the hardware to do the format
721    * conversion and copy:
722    */
723   if (compressed_src) {
724      memcpy(texImage->Data, pixels, imageSize);
725   }
726   else {
727      const GLuint srcImageStride =
728         _mesa_image_image_stride(unpack, width, height, format, type);
729      GLint i;
730      const GLubyte *src = (const GLubyte *) pixels;
731
732      for (i = 0; i < depth; i++) {
733	 if (!texImage->TexFormat->StoreImage(ctx, dims,
734					      texImage->_BaseFormat,
735					      texImage->TexFormat,
736					      texImage->Data,
737					      0, 0, 0, /* dstX/Y/Zoffset */
738					      dstRowStride,
739					      texImage->ImageOffsets,
740					      width, height, 1,
741					      format, type, src, unpack)) {
742	    _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
743	 }
744
745	 if (stImage->pt && i + 1 < depth) {
746            /* unmap this slice */
747	    st_texture_image_unmap(ctx->st, stImage);
748            /* map next slice of 3D texture */
749	    texImage->Data = st_texture_image_map(ctx->st, stImage, i + 1,
750                                                  transfer_usage, 0, 0,
751                                                  stImage->base.Width,
752                                                  stImage->base.Height);
753	    src += srcImageStride;
754	 }
755      }
756   }
757
758   _mesa_unmap_teximage_pbo(ctx, unpack);
759
760done:
761   if (stImage->pt && texImage->Data) {
762      st_texture_image_unmap(ctx->st, stImage);
763      texImage->Data = NULL;
764   }
765
766   if (level == texObj->BaseLevel && texObj->GenerateMipmap) {
767      ctx->Driver.GenerateMipmap(ctx, target, texObj);
768   }
769}
770
771
772static void
773st_TexImage3D(GLcontext * ctx,
774              GLenum target, GLint level,
775              GLint internalFormat,
776              GLint width, GLint height, GLint depth,
777              GLint border,
778              GLenum format, GLenum type, const void *pixels,
779              const struct gl_pixelstore_attrib *unpack,
780              struct gl_texture_object *texObj,
781              struct gl_texture_image *texImage)
782{
783   st_TexImage(ctx, 3, target, level, internalFormat, width, height, depth,
784               border, format, type, pixels, unpack, texObj, texImage,
785               0, GL_FALSE);
786}
787
788
789static void
790st_TexImage2D(GLcontext * ctx,
791              GLenum target, GLint level,
792              GLint internalFormat,
793              GLint width, GLint height, GLint border,
794              GLenum format, GLenum type, const void *pixels,
795              const struct gl_pixelstore_attrib *unpack,
796              struct gl_texture_object *texObj,
797              struct gl_texture_image *texImage)
798{
799   st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
800               format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
801}
802
803
804static void
805st_TexImage1D(GLcontext * ctx,
806              GLenum target, GLint level,
807              GLint internalFormat,
808              GLint width, GLint border,
809              GLenum format, GLenum type, const void *pixels,
810              const struct gl_pixelstore_attrib *unpack,
811              struct gl_texture_object *texObj,
812              struct gl_texture_image *texImage)
813{
814   st_TexImage(ctx, 1, target, level, internalFormat, width, 1, 1, border,
815               format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
816}
817
818
819static void
820st_CompressedTexImage2D(GLcontext *ctx, GLenum target, GLint level,
821                        GLint internalFormat,
822                        GLint width, GLint height, GLint border,
823                        GLsizei imageSize, const GLvoid *data,
824                        struct gl_texture_object *texObj,
825                        struct gl_texture_image *texImage)
826{
827   st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
828               0, 0, data, &ctx->Unpack, texObj, texImage, imageSize, GL_TRUE);
829}
830
831
832
833/**
834 * glGetTexImage() helper: decompress a compressed texture by rendering
835 * a textured quad.  Store the results in the user's buffer.
836 */
837static void
838decompress_with_blit(GLcontext * ctx, GLenum target, GLint level,
839                     GLenum format, GLenum type, GLvoid *pixels,
840                     struct gl_texture_object *texObj,
841                     struct gl_texture_image *texImage)
842{
843   struct pipe_screen *screen = ctx->st->pipe->screen;
844   struct st_texture_image *stImage = st_texture_image(texImage);
845   const GLuint width = texImage->Width;
846   const GLuint height = texImage->Height;
847   struct pipe_surface *dst_surface;
848   struct pipe_texture *dst_texture;
849   struct pipe_transfer *tex_xfer;
850
851   /* create temp / dest surface */
852   if (!util_create_rgba_surface(screen, width, height,
853                                 &dst_texture, &dst_surface)) {
854      _mesa_problem(ctx, "util_create_rgba_surface() failed "
855                    "in decompress_with_blit()");
856      return;
857   }
858
859   /* blit/render/decompress */
860   util_blit_pixels_tex(ctx->st->blit,
861                        stImage->pt,      /* pipe_texture (src) */
862                        0, 0,             /* src x0, y0 */
863                        width, height,    /* src x1, y1 */
864                        dst_surface,      /* pipe_surface (dst) */
865                        0, 0,             /* dst x0, y0 */
866                        width, height,    /* dst x1, y1 */
867                        0.0,              /* z */
868                        PIPE_TEX_MIPFILTER_NEAREST);
869
870   /* map the dst_surface so we can read from it */
871   tex_xfer = st_cond_flush_get_tex_transfer(st_context(ctx),
872					     dst_texture, 0, 0, 0,
873					     PIPE_TRANSFER_READ,
874					     0, 0, width, height);
875
876   pixels = _mesa_map_readpix_pbo(ctx, &ctx->Pack, pixels);
877
878   /* copy/pack data into user buffer */
879   if (st_equal_formats(stImage->pt->format, format, type)) {
880      /* memcpy */
881      const uint bytesPerRow = width * pf_get_size(stImage->pt->format);
882      ubyte *map = screen->transfer_map(screen, tex_xfer);
883      GLuint row;
884      for (row = 0; row < height; row++) {
885         GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
886                                              height, format, type, row, 0);
887         memcpy(dest, map, bytesPerRow);
888         map += tex_xfer->stride;
889      }
890      screen->transfer_unmap(screen, tex_xfer);
891   }
892   else {
893      /* format translation via floats */
894      GLuint row;
895      for (row = 0; row < height; row++) {
896         const GLbitfield transferOps = 0x0; /* bypassed for glGetTexImage() */
897         GLfloat rgba[4 * MAX_WIDTH];
898         GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
899                                              height, format, type, row, 0);
900
901         /* get float[4] rgba row from surface */
902         pipe_get_tile_rgba(tex_xfer, 0, row, width, 1, rgba);
903
904         _mesa_pack_rgba_span_float(ctx, width, (GLfloat (*)[4]) rgba, format,
905                                    type, dest, &ctx->Pack, transferOps);
906      }
907   }
908
909   _mesa_unmap_readpix_pbo(ctx, &ctx->Pack);
910
911   /* destroy the temp / dest surface */
912   util_destroy_rgba_surface(dst_texture, dst_surface);
913}
914
915
916
917/**
918 * Need to map texture image into memory before copying image data,
919 * then unmap it.
920 */
921static void
922st_get_tex_image(GLcontext * ctx, GLenum target, GLint level,
923                 GLenum format, GLenum type, GLvoid * pixels,
924                 struct gl_texture_object *texObj,
925                 struct gl_texture_image *texImage, GLboolean compressed_dst)
926{
927   struct st_texture_image *stImage = st_texture_image(texImage);
928   const GLuint dstImageStride =
929      _mesa_image_image_stride(&ctx->Pack, texImage->Width, texImage->Height,
930                               format, type);
931   GLuint depth, i;
932   GLubyte *dest;
933
934   if (stImage->pt &&
935       pf_is_compressed(stImage->pt->format) &&
936       !compressed_dst) {
937      /* Need to decompress the texture.
938       * We'll do this by rendering a textured quad.
939       * Note that we only expect RGBA formats (no Z/depth formats).
940       */
941      decompress_with_blit(ctx, target, level, format, type, pixels,
942                           texObj, texImage);
943      return;
944   }
945
946   /* Map */
947   if (stImage->pt) {
948      /* Image is stored in hardware format in a buffer managed by the
949       * kernel.  Need to explicitly map and unmap it.
950       */
951      unsigned face = _mesa_tex_target_to_face(target);
952
953      st_teximage_flush_before_map(ctx->st, stImage->pt, face, level,
954				   PIPE_TRANSFER_READ);
955
956      texImage->Data = st_texture_image_map(ctx->st, stImage, 0,
957                                            PIPE_TRANSFER_READ, 0, 0,
958                                            stImage->base.Width,
959                                            stImage->base.Height);
960      texImage->RowStride = stImage->transfer->stride / stImage->pt->block.size;
961   }
962   else {
963      /* Otherwise, the image should actually be stored in
964       * texImage->Data.  This is pretty confusing for
965       * everybody, I'd much prefer to separate the two functions of
966       * texImage->Data - storage for texture images in main memory
967       * and access (ie mappings) of images.  In other words, we'd
968       * create a new texImage->Map field and leave Data simply for
969       * storage.
970       */
971      assert(texImage->Data);
972   }
973
974   depth = texImage->Depth;
975   texImage->Depth = 1;
976
977   dest = (GLubyte *) pixels;
978
979   for (i = 0; i < depth; i++) {
980      if (compressed_dst) {
981	 _mesa_get_compressed_teximage(ctx, target, level, dest,
982				       texObj, texImage);
983      }
984      else {
985	 _mesa_get_teximage(ctx, target, level, format, type, dest,
986			    texObj, texImage);
987      }
988
989      if (stImage->pt && i + 1 < depth) {
990         /* unmap this slice */
991	 st_texture_image_unmap(ctx->st, stImage);
992         /* map next slice of 3D texture */
993	 texImage->Data = st_texture_image_map(ctx->st, stImage, i + 1,
994                                               PIPE_TRANSFER_READ, 0, 0,
995                                               stImage->base.Width,
996                                               stImage->base.Height);
997	 dest += dstImageStride;
998      }
999   }
1000
1001   texImage->Depth = depth;
1002
1003   /* Unmap */
1004   if (stImage->pt) {
1005      st_texture_image_unmap(ctx->st, stImage);
1006      texImage->Data = NULL;
1007   }
1008}
1009
1010
1011static void
1012st_GetTexImage(GLcontext * ctx, GLenum target, GLint level,
1013               GLenum format, GLenum type, GLvoid * pixels,
1014               struct gl_texture_object *texObj,
1015               struct gl_texture_image *texImage)
1016{
1017   st_get_tex_image(ctx, target, level, format, type, pixels, texObj, texImage,
1018                    GL_FALSE);
1019}
1020
1021
1022static void
1023st_GetCompressedTexImage(GLcontext *ctx, GLenum target, GLint level,
1024                         GLvoid *pixels,
1025                         struct gl_texture_object *texObj,
1026                         struct gl_texture_image *texImage)
1027{
1028   st_get_tex_image(ctx, target, level, 0, 0, pixels, texObj, texImage,
1029                    GL_TRUE);
1030}
1031
1032
1033
1034static void
1035st_TexSubimage(GLcontext *ctx, GLint dims, GLenum target, GLint level,
1036               GLint xoffset, GLint yoffset, GLint zoffset,
1037               GLint width, GLint height, GLint depth,
1038               GLenum format, GLenum type, const void *pixels,
1039               const struct gl_pixelstore_attrib *packing,
1040               struct gl_texture_object *texObj,
1041               struct gl_texture_image *texImage)
1042{
1043   struct pipe_screen *screen = ctx->st->pipe->screen;
1044   struct st_texture_image *stImage = st_texture_image(texImage);
1045   GLuint dstRowStride;
1046   const GLuint srcImageStride =
1047      _mesa_image_image_stride(packing, width, height, format, type);
1048   GLint i;
1049   const GLubyte *src;
1050   /* init to silence warning only: */
1051   enum pipe_transfer_usage transfer_usage = PIPE_TRANSFER_WRITE;
1052
1053   DBG("%s target %s level %d offset %d,%d %dx%d\n", __FUNCTION__,
1054       _mesa_lookup_enum_by_nr(target),
1055       level, xoffset, yoffset, width, height);
1056
1057   pixels =
1058      _mesa_validate_pbo_teximage(ctx, dims, width, height, depth, format,
1059                                  type, pixels, packing, "glTexSubImage2D");
1060   if (!pixels)
1061      return;
1062
1063   /* See if we can do texture compression with a blit/render.
1064    */
1065   if (!ctx->Mesa_DXTn &&
1066       is_compressed_mesa_format(texImage->TexFormat) &&
1067       screen->is_format_supported(screen,
1068                                   stImage->pt->format,
1069                                   stImage->pt->target,
1070                                   PIPE_TEXTURE_USAGE_RENDER_TARGET, 0)) {
1071      if (compress_with_blit(ctx, target, level,
1072                             xoffset, yoffset, zoffset,
1073                             width, height, depth,
1074                             format, type, pixels, packing, texImage)) {
1075         goto done;
1076      }
1077   }
1078
1079   /* Map buffer if necessary.  Need to lock to prevent other contexts
1080    * from uploading the buffer under us.
1081    */
1082   if (stImage->pt) {
1083      unsigned face = _mesa_tex_target_to_face(target);
1084
1085      if (format == GL_DEPTH_COMPONENT &&
1086          pf_is_depth_and_stencil(stImage->pt->format))
1087         transfer_usage = PIPE_TRANSFER_READ_WRITE;
1088      else
1089         transfer_usage = PIPE_TRANSFER_WRITE;
1090
1091      st_teximage_flush_before_map(ctx->st, stImage->pt, face, level,
1092				   transfer_usage);
1093      texImage->Data = st_texture_image_map(ctx->st, stImage, zoffset,
1094                                            transfer_usage,
1095                                            xoffset, yoffset,
1096                                            width, height);
1097   }
1098
1099   if (!texImage->Data) {
1100      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
1101      return;
1102   }
1103
1104   src = (const GLubyte *) pixels;
1105   dstRowStride = stImage->transfer->stride;
1106
1107   for (i = 0; i < depth; i++) {
1108      if (!texImage->TexFormat->StoreImage(ctx, dims, texImage->_BaseFormat,
1109					   texImage->TexFormat,
1110					   texImage->Data,
1111					   0, 0, 0,
1112					   dstRowStride,
1113					   texImage->ImageOffsets,
1114					   width, height, 1,
1115					   format, type, src, packing)) {
1116	 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
1117      }
1118
1119      if (stImage->pt && i + 1 < depth) {
1120         /* unmap this slice */
1121	 st_texture_image_unmap(ctx->st, stImage);
1122         /* map next slice of 3D texture */
1123	 texImage->Data = st_texture_image_map(ctx->st, stImage,
1124                                               zoffset + i + 1,
1125                                               transfer_usage,
1126                                               xoffset, yoffset,
1127                                               width, height);
1128	 src += srcImageStride;
1129      }
1130   }
1131
1132   _mesa_unmap_teximage_pbo(ctx, packing);
1133
1134done:
1135   if (stImage->pt) {
1136      st_texture_image_unmap(ctx->st, stImage);
1137      texImage->Data = NULL;
1138   }
1139
1140   if (level == texObj->BaseLevel && texObj->GenerateMipmap) {
1141      ctx->Driver.GenerateMipmap(ctx, target, texObj);
1142   }
1143}
1144
1145
1146
1147static void
1148st_TexSubImage3D(GLcontext *ctx, GLenum target, GLint level,
1149                 GLint xoffset, GLint yoffset, GLint zoffset,
1150                 GLsizei width, GLsizei height, GLsizei depth,
1151                 GLenum format, GLenum type, const GLvoid *pixels,
1152                 const struct gl_pixelstore_attrib *packing,
1153                 struct gl_texture_object *texObj,
1154                 struct gl_texture_image *texImage)
1155{
1156   st_TexSubimage(ctx, 3, target, level, xoffset, yoffset, zoffset,
1157                  width, height, depth, format, type,
1158                  pixels, packing, texObj, texImage);
1159}
1160
1161
1162static void
1163st_TexSubImage2D(GLcontext *ctx, GLenum target, GLint level,
1164                 GLint xoffset, GLint yoffset,
1165                 GLsizei width, GLsizei height,
1166                 GLenum format, GLenum type, const GLvoid * pixels,
1167                 const struct gl_pixelstore_attrib *packing,
1168                 struct gl_texture_object *texObj,
1169                 struct gl_texture_image *texImage)
1170{
1171   st_TexSubimage(ctx, 2, target, level, xoffset, yoffset, 0,
1172                  width, height, 1, format, type,
1173                  pixels, packing, texObj, texImage);
1174}
1175
1176
1177static void
1178st_TexSubImage1D(GLcontext *ctx, GLenum target, GLint level,
1179                 GLint xoffset, GLsizei width, GLenum format, GLenum type,
1180                 const GLvoid * pixels,
1181                 const struct gl_pixelstore_attrib *packing,
1182                 struct gl_texture_object *texObj,
1183                 struct gl_texture_image *texImage)
1184{
1185   st_TexSubimage(ctx, 1, target, level, xoffset, 0, 0, width, 1, 1,
1186                  format, type, pixels, packing, texObj, texImage);
1187}
1188
1189
1190static void
1191st_CompressedTexSubImage1D(GLcontext *ctx, GLenum target, GLint level,
1192                           GLint xoffset, GLsizei width,
1193                           GLenum format,
1194                           GLsizei imageSize, const GLvoid *data,
1195                           struct gl_texture_object *texObj,
1196                           struct gl_texture_image *texImage)
1197{
1198   assert(0);
1199}
1200
1201
1202static void
1203st_CompressedTexSubImage2D(GLcontext *ctx, GLenum target, GLint level,
1204                           GLint xoffset, GLint yoffset,
1205                           GLsizei width, GLint height,
1206                           GLenum format,
1207                           GLsizei imageSize, const GLvoid *data,
1208                           struct gl_texture_object *texObj,
1209                           struct gl_texture_image *texImage)
1210{
1211   struct st_texture_image *stImage = st_texture_image(texImage);
1212   struct pipe_format_block block;
1213   int srcBlockStride;
1214   int dstBlockStride;
1215   int y;
1216
1217   if (stImage->pt) {
1218      unsigned face = _mesa_tex_target_to_face(target);
1219
1220      st_teximage_flush_before_map(ctx->st, stImage->pt, face, level,
1221				   PIPE_TRANSFER_WRITE);
1222      texImage->Data = st_texture_image_map(ctx->st, stImage, 0,
1223                                            PIPE_TRANSFER_WRITE,
1224                                            xoffset, yoffset,
1225                                            width, height);
1226
1227      block = stImage->pt->block;
1228      srcBlockStride = pf_get_stride(&block, width);
1229      dstBlockStride = stImage->transfer->stride;
1230   } else {
1231      assert(stImage->pt);
1232      /* TODO find good values for block and strides */
1233      /* TODO also adjust texImage->data for yoffset/xoffset */
1234      return;
1235   }
1236
1237   if (!texImage->Data) {
1238      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage");
1239      return;
1240   }
1241
1242   assert(xoffset % block.width == 0);
1243   assert(yoffset % block.height == 0);
1244   assert(width % block.width == 0);
1245   assert(height % block.height == 0);
1246
1247   for (y = 0; y < height; y += block.height) {
1248      /* don't need to adjust for xoffset and yoffset as st_texture_image_map does that */
1249      const char *src = (const char*)data + srcBlockStride * pf_get_nblocksy(&block, y);
1250      char *dst = (char*)texImage->Data + dstBlockStride * pf_get_nblocksy(&block, y);
1251      memcpy(dst, src, pf_get_stride(&block, width));
1252   }
1253
1254   if (stImage->pt) {
1255      st_texture_image_unmap(ctx->st, stImage);
1256      texImage->Data = NULL;
1257   }
1258}
1259
1260
1261static void
1262st_CompressedTexSubImage3D(GLcontext *ctx, GLenum target, GLint level,
1263                           GLint xoffset, GLint yoffset, GLint zoffset,
1264                           GLsizei width, GLint height, GLint depth,
1265                           GLenum format,
1266                           GLsizei imageSize, const GLvoid *data,
1267                           struct gl_texture_object *texObj,
1268                           struct gl_texture_image *texImage)
1269{
1270   assert(0);
1271}
1272
1273
1274
1275/**
1276 * Do a CopyTexSubImage operation using a read transfer from the source,
1277 * a write transfer to the destination and get_tile()/put_tile() to access
1278 * the pixels/texels.
1279 *
1280 * Note: srcY=0=TOP of renderbuffer
1281 */
1282static void
1283fallback_copy_texsubimage(GLcontext *ctx, GLenum target, GLint level,
1284                          struct st_renderbuffer *strb,
1285                          struct st_texture_image *stImage,
1286                          GLenum baseFormat,
1287                          GLint destX, GLint destY, GLint destZ,
1288                          GLint srcX, GLint srcY,
1289                          GLsizei width, GLsizei height)
1290{
1291   struct pipe_context *pipe = ctx->st->pipe;
1292   struct pipe_screen *screen = pipe->screen;
1293   struct pipe_transfer *src_trans;
1294   GLvoid *texDest;
1295   enum pipe_transfer_usage transfer_usage;
1296
1297   assert(width <= MAX_WIDTH);
1298
1299   if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1300      srcY = strb->Base.Height - srcY - height;
1301   }
1302
1303   src_trans = st_cond_flush_get_tex_transfer( st_context(ctx),
1304					       strb->texture,
1305					       0, 0, 0,
1306					       PIPE_TRANSFER_READ,
1307					       srcX, srcY,
1308					       width, height);
1309
1310   if (baseFormat == GL_DEPTH_COMPONENT &&
1311       pf_is_depth_and_stencil(stImage->pt->format))
1312      transfer_usage = PIPE_TRANSFER_READ_WRITE;
1313   else
1314      transfer_usage = PIPE_TRANSFER_WRITE;
1315
1316   st_teximage_flush_before_map(ctx->st, stImage->pt, 0, 0,
1317				transfer_usage);
1318
1319   texDest = st_texture_image_map(ctx->st, stImage, 0, transfer_usage,
1320                                  destX, destY, width, height);
1321
1322   if (baseFormat == GL_DEPTH_COMPONENT ||
1323       baseFormat == GL_DEPTH24_STENCIL8) {
1324      const GLboolean scaleOrBias = (ctx->Pixel.DepthScale != 1.0F ||
1325                                     ctx->Pixel.DepthBias != 0.0F);
1326      GLint row, yStep;
1327
1328      /* determine bottom-to-top vs. top-to-bottom order for src buffer */
1329      if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1330         srcY = height - 1;
1331         yStep = -1;
1332      }
1333      else {
1334         srcY = 0;
1335         yStep = 1;
1336      }
1337
1338      /* To avoid a large temp memory allocation, do copy row by row */
1339      for (row = 0; row < height; row++, srcY += yStep) {
1340         uint data[MAX_WIDTH];
1341         pipe_get_tile_z(src_trans, 0, srcY, width, 1, data);
1342         if (scaleOrBias) {
1343            _mesa_scale_and_bias_depth_uint(ctx, width, data);
1344         }
1345         pipe_put_tile_z(stImage->transfer, 0, row, width, 1, data);
1346      }
1347   }
1348   else {
1349      /* RGBA format */
1350      GLfloat *tempSrc =
1351         (GLfloat *) _mesa_malloc(width * height * 4 * sizeof(GLfloat));
1352
1353      if (tempSrc && texDest) {
1354         const GLint dims = 2;
1355         const GLint dstRowStride = stImage->transfer->stride;
1356         struct gl_texture_image *texImage = &stImage->base;
1357         struct gl_pixelstore_attrib unpack = ctx->DefaultPacking;
1358
1359         if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
1360            unpack.Invert = GL_TRUE;
1361         }
1362
1363         /* get float/RGBA image from framebuffer */
1364         /* XXX this usually involves a lot of int/float conversion.
1365          * try to avoid that someday.
1366          */
1367         pipe_get_tile_rgba(src_trans, 0, 0, width, height, tempSrc);
1368
1369         /* Store into texture memory.
1370          * Note that this does some special things such as pixel transfer
1371          * ops and format conversion.  In particular, if the dest tex format
1372          * is actually RGBA but the user created the texture as GL_RGB we
1373          * need to fill-in/override the alpha channel with 1.0.
1374          */
1375         texImage->TexFormat->StoreImage(ctx, dims,
1376                                         texImage->_BaseFormat,
1377                                         texImage->TexFormat,
1378                                         texDest,
1379                                         0, 0, 0,
1380                                         dstRowStride,
1381                                         texImage->ImageOffsets,
1382                                         width, height, 1,
1383                                         GL_RGBA, GL_FLOAT, tempSrc, /* src */
1384                                         &unpack);
1385      }
1386      else {
1387         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
1388      }
1389
1390      if (tempSrc)
1391         _mesa_free(tempSrc);
1392   }
1393
1394   st_texture_image_unmap(ctx->st, stImage);
1395   screen->tex_transfer_destroy(src_trans);
1396}
1397
1398
1399/**
1400 * Do a CopyTex[Sub]Image1/2/3D() using a hardware (blit) path if possible.
1401 * Note that the region to copy has already been clipped so we know we
1402 * won't read from outside the source renderbuffer's bounds.
1403 *
1404 * Note: srcY=0=Bottom of renderbuffer (GL convention)
1405 */
1406static void
1407st_copy_texsubimage(GLcontext *ctx,
1408                    GLenum target, GLint level,
1409                    GLint destX, GLint destY, GLint destZ,
1410                    GLint srcX, GLint srcY,
1411                    GLsizei width, GLsizei height)
1412{
1413   struct gl_texture_unit *texUnit =
1414      &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
1415   struct gl_texture_object *texObj =
1416      _mesa_select_tex_object(ctx, texUnit, target);
1417   struct gl_texture_image *texImage =
1418      _mesa_select_tex_image(ctx, texObj, target, level);
1419   struct st_texture_image *stImage = st_texture_image(texImage);
1420   const GLenum texBaseFormat = texImage->InternalFormat;
1421   struct gl_framebuffer *fb = ctx->ReadBuffer;
1422   struct st_renderbuffer *strb;
1423   struct pipe_context *pipe = ctx->st->pipe;
1424   struct pipe_screen *screen = pipe->screen;
1425   enum pipe_format dest_format, src_format;
1426   GLboolean use_fallback = GL_TRUE;
1427   GLboolean matching_base_formats;
1428
1429   /* any rendering in progress must flushed before we grab the fb image */
1430   st_flush(ctx->st, PIPE_FLUSH_RENDER_CACHE, NULL);
1431
1432   /* make sure finalize_textures has been called?
1433    */
1434   if (0) st_validate_state(ctx->st);
1435
1436   /* determine if copying depth or color data */
1437   if (texBaseFormat == GL_DEPTH_COMPONENT ||
1438       texBaseFormat == GL_DEPTH24_STENCIL8) {
1439      strb = st_renderbuffer(fb->_DepthBuffer);
1440   }
1441   else if (texBaseFormat == GL_DEPTH_STENCIL_EXT) {
1442      strb = st_renderbuffer(fb->_StencilBuffer);
1443   }
1444   else {
1445      /* texBaseFormat == GL_RGB, GL_RGBA, GL_ALPHA, etc */
1446      strb = st_renderbuffer(fb->_ColorReadBuffer);
1447   }
1448
1449   if (!strb || !strb->surface || !stImage->pt) {
1450      debug_printf("%s: null strb or stImage\n", __FUNCTION__);
1451      return;
1452   }
1453
1454   if (srcX < 0) {
1455      width -= -srcX;
1456      destX += -srcX;
1457      srcX = 0;
1458   }
1459
1460   if (srcY < 0) {
1461      height -= -srcY;
1462      destY += -srcY;
1463      srcY = 0;
1464   }
1465
1466   if (destX < 0) {
1467      width -= -destX;
1468      srcX += -destX;
1469      destX = 0;
1470   }
1471
1472   if (destY < 0) {
1473      height -= -destY;
1474      srcY += -destY;
1475      destY = 0;
1476   }
1477
1478   if (width < 0 || height < 0)
1479      return;
1480
1481
1482   assert(strb);
1483   assert(strb->surface);
1484   assert(stImage->pt);
1485
1486   src_format = strb->surface->format;
1487   dest_format = stImage->pt->format;
1488
1489   /*
1490    * Determine if the src framebuffer and dest texture have the same
1491    * base format.  We need this to detect a case such as the framebuffer
1492    * being GL_RGBA but the texture being GL_RGB.  If the actual hardware
1493    * texture format stores RGBA we need to set A=1 (overriding the
1494    * framebuffer's alpha values).  We can't do that with the blit or
1495    * textured-quad paths.
1496    */
1497   matching_base_formats = (strb->Base._BaseFormat == texImage->_BaseFormat);
1498
1499   if (matching_base_formats && ctx->_ImageTransferState == 0x0) {
1500      /* try potential hardware path */
1501      struct pipe_surface *dest_surface = NULL;
1502      boolean do_flip = (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP);
1503
1504      if (src_format == dest_format && !do_flip) {
1505         /* use surface_copy() / blit */
1506
1507         dest_surface = screen->get_tex_surface(screen, stImage->pt,
1508                                                stImage->face, stImage->level,
1509                                                destZ,
1510                                                PIPE_BUFFER_USAGE_GPU_WRITE);
1511
1512         /* for surface_copy(), y=0=top, always */
1513         pipe->surface_copy(pipe,
1514                            /* dest */
1515                            dest_surface,
1516                            destX, destY,
1517                            /* src */
1518                            strb->surface,
1519                            srcX, srcY,
1520                            /* size */
1521                            width, height);
1522         use_fallback = GL_FALSE;
1523      }
1524      else if (screen->is_format_supported(screen, src_format,
1525                                           PIPE_TEXTURE_2D,
1526                                           PIPE_TEXTURE_USAGE_SAMPLER,
1527                                           0) &&
1528               screen->is_format_supported(screen, dest_format,
1529                                           PIPE_TEXTURE_2D,
1530                                           PIPE_TEXTURE_USAGE_RENDER_TARGET,
1531                                           0)) {
1532         /* draw textured quad to do the copy */
1533         GLint srcY0, srcY1;
1534
1535         dest_surface = screen->get_tex_surface(screen, stImage->pt,
1536                                                stImage->face, stImage->level,
1537                                                destZ,
1538                                                PIPE_BUFFER_USAGE_GPU_WRITE);
1539
1540         if (do_flip) {
1541            srcY1 = strb->Base.Height - srcY - height;
1542            srcY0 = srcY1 + height;
1543         }
1544         else {
1545            srcY0 = srcY;
1546            srcY1 = srcY0 + height;
1547         }
1548         util_blit_pixels(ctx->st->blit,
1549                          strb->surface,
1550                          srcX, srcY0,
1551                          srcX + width, srcY1,
1552                          dest_surface,
1553                          destX, destY,
1554                          destX + width, destY + height,
1555                          0.0, PIPE_TEX_MIPFILTER_NEAREST);
1556         use_fallback = GL_FALSE;
1557      }
1558
1559      if (dest_surface)
1560         pipe_surface_reference(&dest_surface, NULL);
1561   }
1562
1563   if (use_fallback) {
1564      /* software fallback */
1565      fallback_copy_texsubimage(ctx, target, level,
1566                                strb, stImage, texBaseFormat,
1567                                destX, destY, destZ,
1568                                srcX, srcY, width, height);
1569   }
1570
1571   if (level == texObj->BaseLevel && texObj->GenerateMipmap) {
1572      ctx->Driver.GenerateMipmap(ctx, target, texObj);
1573   }
1574}
1575
1576
1577
1578static void
1579st_CopyTexImage1D(GLcontext * ctx, GLenum target, GLint level,
1580                  GLenum internalFormat,
1581                  GLint x, GLint y, GLsizei width, GLint border)
1582{
1583   struct gl_texture_unit *texUnit =
1584      &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
1585   struct gl_texture_object *texObj =
1586      _mesa_select_tex_object(ctx, texUnit, target);
1587   struct gl_texture_image *texImage =
1588      _mesa_select_tex_image(ctx, texObj, target, level);
1589
1590   /* Setup or redefine the texture object, texture and texture
1591    * image.  Don't populate yet.
1592    */
1593   ctx->Driver.TexImage1D(ctx, target, level, internalFormat,
1594                          width, border,
1595                          GL_RGBA, CHAN_TYPE, NULL,
1596                          &ctx->DefaultPacking, texObj, texImage);
1597
1598   st_copy_texsubimage(ctx, target, level,
1599                       0, 0, 0,  /* destX,Y,Z */
1600                       x, y, width, 1);  /* src X, Y, size */
1601}
1602
1603
1604static void
1605st_CopyTexImage2D(GLcontext * ctx, GLenum target, GLint level,
1606                  GLenum internalFormat,
1607                  GLint x, GLint y, GLsizei width, GLsizei height,
1608                  GLint border)
1609{
1610   struct gl_texture_unit *texUnit =
1611      &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
1612   struct gl_texture_object *texObj =
1613      _mesa_select_tex_object(ctx, texUnit, target);
1614   struct gl_texture_image *texImage =
1615      _mesa_select_tex_image(ctx, texObj, target, level);
1616
1617   /* Setup or redefine the texture object, texture and texture
1618    * image.  Don't populate yet.
1619    */
1620   ctx->Driver.TexImage2D(ctx, target, level, internalFormat,
1621                          width, height, border,
1622                          GL_RGBA, CHAN_TYPE, NULL,
1623                          &ctx->DefaultPacking, texObj, texImage);
1624
1625   st_copy_texsubimage(ctx, target, level,
1626                       0, 0, 0,  /* destX,Y,Z */
1627                       x, y, width, height);  /* src X, Y, size */
1628}
1629
1630
1631static void
1632st_CopyTexSubImage1D(GLcontext * ctx, GLenum target, GLint level,
1633                     GLint xoffset, GLint x, GLint y, GLsizei width)
1634{
1635   const GLint yoffset = 0, zoffset = 0;
1636   const GLsizei height = 1;
1637   st_copy_texsubimage(ctx, target, level,
1638                       xoffset, yoffset, zoffset,  /* destX,Y,Z */
1639                       x, y, width, height);  /* src X, Y, size */
1640}
1641
1642
1643static void
1644st_CopyTexSubImage2D(GLcontext * ctx, GLenum target, GLint level,
1645                     GLint xoffset, GLint yoffset,
1646                     GLint x, GLint y, GLsizei width, GLsizei height)
1647{
1648   const GLint zoffset = 0;
1649   st_copy_texsubimage(ctx, target, level,
1650                       xoffset, yoffset, zoffset,  /* destX,Y,Z */
1651                       x, y, width, height);  /* src X, Y, size */
1652}
1653
1654
1655static void
1656st_CopyTexSubImage3D(GLcontext * ctx, GLenum target, GLint level,
1657                     GLint xoffset, GLint yoffset, GLint zoffset,
1658                     GLint x, GLint y, GLsizei width, GLsizei height)
1659{
1660   st_copy_texsubimage(ctx, target, level,
1661                       xoffset, yoffset, zoffset,  /* destX,Y,Z */
1662                       x, y, width, height);  /* src X, Y, size */
1663}
1664
1665
1666/**
1667 * Compute which mipmap levels that really need to be sent to the hardware.
1668 * This depends on the base image size, GL_TEXTURE_MIN_LOD,
1669 * GL_TEXTURE_MAX_LOD, GL_TEXTURE_BASE_LEVEL, and GL_TEXTURE_MAX_LEVEL.
1670 */
1671static void
1672calculate_first_last_level(struct st_texture_object *stObj)
1673{
1674   struct gl_texture_object *tObj = &stObj->base;
1675
1676   /* These must be signed values.  MinLod and MaxLod can be negative numbers,
1677    * and having firstLevel and lastLevel as signed prevents the need for
1678    * extra sign checks.
1679    */
1680   GLint firstLevel;
1681   GLint lastLevel;
1682
1683   /* Yes, this looks overly complicated, but it's all needed.
1684    */
1685   switch (tObj->Target) {
1686   case GL_TEXTURE_1D:
1687   case GL_TEXTURE_2D:
1688   case GL_TEXTURE_3D:
1689   case GL_TEXTURE_CUBE_MAP:
1690      if (tObj->MinFilter == GL_NEAREST || tObj->MinFilter == GL_LINEAR) {
1691         /* GL_NEAREST and GL_LINEAR only care about GL_TEXTURE_BASE_LEVEL.
1692          */
1693         firstLevel = lastLevel = tObj->BaseLevel;
1694      }
1695      else {
1696         firstLevel = 0;
1697         lastLevel = MIN2(tObj->MaxLevel,
1698                          (int) tObj->Image[0][tObj->BaseLevel]->WidthLog2);
1699      }
1700      break;
1701   case GL_TEXTURE_RECTANGLE_NV:
1702   case GL_TEXTURE_4D_SGIS:
1703      firstLevel = lastLevel = 0;
1704      break;
1705   default:
1706      return;
1707   }
1708
1709   stObj->lastLevel = lastLevel;
1710}
1711
1712
1713static void
1714copy_image_data_to_texture(struct st_context *st,
1715			   struct st_texture_object *stObj,
1716                           GLuint dstLevel,
1717			   struct st_texture_image *stImage)
1718{
1719   if (stImage->pt) {
1720      /* Copy potentially with the blitter:
1721       */
1722      st_texture_image_copy(st->pipe,
1723                            stObj->pt, dstLevel,  /* dest texture, level */
1724                            stImage->pt, /* src texture */
1725                            stImage->face
1726                            );
1727
1728      pipe_texture_reference(&stImage->pt, NULL);
1729   }
1730   else if (stImage->base.Data) {
1731      assert(stImage->base.Data != NULL);
1732
1733      /* More straightforward upload.
1734       */
1735
1736      st_teximage_flush_before_map(st, stObj->pt, stImage->face, dstLevel,
1737				   PIPE_TRANSFER_WRITE);
1738
1739
1740      st_texture_image_data(st,
1741                            stObj->pt,
1742                            stImage->face,
1743                            dstLevel,
1744                            stImage->base.Data,
1745                            stImage->base.RowStride *
1746                            stObj->pt->block.size,
1747                            stImage->base.RowStride *
1748                            stImage->base.Height *
1749                            stObj->pt->block.size);
1750      _mesa_align_free(stImage->base.Data);
1751      stImage->base.Data = NULL;
1752   }
1753
1754   pipe_texture_reference(&stImage->pt, stObj->pt);
1755}
1756
1757
1758/**
1759 * Called during state validation.  When this function is finished,
1760 * the texture object should be ready for rendering.
1761 * \return GL_TRUE for success, GL_FALSE for failure (out of mem)
1762 */
1763GLboolean
1764st_finalize_texture(GLcontext *ctx,
1765		    struct pipe_context *pipe,
1766		    struct gl_texture_object *tObj,
1767		    GLboolean *needFlush)
1768{
1769   struct st_texture_object *stObj = st_texture_object(tObj);
1770   const GLuint nr_faces = (stObj->base.Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
1771   GLuint cpp, face;
1772   struct st_texture_image *firstImage;
1773
1774   *needFlush = GL_FALSE;
1775
1776   /* We know/require this is true by now:
1777    */
1778   assert(stObj->base._Complete);
1779
1780   /* What levels must the texture include at a minimum?
1781    */
1782   calculate_first_last_level(stObj);
1783   firstImage = st_texture_image(stObj->base.Image[0][stObj->base.BaseLevel]);
1784
1785   /* If both firstImage and stObj point to a texture which can contain
1786    * all active images, favour firstImage.  Note that because of the
1787    * completeness requirement, we know that the image dimensions
1788    * will match.
1789    */
1790   if (firstImage->pt &&
1791       firstImage->pt != stObj->pt &&
1792       firstImage->pt->last_level >= stObj->lastLevel) {
1793      pipe_texture_reference(&stObj->pt, firstImage->pt);
1794   }
1795
1796   /* FIXME: determine format block instead of cpp */
1797   if (firstImage->base.IsCompressed) {
1798      cpp = compressed_num_bytes(firstImage->base.TexFormat->MesaFormat);
1799   }
1800   else {
1801      cpp = firstImage->base.TexFormat->TexelBytes;
1802   }
1803
1804   /* If we already have a gallium texture, check that it matches the texture
1805    * object's format, target, size, num_levels, etc.
1806    */
1807   if (stObj->pt) {
1808      const enum pipe_format fmt =
1809         st_mesa_format_to_pipe_format(firstImage->base.TexFormat->MesaFormat);
1810      if (stObj->pt->target != gl_target_to_pipe(stObj->base.Target) ||
1811          stObj->pt->format != fmt ||
1812          stObj->pt->last_level < stObj->lastLevel ||
1813          stObj->pt->width[0] != firstImage->base.Width2 ||
1814          stObj->pt->height[0] != firstImage->base.Height2 ||
1815          stObj->pt->depth[0] != firstImage->base.Depth2 ||
1816          /* Nominal bytes per pixel: */
1817          stObj->pt->block.size / stObj->pt->block.width != cpp)
1818      {
1819         pipe_texture_reference(&stObj->pt, NULL);
1820         ctx->st->dirty.st |= ST_NEW_FRAMEBUFFER;
1821      }
1822   }
1823
1824   /* May need to create a new gallium texture:
1825    */
1826   if (!stObj->pt) {
1827      const enum pipe_format fmt =
1828         st_mesa_format_to_pipe_format(firstImage->base.TexFormat->MesaFormat);
1829      GLuint usage = default_usage(fmt);
1830
1831      stObj->pt = st_texture_create(ctx->st,
1832                                    gl_target_to_pipe(stObj->base.Target),
1833                                    fmt,
1834                                    stObj->lastLevel,
1835                                    firstImage->base.Width2,
1836                                    firstImage->base.Height2,
1837                                    firstImage->base.Depth2,
1838                                    usage);
1839
1840      if (!stObj->pt) {
1841         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
1842         return GL_FALSE;
1843      }
1844   }
1845
1846   /* Pull in any images not in the object's texture:
1847    */
1848   for (face = 0; face < nr_faces; face++) {
1849      GLuint level;
1850      for (level = 0; level <= stObj->lastLevel; level++) {
1851         struct st_texture_image *stImage =
1852            st_texture_image(stObj->base.Image[face][stObj->base.BaseLevel + level]);
1853
1854         /* Need to import images in main memory or held in other textures.
1855          */
1856         if (stImage && stObj->pt != stImage->pt) {
1857            copy_image_data_to_texture(ctx->st, stObj, level, stImage);
1858	    *needFlush = GL_TRUE;
1859         }
1860      }
1861   }
1862
1863   return GL_TRUE;
1864}
1865
1866
1867/**
1868 * Returns pointer to a default/dummy texture.
1869 * This is typically used when the current shader has tex/sample instructions
1870 * but the user has not provided a (any) texture(s).
1871 */
1872struct gl_texture_object *
1873st_get_default_texture(struct st_context *st)
1874{
1875   if (!st->default_texture) {
1876      static const GLenum target = GL_TEXTURE_2D;
1877      GLubyte pixels[16][16][4];
1878      struct gl_texture_object *texObj;
1879      struct gl_texture_image *texImg;
1880      GLuint i, j;
1881
1882      /* The ARB_fragment_program spec says (0,0,0,1) should be returned
1883       * when attempting to sample incomplete textures.
1884       */
1885      for (i = 0; i < 16; i++) {
1886         for (j = 0; j < 16; j++) {
1887            pixels[i][j][0] = 0;
1888            pixels[i][j][1] = 0;
1889            pixels[i][j][2] = 0;
1890            pixels[i][j][3] = 255;
1891         }
1892      }
1893
1894      texObj = st->ctx->Driver.NewTextureObject(st->ctx, 0, target);
1895
1896      texImg = _mesa_get_tex_image(st->ctx, texObj, target, 0);
1897
1898      _mesa_init_teximage_fields(st->ctx, target, texImg,
1899                                 16, 16, 1, 0,  /* w, h, d, border */
1900                                 GL_RGBA);
1901
1902      st_TexImage(st->ctx, 2, target,
1903                  0, GL_RGBA,    /* level, intformat */
1904                  16, 16, 1, 0,  /* w, h, d, border */
1905                  GL_RGBA, GL_UNSIGNED_BYTE, pixels,
1906                  &st->ctx->DefaultPacking,
1907                  texObj, texImg,
1908                  0, 0);
1909
1910      texObj->MinFilter = GL_NEAREST;
1911      texObj->MagFilter = GL_NEAREST;
1912      texObj->_Complete = GL_TRUE;
1913
1914      st->default_texture = texObj;
1915   }
1916   return st->default_texture;
1917}
1918
1919
1920void
1921st_init_texture_functions(struct dd_function_table *functions)
1922{
1923   functions->ChooseTextureFormat = st_ChooseTextureFormat;
1924   functions->TexImage1D = st_TexImage1D;
1925   functions->TexImage2D = st_TexImage2D;
1926   functions->TexImage3D = st_TexImage3D;
1927   functions->TexSubImage1D = st_TexSubImage1D;
1928   functions->TexSubImage2D = st_TexSubImage2D;
1929   functions->TexSubImage3D = st_TexSubImage3D;
1930   functions->CompressedTexSubImage1D = st_CompressedTexSubImage1D;
1931   functions->CompressedTexSubImage2D = st_CompressedTexSubImage2D;
1932   functions->CompressedTexSubImage3D = st_CompressedTexSubImage3D;
1933   functions->CopyTexImage1D = st_CopyTexImage1D;
1934   functions->CopyTexImage2D = st_CopyTexImage2D;
1935   functions->CopyTexSubImage1D = st_CopyTexSubImage1D;
1936   functions->CopyTexSubImage2D = st_CopyTexSubImage2D;
1937   functions->CopyTexSubImage3D = st_CopyTexSubImage3D;
1938   functions->GenerateMipmap = st_generate_mipmap;
1939
1940   functions->GetTexImage = st_GetTexImage;
1941
1942   /* compressed texture functions */
1943   functions->CompressedTexImage2D = st_CompressedTexImage2D;
1944   functions->GetCompressedTexImage = st_GetCompressedTexImage;
1945   functions->CompressedTextureSize = _mesa_compressed_texture_size;
1946
1947   functions->NewTextureObject = st_NewTextureObject;
1948   functions->NewTextureImage = st_NewTextureImage;
1949   functions->DeleteTexture = st_DeleteTextureObject;
1950   functions->FreeTexImageData = st_FreeTextureImageData;
1951   functions->UpdateTexturePalette = 0;
1952
1953   functions->TextureMemCpy = do_memcpy;
1954
1955   /* XXX Temporary until we can query pipe's texture sizes */
1956   functions->TestProxyTexImage = _mesa_test_proxy_teximage;
1957}
1958