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